From 000d39b0421225e3382b3b6b30b52196990caf24 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 02:33:38 -0700 Subject: [PATCH 001/102] M4: closed vectors take corner smoothing A vector's corner smoothing was stored, imported and exported, but its rounded points were drawn as plain circular arcs, and the Design panel hid the Corner smoothing control for vectors. A vector with a closed region now draws its rounded points with the layer's corner smoothing, on the canvas, in hit testing, in PNG, SVG and PDF exports, and in the fill and stroke geometry of .fig exports. Each point keeps its own radius; a point without one stays sharp. The corner uses the profile of smoothed polygon corners, and smoothing is reduced before the radius when a corner does not fit in half of each segment. FigCraft's own rules for cases the help page does not describe: only a point between two straight segments that both bound a closed region is smoothed; points on open branches and points next to a curved segment keep the plain arc; concave corners are smoothed like convex ones. The Design panel shows Corner smoothing and its iOS (60%) button for vectors with a closed region, and not for open paths. --- crates/doc/src/geometry.rs | 21 ++- crates/doc/src/node.rs | 8 +- crates/doc/src/tests.rs | 122 +++++++++++++ crates/doc/src/vector.rs | 101 ++++++++--- crates/engine/src/canvas/shapebuilder.rs | 4 +- .../engine/src/canvas/vectoredit/regions.rs | 14 +- crates/engine/src/shapes_behaviour_tests.rs | 51 +++++- crates/format/src/fig/export/common.rs | 4 +- crates/format/src/fig/export/shape.rs | 4 +- crates/format/src/fig/export_tests.rs | 43 +++++ crates/geom/src/lib.rs | 168 ++++++++++++------ crates/geom/src/tests.rs | 47 +++++ crates/pdf/src/draw.rs | 4 +- crates/pdf/src/tests.rs | 21 +++ crates/render/src/draw.rs | 14 +- crates/svg/src/lib.rs | 4 +- crates/ui-egui/src/corner_individual_tests.rs | 33 ++++ crates/ui-egui/src/panels/right/paints.rs | 2 +- docs/gaps.md | 4 +- docs/target-app-parity.md | 2 +- 20 files changed, 559 insertions(+), 112 deletions(-) diff --git a/crates/doc/src/geometry.rs b/crates/doc/src/geometry.rs index 0e06d2941..3dbbce6d4 100644 --- a/crates/doc/src/geometry.rs +++ b/crates/doc/src/geometry.rs @@ -28,8 +28,9 @@ pub fn shape_path(n: &Node) -> Option { p } NodeKind::Vector { network } => { - let f = network.fill_path(); - if f.elements().is_empty() { network.stroke_path() } else { f } + let net = drawn_network(network, c.smoothing); + let f = net.fill_path(); + if f.elements().is_empty() { net.stroke_path() } else { f } } NodeKind::Text(_) => figcraft_geom::rounded_rect(w, h, [0.0; 4], 0.0), NodeKind::Page { .. } | NodeKind::Group | NodeKind::BooleanOp { .. } => return None, @@ -39,11 +40,21 @@ pub fn shape_path(n: &Node) -> Option { /// The open/closed path strokes follow (vector networks stroke every segment, filled or not). pub fn stroke_geometry(n: &Node) -> Option { match &n.kind { - NodeKind::Vector { network } => Some(network.stroke_path()), + NodeKind::Vector { network } => Some(drawn_network(network, n.corners.smoothing).stroke_path()), _ => shape_path(n), } } +/// A vector's `network` as the layer draws it: rounded points drawn in with the layer's corner +/// `smoothing` (see [`VectorNetwork::rounded_smoothed`](crate::VectorNetwork::rounded_smoothed)), +/// or the network itself when no point is rounded. +pub fn drawn_network(network: &crate::VectorNetwork, smoothing: f64) -> std::borrow::Cow<'_, crate::VectorNetwork> { + match network.rounded_smoothed(smoothing) { + Some(r) => std::borrow::Cow::Owned(r), + None => std::borrow::Cow::Borrowed(network), + } +} + /// Whether the shape's path is closed (fills apply). pub fn is_closed(n: &Node) -> bool { match &n.kind { @@ -75,8 +86,8 @@ fn hits_node_itself(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, o n.local_rect().inflate(tol_l, tol_l).contains(lp) } NodeKind::Vector { network } if network.regions.iter().any(|r| r.fills.is_some() || r.paint_space.is_some()) => { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); + let drawn = drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); if !outline { for (i, region) in net.regions.iter().enumerate().rev() { let paints = region.fills.as_deref().unwrap_or(&n.fills); diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 6ec7e8245..21241cf0f 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -416,9 +416,13 @@ impl NodeKind { self.has_corner_radius() && !matches!(self, NodeKind::Polygon { .. } | NodeKind::Star { .. } | NodeKind::Vector { .. }) } - /// Kinds whose rounded corners are drawn with corner smoothing (a vector's rounded points are drawn without it). + /// Kinds whose rounded corners are drawn with corner smoothing: a vector only when its network + /// has a closed region (an open path's rounded points are drawn without it). pub fn has_corner_smoothing(&self) -> bool { - self.has_corner_radius() && !matches!(self, NodeKind::Vector { .. }) + match self { + NodeKind::Vector { network } => !network.regions.is_empty(), + _ => self.has_corner_radius(), + } } pub fn text(&self) -> Option<&TextData> { diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index a0e3e17b0..2eb912f45 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -665,6 +665,128 @@ fn two_segment_closed_loop_rounded_corners() { assert_eq!(r.regions[0].loops[0].len(), 4, "both arcs are in the loop"); let path = net.fill_path(); assert!(!path.elements().is_empty()); + // Both points sit next to the curved segment, so smoothing keeps their plain arcs. + assert_eq!(net.rounded_smoothed(0.6), net.rounded(), "a corner next to a curve keeps the plain arc"); +} + +/// A closed 100 × 100 square whose corners (top left, top right, bottom right, bottom left) have +/// radii `radii`. +fn rounded_square(radii: [f64; 4]) -> VectorNetwork { + let pts = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)]; + let mut net = VectorNetwork::from_points(&pts, true); + for (v, r) in net.vertices.iter_mut().zip(radii) { + v.radius = r; + } + net +} + +/// The area a closed path encloses, whichever way it runs. +fn area_of(p: &figcraft_geom::BezPath) -> f64 { + use figcraft_geom::Shape; + p.area().abs() +} + +#[test] +fn closed_vectors_smooth_each_rounded_point_with_its_own_radius() { + use figcraft_geom::Shape; + use figcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest}; + // (point radii, smoothing, derivation): a closed square draws the smoothed rectangle's corners, + // each point keeping its own radius and a point without one staying sharp. + let rows: Vec<([f64; 4], f64, &str)> = vec![ + ([20.0; 4], 0.6, "one radius on every point"), + ([30.0, 0.0, 10.0, 0.0], 0.6, "each point keeps its own radius; points without one stay sharp"), + ([12.0; 4], 1.0, "full smoothing"), + ([40.0; 4], 0.6, "a corner too large for its edges loses smoothing first"), + ]; + for (radii, s, why) in rows { + let net = rounded_square(radii); + let smoothed = net.rounded_smoothed(s).unwrap().fill_path(); + // The rectangle's corners take [top left, top right, bottom right, bottom left] radii. + let want = area_of(&figcraft_geom::rounded_rect(100.0, 100.0, radii, s)); + let got = area_of(&smoothed); + assert!((got - want).abs() < 0.1, "{why}: {got} vs the smoothed rectangle's {want}"); + assert!((got - area_of(&net.fill_path())).abs() > 1.0, "{why}: smoothing changes the outline"); + let b = smoothed.bounding_box(); + assert!(b.x0 >= -1e-6 && b.y0 >= -1e-6 && b.x1 <= 100.0 + 1e-6 && b.y1 <= 100.0 + 1e-6, "{why}: {b:?}"); + } + // The sharp points stay on the outline, and the outline has no kinks at the rounded points. + let smoothed = rounded_square([30.0, 0.0, 10.0, 0.0]).rounded_smoothed(0.6).unwrap(); + let path = smoothed.fill_path(); + for p in [Point::new(100.0, 0.0), Point::new(0.0, 100.0)] { + let d = path.segments().map(|seg| seg.nearest(p, 1e-9).distance_sq).fold(f64::INFINITY, f64::min); + assert!(d < 1e-12, "the sharp point {p:?} stays a corner"); + } + let segs: Vec<_> = path.segments().filter(|seg| seg.arclen(1e-6) > 1e-6).collect(); + let mut kinks = 0; + for (i, seg) in segs.iter().enumerate() { + let next = segs[(i + 1) % segs.len()]; + let out = (seg.eval(1.0) - seg.eval(1.0 - 1e-6)).normalize(); + let into = (next.eval(1e-6) - next.eval(0.0)).normalize(); + if out.dot(into) < 0.999 { + kinks += 1; + } + } + assert_eq!(kinks, 2, "only the two sharp points turn without a curve"); + assert_eq!(smoothed.regions[0].loops[0].len(), smoothed.segments.len(), "the loop walks every curve once"); +} + +#[test] +fn corner_smoothing_leaves_open_paths_and_zero_alone() { + let square = rounded_square([20.0; 4]); + assert_eq!(square.rounded_smoothed(0.0), square.rounded(), "no smoothing draws the plain rounded points"); + assert_eq!(square.rounded_smoothed(f64::NAN), square.rounded(), "an unusable smoothing draws no smoothing"); + // An open path (no closed region) keeps its plain arcs. + let pts = [Point::new(200.0, 0.0), Point::new(250.0, 0.0), Point::new(250.0, 50.0)]; + let mut open = VectorNetwork::from_points(&pts, false); + for v in &mut open.vertices { + v.radius = 20.0; + } + assert!(open.regions.is_empty()); + assert_eq!(open.rounded_smoothed(0.6), open.rounded(), "an open path takes no smoothing"); + // In a network with a closed square and a separate open branch, only the square smooths. + let mut mixed = square.clone(); + let base = mixed.vertices.len(); + mixed.vertices.extend(open.vertices.iter().copied()); + mixed.segments.extend(open.segments.iter().map(|s| Segment { a: s.a + base, b: s.b + base, ..*s })); + let runs = mixed.rounded_smoothed(0.6).unwrap().stroke_runs(); + let open_run = runs.iter().find(|r| !r.closed).expect("the open branch"); + assert_eq!(open_run.path, open.rounded().unwrap().stroke_runs()[0].path, "the open branch keeps its plain arc"); + let closed_run = runs.iter().find(|r| r.closed).expect("the square"); + assert_eq!(closed_run.path, square.rounded_smoothed(0.6).unwrap().stroke_runs()[0].path, "the square smooths"); + assert_ne!(closed_run.path, square.rounded().unwrap().stroke_runs()[0].path, "the square's smoothed corners differ from its arcs"); +} + +#[test] +fn smoothed_vector_corners_stay_finite_on_awkward_networks() { + use figcraft_geom::Shape; + // A concave L, a square with a square hole, points with unusable radii and a loop that names a + // missing segment. + let l = [(0.0, 0.0), (100.0, 0.0), (100.0, 40.0), (40.0, 40.0), (40.0, 100.0), (0.0, 100.0)]; + let mut concave = VectorNetwork::from_points(&l.map(|(x, y)| Point::new(x, y)), true); + for v in &mut concave.vertices { + v.radius = 1000.0; + } + let mut holed = rounded_square([10.0; 4]); + let hole = rounded_square([5.0; 4]); + let (base, seg_base) = (holed.vertices.len(), holed.segments.len()); + holed.vertices.extend(hole.vertices.iter().map(|v| Vertex { x: 25.0 + v.x / 2.0, y: 25.0 + v.y / 2.0, ..*v })); + holed.segments.extend(hole.segments.iter().map(|s| Segment { a: s.a + base, b: s.b + base, ..*s })); + holed.regions[0].loops.push((seg_base..seg_base + hole.segments.len()).collect()); + holed.regions[0].winding = WindingRule::EvenOdd; + let mut odd = rounded_square([f64::INFINITY, 10.0, f64::NAN, 10.0]); + odd.regions[0].loops[0].push(99); + for (net, s, why) in [(&concave, 1.0, "concave"), (&holed, 0.6, "holed"), (&odd, 0.6, "odd radii")] { + let drawn = net.rounded_smoothed(s).unwrap(); + let b = drawn.fill_path().bounding_box(); + assert!([b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()), "{why}: {b:?}"); + assert!(b.x0 >= -1e-6 && b.y0 >= -1e-6 && b.x1 <= 100.0 + 1e-6 && b.y1 <= 100.0 + 1e-6, "{why}: {b:?}"); + assert!(!drawn.stroke_path().elements().is_empty(), "{why}"); + } + let concave_path = concave.rounded_smoothed(1.0).unwrap().fill_path(); + assert_ne!(concave_path, concave.fill_path(), "the concave L smooths"); + assert!(concave_path.winding(Point::new(20.0, 60.0)) != 0, "the L stays filled"); + let holed_net = holed.rounded_smoothed(0.6).unwrap(); + assert!(!holed_net.fill_contains(Point::new(50.0, 50.0)) && holed_net.fill_contains(Point::new(12.0, 50.0)), "the hole stays a hole"); } #[test] diff --git a/crates/doc/src/vector.rs b/crates/doc/src/vector.rs index 5ae01a089..f53ad4408 100644 --- a/crates/doc/src/vector.rs +++ b/crates/doc/src/vector.rs @@ -129,9 +129,10 @@ impl Region { } } -/// A rounded point as drawn: point `v` moves to `a` (on segment `s1`), segment `s2` starts again -/// at `b`, and an arc with handles `ta`/`tb` joins them. `cut1`/`cut2`: where each segment is cut, -/// in its own parameter (curved segments keep the rest of their curve). +/// A rounded point as drawn: point `v` moves to `a` (on segment `s1`), and the curves of `chain` +/// lead from there to where segment `s2` starts again (one arc, or a smoothed corner's easing +/// curves and arc). `cut1`/`cut2`: where each segment is cut, in its own parameter (curved +/// segments keep the rest of their curve). struct Corner { v: usize, s1: usize, @@ -139,13 +140,19 @@ struct Corner { s2: usize, s2_at_a: bool, a: Point, - b: Point, - ta: (f64, f64), - tb: (f64, f64), + chain: Vec, cut1: f64, cut2: f64, } +/// One curve of a rounded point: its handles at its start (`ta`) and its end (`tb`), relative to +/// those ends, and the point it ends at. +struct CornerCurve { + ta: (f64, f64), + tb: (f64, f64), + end: Point, +} + /// Accuracy of arc lengths along curved segments (local units). const ARCLEN_ACC: f64 = 1e-6; @@ -382,9 +389,19 @@ impl VectorNetwork { /// the rest of its curve, the arc leaving along its direction there. `None` when no point is /// rounded. pub fn rounded(&self) -> Option { + self.rounded_smoothed(0.0) + } + + /// [`Self::rounded`] with the layer's corner smoothing (0..=1): a rounded point between two + /// straight segments that both belong to a region's loops gets a smoothed corner, drawn with + /// the profile of a smoothed polygon's corners (`figcraft_geom::smoothed_corner`). Other + /// rounded points (on open branches, or next to a curved segment) keep the plain arc, and a + /// point without a radius stays sharp. Without smoothing this is [`Self::rounded`]. + pub fn rounded_smoothed(&self, smoothing: f64) -> Option { if !self.vertices.iter().any(|v| v.radius > 0.0) { return None; } + let smoothing = if smoothing.is_finite() { smoothing.clamp(0.0, 1.0) } else { 0.0 }; let mut incident: Vec> = vec![Vec::new(); self.vertices.len()]; for (i, s) in self.segments.iter().enumerate() { for (v, at_a) in [(s.a, true), (s.b, false)] { @@ -393,7 +410,14 @@ impl VectorNetwork { } } } - let corners: Vec = (0..self.vertices.len()).filter_map(|v| self.corner(v, incident.get(v)?)).collect(); + // The segments that bound a closed region, where corners take smoothing. + let mut on_loop = vec![false; if smoothing > 0.0 { self.segments.len() } else { 0 }]; + for &i in self.regions.iter().flat_map(|r| r.loops.iter().flatten()) { + if let Some(x) = on_loop.get_mut(i) { + *x = true; + } + } + let corners: Vec = (0..self.vertices.len()).filter_map(|v| self.corner(v, incident.get(v)?, smoothing, &on_loop)).collect(); let mut out = self.clone(); for v in &mut out.vertices { v.radius = 0.0; @@ -420,26 +444,33 @@ impl VectorNetwork { s.ta = (q.p1.x - q.p0.x, q.p1.y - q.p0.y); s.tb = (q.p2.x - q.p3.x, q.p2.y - q.p3.y); } - let mut by_vertex: std::collections::BTreeMap = std::collections::BTreeMap::new(); + // Each rounded point's curves in order from `s1`'s side, by point. + let mut by_vertex: std::collections::BTreeMap)> = std::collections::BTreeMap::new(); for c in corners { if let Some(v) = out.vertices.get_mut(c.v) { (v.x, v.y) = (c.a.x, c.a.y); } - out.vertices.push(Vertex::new(c.b.x, c.b.y)); - let nb = out.vertices.len() - 1; + let mut from = c.v; + let mut arcs = Vec::with_capacity(c.chain.len()); + for CornerCurve { ta, tb, end } in c.chain { + out.vertices.push(Vertex::new(end.x, end.y)); + let to = out.vertices.len() - 1; + out.segments.push(Segment { a: from, b: to, ta, tb }); + arcs.push(out.segments.len() - 1); + from = to; + } if let Some(s) = out.segments.get_mut(c.s2) { if c.s2_at_a { - s.a = nb; + s.a = from; } else { - s.b = nb; + s.b = from; } } - out.segments.push(Segment { a: c.v, b: nb, ta: c.ta, tb: c.tb }); - let arc = out.segments.len() - 1; - by_vertex.insert(c.v, arc); + by_vertex.insert(c.v, (c.s1, arcs)); } - // The arc goes between the two segments wherever a loop walks through the point. Each loop - // is rebuilt in one pass, so a polygon with many rounded corners isn't quadratic. + // The curves go between the two segments wherever a loop walks through the point, in the + // order the loop meets them. Each loop is rebuilt in one pass, so a polygon with many + // rounded corners isn't quadratic. for lp in out.regions.iter_mut().flat_map(|r| r.loops.iter_mut()) { let Some(&first_idx) = lp.first() else { continue }; let start_v = match (self.segments.get(first_idx), lp.get(1).and_then(|&i| self.segments.get(i))) { @@ -453,8 +484,12 @@ impl VectorNetwork { rebuilt.push(x); let Some(s) = self.segments.get(x) else { continue }; cur = if s.a == cur { s.b } else { s.a }; - if let Some(&arc) = by_vertex.get(&cur) { - rebuilt.push(arc); + if let Some((s1, arcs)) = by_vertex.get(&cur) { + if x == *s1 { + rebuilt.extend(arcs.iter().copied()); + } else { + rebuilt.extend(arcs.iter().rev().copied()); + } } } *lp = rebuilt; @@ -463,8 +498,9 @@ impl VectorNetwork { } /// How point `v` (its `incident` segments) is rounded, if it is: not where the two segments - /// run on smoothly or fold back. - fn corner(&self, v: usize, incident: &[(usize, bool)]) -> Option { + /// run on smoothly or fold back. With `smoothing`, a point between two straight segments that + /// are both `on_loop` gets a smoothed corner. + fn corner(&self, v: usize, incident: &[(usize, bool)], smoothing: f64, on_loop: &[bool]) -> Option { let r = self.vertices.get(v)?.radius; let [(s1, a1), (s2, a2)] = *incident else { return None }; if !(r > 0.0 && r.is_finite()) || s1 == s2 { @@ -480,6 +516,24 @@ impl VectorNetwork { if !(l1 > 1e-9 && l2 > 1e-9) { return None; } + let own = |at_a: bool, t: f64| if at_a { t } else { 1.0 - t }; + let closed = |s: usize| on_loop.get(s).copied().unwrap_or(false); + if smoothing > 0.0 + && is_line(&c1) + && is_line(&c2) + && closed(s1) + && closed(s2) + && let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, l1.min(l2) / 2.0, r, smoothing) + && let (Some(first), Some(last)) = (curves.first(), curves.last()) + { + let (a, b) = (first.p0, last.p3); + let chain = curves + .iter() + .map(|q| CornerCurve { ta: (q.p1.x - q.p0.x, q.p1.y - q.p0.y), tb: (q.p2.x - q.p3.x, q.p2.y - q.p3.y), end: q.p3 }) + .collect(); + let (cut1, cut2) = ((a - c1.p0).hypot() / l1, (b - c2.p0).hypot() / l2); + return Some(Corner { v, s1, s1_at_a: a1, s2, s2_at_a: a2, a, chain, cut1: own(a1, cut1), cut2: own(a2, cut2) }); + } let t = (r / (angle / 2.0).tan()).min(l1.min(l2) / 2.0); let ((a, d1, k1), (b, d2, k2)) = (trim(&c1, t, l1), trim(&c2, t, l2)); // A cubic arc: handles of 4/3·tan(φ/4)·ρ along each end's direction, φ the turn between @@ -490,7 +544,6 @@ impl VectorNetwork { if !(k.is_finite() && a.x.is_finite() && a.y.is_finite() && b.x.is_finite() && b.y.is_finite()) { return None; } - let own = |at_a: bool, t: f64| if at_a { t } else { 1.0 - t }; Some(Corner { v, s1, @@ -498,9 +551,7 @@ impl VectorNetwork { s2, s2_at_a: a2, a, - b, - ta: (d1.x * k, d1.y * k), - tb: (d2.x * k, d2.y * k), + chain: vec![CornerCurve { ta: (d1.x * k, d1.y * k), tb: (d2.x * k, d2.y * k), end: b }], cut1: own(a1, k1), cut2: own(a2, k2), }) diff --git a/crates/engine/src/canvas/shapebuilder.rs b/crates/engine/src/canvas/shapebuilder.rs index b68f1e71d..4e6981f14 100644 --- a/crates/engine/src/canvas/shapebuilder.rs +++ b/crates/engine/src/canvas/shapebuilder.rs @@ -132,8 +132,8 @@ fn world_area(doc: &Document, part: Part) -> Option<(BezPath, bool)> { } match (&n.kind, part.region) { (NodeKind::Vector { network }, Some(i)) => { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); + let drawn = figcraft_doc::geometry::drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); let region = net.regions.get(i)?; let path = net.region_path(i)?; (path, if region.winding == WindingRule::EvenOdd { figcraft_render::FillRule::EvenOdd } else { figcraft_render::FillRule::Winding }) diff --git a/crates/engine/src/canvas/vectoredit/regions.rs b/crates/engine/src/canvas/vectoredit/regions.rs index 91763d3aa..6351ce824 100644 --- a/crates/engine/src/canvas/vectoredit/regions.rs +++ b/crates/engine/src/canvas/vectoredit/regions.rs @@ -56,12 +56,10 @@ fn region_filled(n: &figcraft_doc::Node, net: &VectorNetwork, i: usize) -> bool net.regions.get(i).is_some_and(|r| r.fills.as_deref().unwrap_or(&n.fills).iter().any(|f| f.visible)) } -/// The network as its fill draws it: rounded points drawn in (region indexes are kept). -fn drawn(net: &VectorNetwork) -> std::borrow::Cow<'_, VectorNetwork> { - match net.rounded() { - Some(r) => std::borrow::Cow::Owned(r), - None => std::borrow::Cow::Borrowed(net), - } +/// The network as its fill draws it: rounded points drawn in with the layer's corner `smoothing` +/// (region indexes are kept). +fn drawn(net: &VectorNetwork, smoothing: f64) -> std::borrow::Cow<'_, VectorNetwork> { + figcraft_doc::geometry::drawn_network(net, smoothing) } /// The region of the active layer under page point `p` at `zoom`: none when a point is within @@ -90,7 +88,7 @@ pub fn region_hit(doc: &Document, ve: &VectorEdit, p: Point, zoom: f64) -> Optio if (0..net.segments.len()).filter_map(|i| net.cubic(i)).any(|c| c.nearest(lp, 0.01).distance_sq.sqrt() <= sc) { return None; } - let drawn = drawn(net); + let drawn = drawn(net, node.corners.smoothing); (0..drawn.regions.len()).rev().find(|i| region_filled(node, &drawn, *i) && drawn.region_contains(*i, lp)) } @@ -221,7 +219,7 @@ pub fn region_hatch(doc: &Document, ve: &VectorEdit, regions: &[usize], view: Af let zoom = view.determinant().abs().sqrt(); let Some(spacing) = hatch_spacing(zoom).filter(|_| !regions.is_empty()) else { return Vec::new() }; let Some(net) = network(doc, ve.id) else { return Vec::new() }; - let net = drawn(net); + let net = drawn(net, doc.node(ve.id).map_or(0.0, |n| n.corners.smoothing)); let m = view * doc.world_transform(ve.id); let anchor = m * Point::ZERO; let mut out = Vec::new(); diff --git a/crates/engine/src/shapes_behaviour_tests.rs b/crates/engine/src/shapes_behaviour_tests.rs index e628e1683..ca2d16390 100644 --- a/crates/engine/src/shapes_behaviour_tests.rs +++ b/crates/engine/src/shapes_behaviour_tests.rs @@ -233,7 +233,14 @@ fn corner_smoothing_follows_the_documented_rules() { (NodeKind::Frame, true, "frames"), (NodeKind::Polygon { count: 5 }, true, "polygons"), (NodeKind::Star { count: 5, inner_ratio: 0.4 }, true, "stars"), - (NodeKind::Vector { network: Default::default() }, false, "documented for closed vectors; their points round without it here"), + ( + NodeKind::Vector { + network: figcraft_doc::VectorNetwork::from_points(&[Point::ZERO, Point::new(10.0, 0.0), Point::new(10.0, 10.0)], true), + }, + true, + "vector networks that are closed shapes", + ), + (NodeKind::Vector { network: Default::default() }, false, "an open vector has no closed shape to smooth"), (NodeKind::Line, false, "lines take no radius, so no smoothing"), ]; for (kind, smoothing, why) in doc_rows { @@ -241,6 +248,48 @@ fn corner_smoothing_follows_the_documented_rules() { } } +#[test] +fn closed_vectors_take_corner_smoothing() { + // "Vector networks that are closed shapes" take corner smoothing, which applies to the entire + // shape; a single open stroke does not. + let mut s = Session::new(); + let closed = create(&mut s, "vector.create", json!({"points": [[0, 0], [100, 0], [100, 100], [0, 100]], "closed": true})); + let open = create(&mut s, "vector.create", json!({"points": [[200, 0], [300, 0], [300, 100]], "closed": false})); + ex(&mut s, "node.set", json!({"ids": [closed, open], "props": {"cornerRadius": 20}})); + let outline = |s: &Session, id: NodeId| figcraft_doc::geometry::shape_path(&node(s, id)).unwrap(); + let svg = |s: &Session, id: NodeId| figcraft_svg::export_svg(s.doc().unwrap(), &[id], &figcraft_svg::SvgOptions::default()).unwrap(); + let render = |s: &Session, id: NodeId| figcraft_render::node_outline(s.doc().unwrap(), &node(s, id)).unwrap().0; + let (round, open_round, svg_round, drawn_round) = (outline(&s, closed), outline(&s, open), svg(&s, closed), render(&s, closed)); + ex(&mut s, "node.set", json!({"ids": [closed, open], "props": {"cornerSmoothing": 0.6}})); + let smooth = outline(&s, closed); + // The smoothed corner reaches 1.6 radii along each edge, as a smoothed rectangle's does. + let want = figcraft_geom::rounded_rect(100.0, 100.0, [20.0; 4], 0.6).area().abs(); + assert!((smooth.area().abs() - want).abs() < 0.1, "the closed vector smooths: {} vs {want}", smooth.area().abs()); + assert!((smooth.area().abs() - round.area().abs()).abs() > 1.0, "smoothing changes the closed vector's outline"); + assert_ne!(svg(&s, closed), svg_round, "SVG export draws the smoothed corners"); + assert_ne!(render(&s, closed), drawn_round, "the canvas draws the smoothed corners"); + assert_eq!(outline(&s, open), open_round, "an open vector keeps its plain rounded points"); + let stroke = figcraft_doc::geometry::stroke_geometry(&node(&s, closed)).unwrap(); + assert!((stroke.area().abs() - want).abs() < 0.1, "the stroke follows the smoothed outline"); + // Smoothing needs a radius, and undo restores the plain corners in one step. + s.undo().unwrap(); + assert_eq!(outline(&s, closed), round, "one undo step"); + ex(&mut s, "node.set", json!({"ids": [closed], "props": {"cornerRadius": 0}})); + let sharp = outline(&s, closed); + ex(&mut s, "node.set", json!({"ids": [closed], "props": {"cornerSmoothing": 0.6}})); + assert_eq!(outline(&s, closed), sharp, "smoothing needs a radius"); + // A vector whose region has paints of its own draws the smoothed corners too, on the canvas + // and in SVG. + ex(&mut s, "node.set", json!({"ids": [closed], "props": {"cornerRadius": 20}})); + if let NodeKind::Vector { network } = &mut s.doc_mut().unwrap().get_mut(closed).unwrap().kind { + network.regions[0].fills = Some(vec![figcraft_color::Paint::solid(figcraft_color::Color::BLACK)]); + } + let (region_svg, region_path) = (svg(&s, closed), render(&s, closed)); + assert!((region_path.area().abs() - want).abs() < 0.5, "region paints follow the smoothed outline: {}", region_path.area().abs()); + ex(&mut s, "node.set", json!({"ids": [closed], "props": {"cornerSmoothing": 0}})); + assert_ne!(svg(&s, closed), region_svg, "SVG export draws the region's smoothed corners"); +} + #[test] fn rounded_vector_points_are_drawn() { // A converted 100 × 100 square: a point's radius rounds that corner only (it wasn't drawn). diff --git a/crates/format/src/fig/export/common.rs b/crates/format/src/fig/export/common.rs index 4a97eecb9..ee7293dc9 100644 --- a/crates/format/src/fig/export/common.rs +++ b/crates/format/src/fig/export/common.rs @@ -34,10 +34,10 @@ pub(super) fn outlined(n: &Node) -> Option<(Node, String)> { } let path = figcraft_doc::geometry::stroke_geometry(n)?; let net = match &n.kind { - NodeKind::Vector { network } => Some(network), + NodeKind::Vector { network } => Some(figcraft_doc::geometry::drawn_network(network, n.corners.smoothing)), _ => None, }; - let area = figcraft_pathops::stroke_outline_of(&path, sp, figcraft_doc::geometry::is_closed(n), net); + let area = figcraft_pathops::stroke_outline_of(&path, sp, figcraft_doc::geometry::is_closed(n), net.as_deref()); if area.elements().is_empty() || area.elements().len() > MAX_NETWORK / 4 { return None; } diff --git a/crates/format/src/fig/export/shape.rs b/crates/format/src/fig/export/shape.rs index 03c82cfb1..6627935ca 100644 --- a/crates/format/src/fig/export/shape.rs +++ b/crates/format/src/fig/export/shape.rs @@ -257,7 +257,7 @@ impl<'d> Exporter<'d> { if net.regions.iter().any(|r| r.winding != winding) { self.warn("vectors whose filled areas use different winding rules use the first one's in their outline"); } - self.geometry("fillGeometry", &net.fill_path(), winding, f); + self.geometry("fillGeometry", &figcraft_doc::geometry::drawn_network(net, n.corners.smoothing).fill_path(), winding, f); } } @@ -309,7 +309,7 @@ impl<'d> Exporter<'d> { self.geometry("strokeGeometry", &ring, WindingRule::EvenOdd, f); } else if sp.align == StrokeAlign::Center { let path = match &n.kind { - NodeKind::Vector { network } => Some(network.stroke_path()), + NodeKind::Vector { .. } => figcraft_doc::geometry::stroke_geometry(n), NodeKind::Text(_) => None, _ => figcraft_doc::geometry::shape_path(n), }; diff --git a/crates/format/src/fig/export_tests.rs b/crates/format/src/fig/export_tests.rs index 5b4bcb991..45f6866f3 100644 --- a/crates/format/src/fig/export_tests.rs +++ b/crates/format/src/fig/export_tests.rs @@ -912,6 +912,49 @@ fn written_files_decode_and_list_parents_first() { } } +#[test] +fn closed_vector_geometry_is_written_with_its_corner_smoothing() { + // A closed vector with rounded points: its written fill and stroke outlines take the layer's + // corner smoothing, and the smoothing and each point's radius come back on import. + let mut doc = Document::new("smoothing"); + let page = doc.first_page().unwrap(); + let mut network = VectorNetwork::from_points(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| Point::new(x, y)), true); + for (v, r) in network.vertices.iter_mut().zip([20.0, 0.0, 10.0, 0.0]) { + v.radius = r; + } + let id = doc.create(page, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 100.0).unwrap(); + doc.node_mut(id).unwrap().strokes = vec![Paint::solid(Color::BLACK)]; + // The vector's written fill and stroke outlines. + let outlines = |doc: &Document| -> Vec> { + let (bytes, _) = export(doc, None).unwrap(); + let archive = Archive::open(&bytes).unwrap(); + let (schema, message) = decode_canvas(&archive.canvas).unwrap(); + let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap(); + let blobs = msg.get("blobs").unwrap().list(); + let changes = msg.get("nodeChanges").unwrap().list(); + let nc = changes.iter().find(|nc| nc.get("type").and_then(Kv::str) == Some("VECTOR")).unwrap(); + ["fillGeometry", "strokeGeometry"] + .iter() + .map(|key| { + let paths = nc.get(key).map(Kv::list).unwrap_or_default(); + let blob = paths.first().unwrap_or_else(|| panic!("{key} is written")).get("commandsBlob").unwrap().f64().unwrap() as usize; + blobs[blob].get("bytes").and_then(Kv::bytes).unwrap().to_vec() + }) + .collect() + }; + let plain = outlines(&doc); + doc.node_mut(id).unwrap().corners.smoothing = 0.6; + let smoothed = outlines(&doc); + assert_ne!(smoothed[0], plain[0], "the fill outline takes the smoothing"); + assert_ne!(smoothed[1], plain[1], "the stroke outline takes the smoothing"); + let (back, _) = round_trip(&doc, "smoothed vector"); + let v = back.nodes().find(|n| matches!(n.kind, NodeKind::Vector { .. })).unwrap(); + assert!((v.corners.smoothing - 0.6).abs() < 1e-6, "smoothing comes back: {}", v.corners.smoothing); + let NodeKind::Vector { network } = &v.kind else { panic!("vector") }; + let radii: Vec = network.vertices.iter().map(|x| x.radius).collect(); + assert_eq!(radii, vec![20.0, 0.0, 10.0, 0.0], "each point keeps its own radius"); +} + #[test] fn the_written_schema_parses_and_round_trips() { let schema = Schema::parse(export::SCHEMA).unwrap(); diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 012fca429..d63d84397 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -249,67 +249,133 @@ pub fn smoothed_polygon(points: &[Point], radius: f64, smoothing: f64) -> BezPat }; let (v1, v2) = (*prev - *cur, *next - *cur); let (l1, l2) = (v1.hypot(), v2.hypot()); - let angle = if l1 < 1e-9 || l2 < 1e-9 { 0.0 } else { (v1 / l1).dot(v2 / l2).clamp(-1.0, 1.0).acos() }; - if angle < 1e-6 || (PI - angle) < 1e-6 { + let corner = if l1 < 1e-9 || l2 < 1e-9 { None } else { smooth_corner(*cur, v1 / l1, v2 / l2, l1.min(l2) / 2.0, radius, s) }; + let Some(k) = corner else { line_or_move(&mut path, *cur); continue; + }; + line_or_move(&mut path, k.start); + match k.ease_in { + Some((h1, h2)) => path.curve_to(h1, h2, k.p3), + None => path.line_to(k.p3), } - let (u1, u2) = (v1 / l1, v2 / l2); - // The plain corner's length along each edge, then the fit: smoothing first, then the radius. - let max_p = l1.min(l2) / 2.0; - let mut r = radius; - let mut t = r / (angle / 2.0).tan(); - let mut sm = s; - if (1.0 + sm) * t > max_p { - sm = (max_p / t - 1.0).clamp(0.0, sm); + if k.sweep.abs() > 1e-9 { + kurbo::Arc::new(k.center, (k.r, k.r), k.a0, k.sweep, 0.0).to_cubic_beziers(0.01, |p1, p2, q| path.curve_to(p1, p2, q)); } - if t > max_p { - r *= max_p / t; - t = max_p; - } - let p = ((1.0 + sm) * t).min(max_p); - // Each easing curve covers `beta` of the turn and ends on the arc at `back` along the edge - // and `side` across it; its last handle points along the arc there. - let beta = (PI - angle) * sm / 2.0; - let back = t - r * beta.sin(); - let side = r * (1.0 - beta.cos()); - let c = r * (beta / 2.0).tan() * beta.cos(); - let b = ((p - back - c) / 3.0).max(0.0); - let a = 2.0 * b; - let bisector = (u1 + u2).normalize(); - let center = *cur + bisector * (r / (angle / 2.0).sin()); - // A point `along` an edge from the vertex and `across` it toward the arc's center. - let at = |u: Vec2, along: f64, across: f64| *cur + u * along + (bisector - u * bisector.dot(u)).normalize() * across; - line_or_move(&mut path, at(u1, p, 0.0)); - let p3 = at(u1, back, side); - let p4 = at(u2, back, side); - if a + b + c > 1e-9 { - path.curve_to(at(u1, p - a, 0.0), at(u1, p - a - b, 0.0), p3); - } else { - path.line_to(p3); - } - let a0 = (p3 - center).atan2(); - let mut sweep = (p4 - center).atan2() - a0; - while sweep <= -PI { - sweep += TAU; - } - while sweep > PI { - sweep -= TAU; - } - if sweep.abs() > 1e-9 { - kurbo::Arc::new(center, (r, r), a0, sweep, 0.0).to_cubic_beziers(0.01, |p1, p2, q| path.curve_to(p1, p2, q)); - } - let end = at(u2, p, 0.0); - if a + b + c > 1e-9 { - path.curve_to(at(u2, p - a - b, 0.0), at(u2, p - a, 0.0), end); - } else { - path.line_to(end); + match k.ease_out { + Some((h1, h2)) => path.curve_to(h1, h2, k.end), + None => path.line_to(k.end), } } path.close_path(); path } +/// One smoothed corner as [`smoothed_polygon`] draws it: it starts at `start` on the first edge, +/// eases into a circular arc at `p3` (through handles `ease_in`, or straight when `None`), follows +/// the arc of radius `r` about `center` from angle `a0` through `sweep` to `p4`, and eases out to +/// `end` on the second edge. +struct SmoothCorner { + start: Point, + ease_in: Option<(Point, Point)>, + p3: Point, + center: Point, + r: f64, + a0: f64, + sweep: f64, + p4: Point, + ease_out: Option<(Point, Point)>, + end: Point, +} + +/// The smoothed corner at `cur` between edges that leave it along unit directions `u1` and `u2`, +/// with `max_p` of room along each: `None` where the edges run straight on or fold back. +fn smooth_corner(cur: Point, u1: Vec2, u2: Vec2, max_p: f64, radius: f64, s: f64) -> Option { + let angle = u1.dot(u2).clamp(-1.0, 1.0).acos(); + if angle < 1e-6 || (PI - angle) < 1e-6 { + return None; + } + // The plain corner's length along each edge, then the fit: smoothing first, then the radius. + let mut r = radius; + let mut t = r / (angle / 2.0).tan(); + let mut sm = s; + if (1.0 + sm) * t > max_p { + sm = (max_p / t - 1.0).clamp(0.0, sm); + } + if t > max_p { + r *= max_p / t; + t = max_p; + } + let p = ((1.0 + sm) * t).min(max_p); + // Each easing curve covers `beta` of the turn and ends on the arc at `back` along the edge + // and `side` across it; its last handle points along the arc there. + let beta = (PI - angle) * sm / 2.0; + let back = t - r * beta.sin(); + let side = r * (1.0 - beta.cos()); + let c = r * (beta / 2.0).tan() * beta.cos(); + let b = ((p - back - c) / 3.0).max(0.0); + let a = 2.0 * b; + let bisector = (u1 + u2).normalize(); + let center = cur + bisector * (r / (angle / 2.0).sin()); + // A point `along` an edge from the vertex and `across` it toward the arc's center. + let at = |u: Vec2, along: f64, across: f64| cur + u * along + (bisector - u * bisector.dot(u)).normalize() * across; + let p3 = at(u1, back, side); + let p4 = at(u2, back, side); + let eased = a + b + c > 1e-9; + let a0 = (p3 - center).atan2(); + let mut sweep = (p4 - center).atan2() - a0; + while sweep <= -PI { + sweep += TAU; + } + while sweep > PI { + sweep -= TAU; + } + Some(SmoothCorner { + start: at(u1, p, 0.0), + ease_in: eased.then(|| (at(u1, p - a, 0.0), at(u1, p - a - b, 0.0))), + p3, + center, + r, + a0, + sweep, + p4, + ease_out: eased.then(|| (at(u2, p - a - b, 0.0), at(u2, p - a, 0.0))), + end: at(u2, p, 0.0), + }) +} + +/// The curves of one corner rounded by `radius` with corner smoothing (0..=1) at `corner`, between +/// two straight edges that leave it along unit directions `u1` and `u2` with `max_p` of room along +/// each. The curves follow the profile of [`smoothed_polygon`], with the circular part as one +/// cubic, and run from the point on the `u1` edge to the point on the `u2` edge; a straight piece +/// has its handles on its ends. As in the polygon, smoothing is reduced first when the corner does +/// not fit, then the radius. `None` for a corner that is not rounded, or where the edges run +/// straight on or fold back. +pub fn smoothed_corner(corner: Point, u1: Vec2, u2: Vec2, max_p: f64, radius: f64, smoothing: f64) -> Option> { + let (s, radius, max_p) = (finite(smoothing).clamp(0.0, 1.0), finite(radius).max(0.0), finite(max_p).max(0.0)); + let usable = |u: Vec2| u.x.is_finite() && u.y.is_finite() && u.hypot() > 1e-9; + if radius <= 0.0 || max_p <= 0.0 || !usable(u1) || !usable(u2) || !(corner.x.is_finite() && corner.y.is_finite()) { + return None; + } + let k = smooth_corner(corner, u1 / u1.hypot(), u2 / u2.hypot(), max_p, radius, s)?; + let piece = |p0: Point, handles: Option<(Point, Point)>, p3: Point| { + let (h1, h2) = handles.unwrap_or((p0, p3)); + kurbo::CubicBez::new(p0, h1, h2, p3) + }; + let mut out = vec![piece(k.start, k.ease_in, k.p3)]; + if k.sweep.abs() > 1e-9 { + // The arc as one cubic: handles of 4/3·tan(θ/4)·r along the circle's tangents at its ends. + let h = 4.0 / 3.0 * (k.sweep.abs() / 4.0).tan() * k.r * k.sweep.signum(); + let tangent = |a: f64| Vec2::new(-a.sin(), a.cos()); + out.push(kurbo::CubicBez::new(k.p3, k.p3 + tangent(k.a0) * h, k.p4 - tangent(k.a0 + k.sweep) * h, k.p4)); + } + out.push(piece(k.p4, k.ease_out, k.end)); + out.retain(|q| (q.p3 - q.p0).hypot() > 1e-9 || (q.p1 - q.p0).hypot() > 1e-9 || (q.p2 - q.p3).hypot() > 1e-9); + let finite_point = |p: &Point| p.x.is_finite() && p.y.is_finite(); + let ok = out.iter().all(|q| [q.p0, q.p1, q.p2, q.p3].iter().all(finite_point)); + (ok && !out.is_empty()).then_some(out) +} + /// Starts `path` at `p`, or continues it there with a straight segment. fn line_or_move(path: &mut BezPath, p: Point) { if path.elements().is_empty() { diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rs index 37e6ccab7..1a2391a35 100644 --- a/crates/geom/src/tests.rs +++ b/crates/geom/src/tests.rs @@ -52,6 +52,53 @@ fn degenerate_inputs_dont_panic() { let _ = smoothed_polygon(&polygon_points(10.0, 10.0, 5), f64::INFINITY, f64::NAN); let _ = smoothed_polygon(&polygon_points(10.0, 10.0, 5), 3.0, f64::INFINITY); let _ = ellipse(f64::NAN, 10.0, f64::NAN, 100.0, 2.0); + // (corner, first edge, second edge, room, radius, smoothing): none of these is a corner to round. + let x = Vec2::new(1.0, 0.0); + let rows = [ + (Point::ZERO, x, Vec2::new(0.0, 1.0), 10.0, 0.0, 0.6), + (Point::ZERO, x, Vec2::new(0.0, 1.0), 0.0, 5.0, 0.6), + (Point::ZERO, x, x, 10.0, 5.0, 0.6), + (Point::ZERO, x, -x, 10.0, 5.0, 0.6), + (Point::ZERO, Vec2::ZERO, x, 10.0, 5.0, 0.6), + (Point::ZERO, Vec2::new(f64::NAN, 0.0), x, 10.0, 5.0, 0.6), + (Point::new(f64::INFINITY, 0.0), x, Vec2::new(0.0, 1.0), 10.0, 5.0, 0.6), + ]; + for (corner, u1, u2, room, r, s) in rows { + assert!(smoothed_corner(corner, u1, u2, room, r, s).is_none(), "{corner:?} {u1:?} {u2:?} {room} {r} {s}"); + } +} + +#[test] +fn smoothed_corner_draws_the_polygon_corner() { + use kurbo::ParamCurve; + // The corner of a square drawn by itself follows the smoothed polygon's corner and joins its + // edges and its own pieces without a kink. + for s in [0.0, 0.6, 1.0] { + let curves = smoothed_corner(Point::ZERO, Vec2::new(0.0, 1.0), Vec2::new(1.0, 0.0), 50.0, 20.0, s).unwrap(); + let mut path = BezPath::new(); + path.move_to(curves[0].p0); + for q in &curves { + path.curve_to(q.p1, q.p2, q.p3); + } + path.line_to((100.0, 0.0)); + path.line_to((100.0, 100.0)); + path.line_to((0.0, 100.0)); + path.close_path(); + let want = area(&rounded_rect(100.0, 100.0, [20.0, 0.0, 0.0, 0.0], s)); + assert!((area(&path) - want).abs() < 0.05, "s={s}: {} vs {want}", area(&path)); + assert!((curves[0].p0 - Point::new(0.0, 20.0 * (1.0 + s))).hypot() < 1e-9, "s={s}: it starts 1 + smoothing radii along the edge"); + let last = curves[curves.len() - 1]; + assert!((last.p3 - Point::new(20.0 * (1.0 + s), 0.0)).hypot() < 1e-9, "s={s}: and ends as far along the other"); + let dir = |c: &kurbo::CubicBez, t: f64| { + let d = if t < 0.5 { c.eval(1e-6) - c.eval(0.0) } else { c.eval(1.0) - c.eval(1.0 - 1e-6) }; + d.normalize() + }; + assert!(dir(&curves[0], 0.0).dot(Vec2::new(0.0, -1.0)) > 0.999, "s={s}: it leaves along the first edge"); + assert!(dir(&last, 1.0).dot(Vec2::new(1.0, 0.0)) > 0.999, "s={s}: it arrives along the second edge"); + for pair in curves.windows(2) { + assert!(dir(&pair[0], 1.0).dot(dir(&pair[1], 0.0)) > 0.999, "s={s}: its pieces join smoothly"); + } + } } #[test] diff --git a/crates/pdf/src/draw.rs b/crates/pdf/src/draw.rs index eb1b8aaf1..2ae6e366c 100644 --- a/crates/pdf/src/draw.rs +++ b/crates/pdf/src/draw.rs @@ -338,8 +338,8 @@ impl<'a> Exporter<'a> { if let NodeKind::Vector { network } = &n.kind && network.regions.iter().any(|r| r.fills.is_some() || r.paint_space.is_some()) { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); + let drawn = figcraft_doc::geometry::drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); for (i, region) in net.regions.iter().enumerate() { let paints = region.fills.as_deref().unwrap_or(&n.fills); if let Some(mut region_path) = net.region_path(i) { diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index cdd85d6bd..110bfa736 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -82,6 +82,27 @@ fn pdf_vector_region_paints_emit_independent_colors() { assert!(content.contains("1 0 0 rg") && content.contains("0 0 1 rg"), "{content}"); } +#[test] +fn pdf_vector_region_paints_draw_smoothed_corners() { + // A closed vector with rounded points and paints on its region: corner smoothing changes the + // exported outline, as on the canvas. + let corners = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| figcraft_geom::Point::new(x, y)); + let mut network = VectorNetwork::from_points(&corners, true); + for v in &mut network.vertices { + v.radius = 20.0; + } + network.regions[0].fills = Some(vec![Paint::solid(Color::from_hex("FF0000").unwrap())]); + let mut d = Document::new("smoothing"); + let p = d.first_page().unwrap(); + let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 100.0).unwrap(); + let content = |d: &Document| inflated(&export_pdf(d, &[id], &PdfOptions::default()).unwrap()); + let plain = content(&d); + d.get_mut(id).unwrap().corners.smoothing = 0.6; + let smoothed = content(&d); + assert!(smoothed.contains("1 0 0 rg"), "{smoothed}"); + assert_ne!(smoothed, plain, "the region's outline takes the smoothing"); +} + /// A page with two frames: shapes, gradients, an image, strokes, a mask, a boolean, effects, text. pub(crate) fn sample_doc() -> (Document, Vec) { let mut d = Document::new("sample"); diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index f48899aea..74512ef4f 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -274,7 +274,9 @@ fn cached_stroke_outline(n: &Node, path: &BezPath, closed: bool) -> Arc if let Some(p) = locked(stroke_cache()).get(key) { return p; } - let out = Arc::new(figcraft_pathops::stroke_outline_of(path, props, closed, net)); + // Points with styles of their own are stroked on the network as drawn (smoothed corners in). + let drawn = net.map(|network| figcraft_doc::geometry::drawn_network(network, n.corners.smoothing)); + let out = Arc::new(figcraft_pathops::stroke_outline_of(path, props, closed, drawn.as_deref())); locked(stroke_cache()).insert(key, out.clone()); out } @@ -334,9 +336,9 @@ fn node_outline_at(doc: &Document, n: &Node, depth: usize) -> Option<(BezPath, F Some((p, FillRule::Winding)) } NodeKind::Vector { network } => { + let drawn = figcraft_doc::geometry::drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); if network.regions.iter().any(|r| r.fills.is_some() || r.paint_space.is_some()) { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); let mut areas = BezPath::new(); for (i, region) in net.regions.iter().enumerate() { let paints = region.fills.as_deref().unwrap_or(&n.fills); @@ -357,7 +359,7 @@ fn node_outline_at(doc: &Document, n: &Node, depth: usize) -> Option<(BezPath, F } let rule = if network.regions.iter().any(|r| r.winding == figcraft_doc::WindingRule::EvenOdd) { FillRule::EvenOdd } else { FillRule::Winding }; - Some((network.fill_path(), rule)) + Some((net.fill_path(), rule)) } _ => figcraft_doc::geometry::shape_path(n).map(|p| (p, FillRule::Winding)), } @@ -849,8 +851,8 @@ fn region_painted(n: &Node) -> Option<&figcraft_doc::VectorNetwork> { /// Each region of a vector with region paints, filled with its own paints (or the layer's) in its /// own paint frame. fn fill_vector_regions(ctx: &Ctx, pix: &mut Pixmap, n: &Node, network: &figcraft_doc::VectorNetwork, xf: Affine) { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); + let drawn = figcraft_doc::geometry::drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); for (i, region) in net.regions.iter().enumerate() { let paints = region.fills.as_deref().unwrap_or(&n.fills); if let Some(mut path) = net.region_path(i) { diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index de98795d3..b5047cec4 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -537,8 +537,8 @@ impl W<'_> { if let NodeKind::Vector { network } = &n.kind && network.regions.iter().any(|r| r.fills.is_some() || r.paint_space.is_some()) { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); + let drawn = figcraft_doc::geometry::drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); for (i, region) in net.regions.iter().enumerate() { let paints = region.fills.as_deref().unwrap_or(&n.fills); let fr = if region.winding == figcraft_doc::WindingRule::EvenOdd { " fill-rule=\"evenodd\"" } else { "" }; diff --git a/crates/ui-egui/src/corner_individual_tests.rs b/crates/ui-egui/src/corner_individual_tests.rs index e76f2f57e..281ab6f2a 100644 --- a/crates/ui-egui/src/corner_individual_tests.rs +++ b/crates/ui-egui/src/corner_individual_tests.rs @@ -184,3 +184,36 @@ fn polygons_and_stars_take_corner_smoothing() { assert_eq!(u.app.session.undo_depth().0, history + 1, "{cmd}: one undo step"); } } + +/// A closed vector shows the same Corner smoothing control, and its iOS button sets 60% in one +/// undo step; an open vector, which has no closed shape to smooth, shows no smoothing control. +#[test] +fn closed_vectors_take_corner_smoothing() { + let rows = [(true, json!([[0, 0], [120, 0], [120, 120], [0, 120]])), (false, json!([[0, 0], [120, 0], [120, 120]]))]; + for (closed, points) in rows { + let mut s = Session::new(); + let id = NodeId(s.execute("vector.create", &json!({"points": points, "closed": closed})).unwrap()["id"].as_u64().unwrap()); + s.execute("node.set", &json!({"ids": [id], "props": {"cornerRadius": 8}})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let mut u = Ui::new(s); + u.ctx.enable_accesskit(); + u.frame(vec![]); + let out = u.frame_output(vec![]); + let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes; + let toggle = nodes.iter().any(|(_, n)| n.role() == Role::Button && n.label() == Some("Corner smoothing")); + assert_eq!(toggle, closed, "closed {closed}: the Corner smoothing button shows only for a closed vector"); + if !closed { + continue; + } + let t = named_button(&mut u, "Corner smoothing"); + click(&mut u, t); + assert!((0..4).all(|k| u.ctx.read_response(Id::unique(("corner", k)).with("field")).is_none()), "no field per corner"); + assert!(u.ctx.read_response(Id::unique("smoothing").with("field")).is_some(), "the smoothing field shows"); + let history = u.app.session.undo_depth().0; + let ios = named_button(&mut u, "iOS"); + click(&mut u, ios); + let n = u.app.session.doc().unwrap().node(id).unwrap().clone(); + assert!((n.corners.smoothing - 0.6).abs() < 1e-9, "iOS sets 60%: {}", n.corners.smoothing); + assert_eq!(u.app.session.undo_depth().0, history + 1, "one undo step"); + } +} diff --git a/crates/ui-egui/src/panels/right/paints.rs b/crates/ui-egui/src/panels/right/paints.rs index 58423d252..10301a85e 100644 --- a/crates/ui-egui/src/panels/right/paints.rs +++ b/crates/ui-egui/src/panels/right/paints.rs @@ -53,7 +53,7 @@ pub(super) fn appearance(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[N let radius_ok = crate::selection_cache::every(doc, sel, |n| n.kind.has_corner_radius()); // Only rectangles and frames round each corner on its own. let indep_ok = radius_ok && crate::selection_cache::every(doc, sel, |n| n.kind.has_independent_corners()); - // For polygons and stars the same panel holds only the Corner smoothing row. + // For polygons, stars and closed vectors the same panel holds only the Corner smoothing row. let smooth_ok = radius_ok && crate::selection_cache::every(doc, sel, |n| n.kind.has_corner_smoothing()); let r = common(doc, sel, |n| n.corners.uniform().map(|r| (r * 100.0).round() / 100.0)); widgets::sublabels(ui, tr("Opacity"), radius_ok.then_some(tr("Corner radius"))); diff --git a/docs/gaps.md b/docs/gaps.md index 5437c6766..b3685c912 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -384,8 +384,8 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe - **Landed (2026-10-12):** several Bezier handles selected with Shift-click and dragged together, sharp points beside curved segments rounded, a stroke cap and join per point (canvas, PNG, SVG, PDF, outline stroke), the Pen outside edit mode connecting to its own points and continuing a - selected open path. Left: corner smoothing on vectors, corner radius and smoothing on boolean - groups that contain rectangles, per-point caps and joins on dashed, variable-width and brush + selected open path. Left: corner radius and smoothing on boolean groups that contain + rectangles, per-point caps and joins on dashed, variable-width and brush strokes. - **Landed (2026-10-11):** boolean groups are clicked where their result is (a click in a subtracted hole reaches what's behind; with the group or an operand selected its operands are diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 489c0e7da..2775c41d2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -99,7 +99,7 @@ Breadth: does it exist. Ready: depth, correctness and fidelity for real projects | 1 | Canvas & navigation | 6 | 98% | 74% | Display P3 on screen, QA at extreme zooms (behaviour suite for navigation, rulers, guides, layout grids and outline mode landed: guide selection, Auto grid counts, outline-mode clicks; outline mode's Include hidden layers and Include object bounds landed) | 1–4 | | 2 | Selection & transform | 8 | 97% | 72% | Handles, measuring and snapping checked tool by tool against Figma and real files (snap distance, handle reach, cursors); children turned off a right angle scale without skew, approximately (behaviour suite from the documentation, rotated groups and mixed selections, equal spacing snapping, Cmd/Ctrl to ignore constraints and marquees inside frames landed) | 3–5 | | 3 | Layers panel | 5 | 99% | 85% | QA with long real files (behaviour suite from the documentation, Rename layers dialog, sweeping eyes and padlocks, page dragging and dividers, several layers dropped together, keyboard box selection, F2 rename, Shift+F10 context menu and 10k-layer timings landed) | 1–2 | -| 4 | Shapes & vector | 8 | 99% | 73% | Corner smoothing on vectors, corner radius and smoothing on boolean groups that contain rectangles; per-point caps and joins on dashed, variable-width and brush strokes; vector QA with real files (behaviour suites from the documentation, corner radius and star ratio handles, corner smoothing on polygons and stars, rounded vector points drawn, also beside curved segments, a cap and join per point, several handles dragged together, cut and paint bucket drags, delete and heal along the curve, a boolean group's look by operation and the miter angle landed) | 1–3 | +| 4 | Shapes & vector | 8 | 99% | 73% | Corner radius and smoothing on boolean groups that contain rectangles; per-point caps and joins on dashed, variable-width and brush strokes; vector QA with real files (behaviour suites from the documentation, corner radius and star ratio handles, corner smoothing on polygons, stars and closed vectors, rounded vector points drawn, also beside curved segments, a cap and join per point, several handles dragged together, cut and paint bucket drags, delete and heal along the curve, a boolean group's look by operation and the miter angle landed) | 1–3 | | 5 | Paint | 7 | 90% | 71% | Video fills, wide-gamut canvas, HEIC images; plus darker in PDF (behaviour suite from the documentation, pass-through and isolating groups, clipping frames that don't isolate, plus darker, animated GIF fills, TIFF images and embedded image colour profiles landed) | 2–5 | | 6 | Strokes | 3 | 95% | 75% | Stroke QA with real files (colour styles on strokes, stroke weight and per-side weight variables, brush strokes landed, see 20) | 1–2 | | 7 | Effects | 4 | 100% | 75% | Glass and progressive blur tuned side by side (behaviour suite from the documentation, inner shadows and background blur on groups, shadows hidden behind translucent layers on the canvas and in every export landed) | 2–5 | From f56e30e7e3bf992d747881b7d0b0d21ed8e16efd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 02:42:39 -0700 Subject: [PATCH 002/102] Hit testing: clicks on a closed vector follow its smoothed corners A vector without region paints tested a click against its plain rounded fill while the canvas drew the smoothed corners, so a click between the two could select a layer where no fill is drawn or miss fill that is drawn. The inside test now uses the network as drawn, keeping the even-odd rule. --- crates/doc/src/geometry.rs | 5 +++-- crates/doc/src/tests.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/geometry.rs b/crates/doc/src/geometry.rs index 3dbbce6d4..189e06192 100644 --- a/crates/doc/src/geometry.rs +++ b/crates/doc/src/geometry.rs @@ -107,10 +107,11 @@ fn hits_node_itself(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, o } /// Whether the fill of `n`, drawn as `path`, covers `lp` (vectors follow the rule of -/// [`VectorNetwork::fill_contains`](crate::VectorNetwork::fill_contains): even-odd when any region asks for it). +/// [`VectorNetwork::fill_contains`](crate::VectorNetwork::fill_contains) on the network as drawn: even-odd when any +/// region asks for it). fn fills_point(n: &Node, path: &BezPath, lp: Point) -> bool { match &n.kind { - NodeKind::Vector { network } => network.fill_contains(lp), + NodeKind::Vector { network } => drawn_network(network, n.corners.smoothing).fill_contains(lp), _ => path.winding(lp) != 0, } } diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 2eb912f45..7dbc8cc94 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -789,6 +789,33 @@ fn smoothed_vector_corners_stay_finite_on_awkward_networks() { assert!(!holed_net.fill_contains(Point::new(50.0, 50.0)) && holed_net.fill_contains(Point::new(12.0, 50.0)), "the hole stays a hole"); } +#[test] +fn clicks_on_a_smoothed_vector_corner_follow_the_drawn_fill() { + // A closed square with rounded points and smoothing: a click between the plain arc and the + // smoothed corner selects the layer only where the smoothed fill is drawn. + let pts = [Point::new(0.0, 0.0), Point::new(1000.0, 0.0), Point::new(1000.0, 1000.0), Point::new(0.0, 1000.0)]; + let mut net = VectorNetwork::from_points(&pts, true); + for v in &mut net.vertices { + v.radius = 200.0; + } + let smoothed = net.rounded_smoothed(1.0).unwrap(); + let mut d = Document::new("x"); + let p = page(&d); + let v = d.create(p, NodeKind::Vector { network: net.clone() }, "V", 0.0, 0.0, 1000.0, 1000.0).unwrap(); + let n = d.node_mut(v).unwrap(); + n.corners.smoothing = 1.0; + n.strokes.clear(); + // Walk the row 20 units below the top edge inward to where each outline starts covering it. + let first_inside = |inside: &dyn Fn(Point) -> bool| (0..5_000).map(|i| f64::from(i) * 0.1).find(|&x| inside(Point::new(x, 20.0))); + let plain = first_inside(&|pt| net.fill_contains(pt)).unwrap(); + let drawn = first_inside(&|pt| smoothed.fill_contains(pt)).unwrap(); + assert!((plain - drawn).abs() > 5.0, "smoothing moves the corner: plain {plain}, smoothed {drawn}"); + let pt = Point::new((plain + drawn) / 2.0, 20.0); + assert_ne!(net.fill_contains(pt), smoothed.fill_contains(pt)); + assert_eq!(d.hit_test(p, pt, 0.0, None).is_some(), smoothed.fill_contains(pt), "the click follows the smoothed corner at {pt:?}"); + assert_eq!(d.hit_test(p, Point::new(500.0, 500.0), 0.0, None), Some(v)); +} + #[test] fn stored_variable_ids_resolve_only_their_exact_collection() { let mut vars = crate::proto_expr_tests::vars(); From 099cc0375455a63803b49739183583163ef36bf9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 03:21:43 -0700 Subject: [PATCH 003/102] Vector: simplify, offset and Penpot export keep a closed vector's smoothed corners vector.simplify and vector.offset rebuild a closed vector from its rounded outline with the layer's corner smoothing, as the canvas draws it. A vector whose regions have paints of their own was rebuilt from its sharp points before; it now keeps its rounded corners. The Penpot export writes a stroked vector's path with its smoothed corners. --- crates/engine/src/cmd/structure.rs | 13 ++++--- crates/engine/src/vector_behaviour_tests.rs | 39 +++++++++++++++++++++ crates/format/src/penpot/export.rs | 4 ++- crates/format/src/penpot/export_tests.rs | 26 ++++++++++++++ 4 files changed, 77 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/structure.rs b/crates/engine/src/cmd/structure.rs index 52b4a415d..5a79d0a24 100644 --- a/crates/engine/src/cmd/structure.rs +++ b/crates/engine/src/cmd/structure.rs @@ -751,8 +751,11 @@ fn simplify(s: &mut Session, p: &Value) -> Result { for i in req_targets("vector.simplify", s, p)? { let doc = s.doc_mut()?; let n = doc.get_mut(i)?; + let smoothing = n.corners.smoothing; if let NodeKind::Vector { network } = &mut n.kind { let source = network.clone(); + // The regions as the layer draws them: rounded points with the layer's corner smoothing. + let drawn = figcraft_doc::geometry::drawn_network(&source, smoothing); let mut net = VectorNetwork::default(); let legacy = source.regions.iter().all(|region| region.fills.is_none() && region.paint_space.is_none()); if legacy && !source.regions.is_empty() { @@ -761,7 +764,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result { } else { WindingRule::NonZero }; - let path = source.fill_path(); + let path = drawn.fill_path(); let path = figcraft_geom::kurbo::simplify::simplify_bezpath(path.iter(), tol, &Default::default()); let (path, output_winding) = match figcraft_pathops::simplify_with_rule(&path, winding == WindingRule::EvenOdd) { Ok(path) => (path, WindingRule::EvenOdd), @@ -771,7 +774,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result { append_region_path(&mut net, &path, &combined, output_winding); } else { for (index, region) in source.regions.iter().enumerate() { - let Some(path) = source.region_path(index) else { continue }; + let Some(path) = drawn.region_path(index) else { continue }; let path = figcraft_geom::kurbo::simplify::simplify_bezpath(path.iter(), tol, &Default::default()); let path = figcraft_pathops::simplify_with_rule(&path, region.winding == WindingRule::EvenOdd).unwrap_or(path); append_region_path(&mut net, &path, region, region.winding); @@ -859,8 +862,10 @@ fn offset_path(s: &mut Session, p: &Value) -> Result { nm.height = bb.height(); continue; } + // The regions as the layer draws them: rounded points with the layer's corner smoothing. + let drawn = figcraft_doc::geometry::drawn_network(source, n.corners.smoothing); if legacy { - let path = source.fill_path(); + let path = drawn.fill_path(); let even_odd = source.regions.iter().any(|region| region.winding == WindingRule::EvenOdd); let path = figcraft_pathops::simplify_with_rule(&path, even_odd).map_err(|error| bad("vector.offset", error.to_string()))?; let ring = figcraft_pathops::stroke_center(&path, d.abs() * 2.0, &props); @@ -880,7 +885,7 @@ fn offset_path(s: &mut Session, p: &Value) -> Result { append_network(&mut net, part); } else { for (index, region) in source.regions.iter().enumerate() { - let Some(path) = source.region_path(index) else { continue }; + let Some(path) = drawn.region_path(index) else { continue }; let mut paint_region = region.clone(); let (paint_width, paint_height, paint_transform) = region.paint_frame(n.width, n.height); paint_region.paint_space = Some(RegionPaintSpace { width: paint_width, height: paint_height, transform: paint_transform }); diff --git a/crates/engine/src/vector_behaviour_tests.rs b/crates/engine/src/vector_behaviour_tests.rs index 83e585ea0..c990ad348 100644 --- a/crates/engine/src/vector_behaviour_tests.rs +++ b/crates/engine/src/vector_behaviour_tests.rs @@ -278,6 +278,45 @@ fn legacy_evenodd_holes_survive_bucket_offset_and_flatten() { assert!(!net(&s, flattened).fill_contains(Point::new(100.0, 100.0)), "flatten retains the even-odd hole"); } +#[test] +fn simplify_and_offset_keep_a_closed_vectors_smoothed_corners() { + // A closed 100 × 100 vector with radius 20 on every point and corner smoothing 0.6 draws a + // smoothed rectangle's outline; simplify and offset rebuild it from that outline. + let drawn = figcraft_geom::rounded_rect(100.0, 100.0, [20.0; 4], 0.6); + let plain = figcraft_geom::rounded_rect(100.0, 100.0, [20.0; 4], 0.0).area().abs(); + let (area, d) = (drawn.area().abs(), 2.0); + // Offsetting a convex outline by d adds its perimeter times d and a circle of radius d. + let grown = area + drawn.perimeter(1e-6) * d + std::f64::consts::PI * d * d; + assert!((area - plain).abs() > 10.0, "smoothing changes the outline: {area} vs {plain}"); + // (command, params, region paints of its own, expected area, tolerance: the offset ring is + // flattened before the union) + let rows = [ + ("vector.simplify", json!({"tolerance": 0.01}), false, area, 1.0), + ("vector.simplify", json!({"tolerance": 0.01}), true, area, 1.0), + ("vector.offset", json!({"offset": d}), false, grown, 4.0), + ("vector.offset", json!({"offset": d}), true, grown, 4.0), + ]; + let mut wrong = Vec::new(); + for (cmd, mut params, painted, expected, tolerance) in rows { + let mut s = Session::new(); + let id = id_of(&ex(&mut s, "vector.create", json!({"points": [[0, 0], [100, 0], [100, 100], [0, 100]], "closed": true}))["id"]).unwrap(); + ex(&mut s, "node.set", json!({"ids": [id], "props": {"cornerRadius": 20}})); + ex(&mut s, "node.set", json!({"ids": [id], "props": {"cornerSmoothing": 0.6}})); + if painted { + let doc = s.doc_mut().unwrap(); + let NodeKind::Vector { network } = &mut doc.get_mut(id).unwrap().kind else { panic!("expected vector fixture") }; + network.regions[0].fills = Some(vec![figcraft_color::Paint::solid(figcraft_color::Color::BLACK)]); + } + params["ids"] = json!([id]); + ex(&mut s, cmd, params); + let got = net(&s, id).fill_path().area().abs(); + if (got - expected).abs() >= tolerance { + wrong.push(format!("{cmd} (region paints: {painted}): {got} vs {expected}")); + } + } + assert!(wrong.is_empty(), "simplify and offset keep the smoothed corners: {wrong:?}"); +} + /// Give vector `id` a painted region, converting a plain shape to a vector first. fn ex_to_vector(doc: &mut figcraft_doc::Document, id: NodeId) { let n = doc.get(id).unwrap(); diff --git a/crates/format/src/penpot/export.rs b/crates/format/src/penpot/export.rs index cacafd0d9..d0b9d3046 100644 --- a/crates/format/src/penpot/export.rs +++ b/crates/format/src/penpot/export.rs @@ -713,7 +713,9 @@ impl<'a> Exporter<'a> { } } } - NodeKind::Vector { network } if node.fills.is_empty() || !node.strokes.is_empty() => self.doc.world_transform(id) * network.stroke_path(), + NodeKind::Vector { network } if node.fills.is_empty() || !node.strokes.is_empty() => { + self.doc.world_transform(id) * figcraft_doc::geometry::drawn_network(network, node.corners.smoothing).stroke_path() + } _ => match figcraft_doc::geometry::shape_path(node) { Some(p) => self.doc.world_transform(id) * p, None => BezPath::new(), diff --git a/crates/format/src/penpot/export_tests.rs b/crates/format/src/penpot/export_tests.rs index 4dacd4eae..1e9e95638 100644 --- a/crates/format/src/penpot/export_tests.rs +++ b/crates/format/src/penpot/export_tests.rs @@ -174,6 +174,32 @@ fn rectangles_ellipses_and_paths_keep_their_geometry() { assert!(matches!(back.node(named(&back, "Circle")).unwrap().kind, NodeKind::Ellipse { .. })); } +#[test] +fn stroked_closed_vectors_are_written_with_their_corner_smoothing() { + // A stroked closed 100 × 100 vector with radius 20 on every point and corner smoothing 0.6 is + // written as the smoothed outline it draws. + let mut doc = Document::new("Smoothed vector"); + let p = page(&doc); + let corners = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)]; + let mut network = VectorNetwork::from_points(&corners, true); + for v in &mut network.vertices { + v.radius = 20.0; + } + let id = add(&mut doc, p, NodeKind::Vector { network }, "Smoothed", 0.0, 0.0, 100.0, 100.0); + { + let n = doc.node_mut(id).unwrap(); + n.fills = vec![Paint::solid(Color::BLACK)]; + n.strokes = vec![Paint::solid(Color::BLACK)]; + n.corners.smoothing = 0.6; + } + let want = figcraft_doc::geom::rounded_rect(100.0, 100.0, [20.0; 4], 0.6).area().abs(); + let plain = figcraft_doc::geom::rounded_rect(100.0, 100.0, [20.0; 4], 0.0).area().abs(); + assert!((want - plain).abs() > 10.0, "smoothing changes the outline: {want} vs {plain}"); + let (back, _, _) = roundtrip(&doc); + let written = figcraft_doc::geometry::shape_path(back.node(named(&back, "Smoothed")).unwrap()).unwrap().area().abs(); + assert!((written - want).abs() < 0.5, "the written path keeps the smoothed corners: {written} vs {want}"); +} + #[test] fn fills_and_strokes_keep_their_order_and_styles() { let mut doc = Document::new("Paints"); From 01214c6e12aff34a2ac56503b1f7dbe8cb9a60c8 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 31 Oct 2026 11:26:45 -0400 Subject: [PATCH 004/102] M8: CSS colours take none and every hue unit, refuse nan and inf, and to_css keeps the 8-bit alpha Found while testing crates/color/src/lib.rs (no existing issue), each with a test that fails before and passes after: rgb() accepted nan/inf/infinity identifiers (Rust float syntax, not CSS numbers); hsl() refused the turn, grad and rad hue units lch() and oklch() already take, and accepted repeated suffixes; none was refused in rgb() and hsl() and read as opaque in a lch()/oklch() alpha, where CSS Color 4 section 4.4 says a missing component is zero; to_css could print an alpha that read back as a different 8-bit value, and printed NaN or negative alphas from a field-built colour. One css_f32 number reader (sign, digits, point, exponent) and a css_fraction helper (number, percentage or none) now serve every CSS number path. Co-Authored-By: Claude Fable 5.1 --- crates/color/src/lch_tests.rs | 5 ++- crates/color/src/lib.rs | 79 ++++++++++++++++++++++++----------- crates/color/src/tests.rs | 76 +++++++++++++++++++++++++++++++++ 3 files changed, 135 insertions(+), 25 deletions(-) diff --git a/crates/color/src/lch_tests.rs b/crates/color/src/lch_tests.rs index 0bf249b07..d3998261d 100644 --- a/crates/color/src/lch_tests.rs +++ b/crates/color/src/lch_tests.rs @@ -73,7 +73,10 @@ fn css_hue_units_and_none() { assert_eq!(Color::parse_css(&format!("oklch(0.6 0.2 {h})")).unwrap().to_hex(), blue.to_hex(), "{h}"); } assert_eq!(Color::parse_css("lch(50 none none)").unwrap().to_hex(), Color::parse_css("lch(50 0 0)").unwrap().to_hex()); - assert_eq!(Color::parse_css("oklch(none 0 0 / none)").unwrap().to_rgba8(), [0, 0, 0, 255]); + // A missing alpha is zero like any other missing component (CSS Color 4 §4.4), so it is + // transparent; only an *omitted* alpha defaults to opaque. + assert_eq!(Color::parse_css("oklch(none 0 0 / none)").unwrap().to_rgba8(), [0, 0, 0, 0]); + assert_eq!(Color::parse_css("oklch(none 0 0)").unwrap().to_rgba8(), [0, 0, 0, 255]); } #[test] diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 190fdbb9c..764069742 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -158,14 +158,9 @@ impl Color { } if let Some(inner) = t.strip_prefix("rgba(").or_else(|| t.strip_prefix("rgb(")).and_then(|r| r.strip_suffix(')')) { let parts = css_args(inner)?; - let num = |i: usize| -> Option { - let p = parts.get(i)?; - if let Some(pc) = p.strip_suffix('%') { - pc.trim().parse::().ok().map(|v| v / 100.0) - } else { - p.parse::().ok().map(|v| v / 255.0) - } - }; + // A channel is a number of 255, a percentage or `none`; out-of-range values (a number + // too big for f32 included) clamp in `Color::new`, as CSS Color 4 §5.1 asks. + let num = |i: usize| css_fraction(parts.get(i)?, 255.0); let alpha = match parts.get(3) { Some(a) => parse_alpha(a)?, None => 1.0, @@ -177,10 +172,12 @@ impl Color { } if let Some(inner) = t.strip_prefix("hsla(").or_else(|| t.strip_prefix("hsl(")).and_then(|r| r.strip_suffix(')')) { let parts = css_args(inner)?; - let h = parts.first()?.trim_end_matches("deg").parse::().ok()?; - let s = parts.get(1)?.trim_end_matches('%').parse::().ok()? / 100.0; - let l = parts.get(2)?.trim_end_matches('%').parse::().ok()? / 100.0; - if !(h.is_finite() && s.is_finite() && l.is_finite()) { + // The hue takes every CSS angle unit; saturation and lightness are percentages, numbers + // read as percentages (CSS Color 4 §7) or `none`. + let h = css_hue(parts.first()?)?; + let s = css_fraction(parts.get(1)?, 100.0)?; + let l = css_fraction(parts.get(2)?, 100.0)?; + if !(s.is_finite() && l.is_finite()) { return None; } let alpha = match parts.get(3) { @@ -209,14 +206,23 @@ impl Color { /// CSS `rgba(...)` / hex text for copy-as-CSS. pub fn to_css(self) -> String { - let [r, g, b, _] = self.to_rgba8(); - if self.a >= 0.999 { + let [r, g, b, a8] = self.to_rgba8(); + let a = clamp01(self.a); + if a >= 0.999 { return self.to_css_hex(); } - // Two decimals when they keep the 8-bit alpha, three otherwise (near-transparent colours). - let a8 = |a: f32| (a.clamp(0.0, 1.0) * 255.0).round() as u8; - let short = format!("{:.2}", self.a); - let alpha = if short.parse::().is_ok_and(|v| a8(v) == a8(self.a)) { short } else { format!("{:.3}", self.a) }; + // The fewest decimals that read back as the same 8-bit alpha: two, else three, else three + // of the 8-bit value itself (within half a step of it, so it always reads back). + let keeps = |s: &str| s.parse::().is_ok_and(|v| (v * 255.0).round() as u8 == a8); + let two = format!("{a:.2}"); + let three = format!("{a:.3}"); + let alpha = if keeps(&two) { + two + } else if keeps(&three) { + three + } else { + format!("{:.3}", f32::from(a8) / 255.0) + }; format!("rgba({r}, {g}, {b}, {alpha})") } @@ -268,19 +274,42 @@ fn css_polar(inner: &str, l_full: f32, c_full: f32) -> Option<([f32; 3], f32)> { let l = css_number(parts.first()?, l_full)?; let c = css_number(parts.get(1)?, c_full)?; let h = css_hue(parts.get(2)?)?; - let alpha = match parts.get(3).map(String::as_str) { - None | Some("none") => 1.0, + let alpha = match parts.get(3) { + None => 1.0, Some(a) => parse_alpha(a)?, }; Some(([l, c, h], alpha)) } +/// A CSS `` as f32: a sign, digits, a decimal point and an exponent only. Rust's float +/// parser also reads `inf`, `infinity` and `nan`, which are identifiers in CSS, not numbers. A +/// value too big for f32 comes back as an infinity for the caller to clamp or refuse. +fn css_f32(s: &str) -> Option { + if !s.bytes().all(|b| b.is_ascii_digit() || matches!(b, b'+' | b'-' | b'.' | b'e' | b'E')) { + return None; + } + s.parse::().ok() +} + +/// A CSS number, percentage or `none` as a fraction of one: a percentage is of 100, a bare number +/// of `number_full` (255 for an rgb() channel, 100 for hsl() saturation and lightness, 1 for +/// alpha) and `none` is 0 (CSS Color 4 §4.4). +fn css_fraction(p: &str, number_full: f32) -> Option { + if p == "none" { + return Some(0.0); + } + match p.strip_suffix('%') { + Some(pc) => Some(css_f32(pc)? / 100.0), + None => Some(css_f32(p)? / number_full), + } +} + /// A CSS number, a percentage of `full` or `none` (0); finite only. fn css_number(p: &str, full: f32) -> Option { let v = match p.strip_suffix('%') { _ if p == "none" => 0.0, - Some(pc) => pc.trim().parse::().ok()? / 100.0 * full, - None => p.parse::().ok()?, + Some(pc) => css_f32(pc)? / 100.0 * full, + None => css_f32(p)?, }; v.is_finite().then_some(v) } @@ -294,12 +323,14 @@ fn css_hue(p: &str) -> Option { .into_iter() .find_map(|(unit, k)| p.strip_suffix(unit).map(|n| (n, k))) .unwrap_or((p, 1.0)); - let v = num.parse::().ok()? / per_degree; + let v = css_f32(num)? / per_degree; v.is_finite().then_some(v) } +/// A CSS ``: a number, a percentage or `none` (0: a missing alpha is transparent, CSS +/// Color 4 §4.4); finite only. An *omitted* alpha is the caller's default of 1. fn parse_alpha(a: &str) -> Option { - let v = if let Some(pc) = a.strip_suffix('%') { pc.parse::().ok().map(|v| v / 100.0) } else { a.parse::().ok() }?; + let v = css_fraction(a, 1.0)?; v.is_finite().then_some(v) } diff --git a/crates/color/src/tests.rs b/crates/color/src/tests.rs index a41d0dd2e..6100a89ad 100644 --- a/crates/color/src/tests.rs +++ b/crates/color/src/tests.rs @@ -157,3 +157,79 @@ fn css_rejects_empty_arguments() { assert!(Color::parse_css("rgb(255 0 0 / 50%)").is_some()); assert!(Color::parse_css("hsl(120deg 50% 50%)").is_some()); } + +#[test] +fn css_rgb_rejects_non_numeric_channels() { + // `nan`, `inf` and `infinity` are identifiers, not CSS numbers; the hsl(), lch() and oklch() + // branches and the alpha already refuse them, and so must rgb() channels (which previously read + // `rgb(nan, 0, 0)` as black and `rgb(inf, 0, 0)` as red). + for s in ["rgb(nan, 0, 0)", "rgb(inf, 0, 0)", "rgb(0, 0, infinity)", "rgb(-inf, 0, 0)", "rgb(nan%, 0, 0)", "rgb(NaN 0 0)", "rgba(0, 0, 0, inf)"] { + assert_eq!(Color::parse_css(s), None, "{s}"); + } + // A genuine number that overflows f32 is still a number and clamps (CSS Color 4 §5.1). + assert_eq!(Color::parse_css("rgb(1e40, -1e40, 0)").unwrap().to_rgba8(), [255, 0, 0, 255]); + assert_eq!(Color::parse_css("rgb(+255, .5%, 1E2)").unwrap().to_rgba8(), [255, 1, 100, 255]); +} + +#[test] +fn css_hsl_takes_every_hue_unit() { + // CSS Color 4 §4.3: ` = | `, so turn, grad and rad are as valid as deg. + let cyan = Color::parse_css("hsl(180, 100%, 50%)").unwrap(); + assert_eq!(cyan.to_hex(), "00FFFF"); + let units = + ["hsl(0.5turn, 100%, 50%)", "hsl(200grad 100% 50%)", "hsl(3.1415927rad 100% 50%)", "hsl(180deg 100% 50%)", "hsla(-0.5turn, 100%, 50%, 1)"]; + for s in units { + assert_eq!(Color::parse_css(s).map(|c| c.to_hex()), Some(cyan.to_hex()), "{s}"); + } + // One unit only: a repeated or stray unit is not a dimension. + for s in ["hsl(120degdeg, 100%, 50%)", "hsl(120, 100%%, 50%)", "hsl(0.5turndeg 100% 50%)", "hsl(deg 100% 50%)"] { + assert_eq!(Color::parse_css(s), None, "{s}"); + } +} + +#[test] +fn css_none_is_zero_in_every_function() { + // CSS Color 4 §4.4: every modern-syntax component may be `none`, and outside interpolation a + // missing component "behaves as a zero value" -- including a missing alpha, which renders + // fully transparent. + assert_eq!(Color::parse_css("rgb(none 0 0)").unwrap().to_rgba8(), [0, 0, 0, 255]); + assert_eq!(Color::parse_css("rgb(255 none none)").unwrap().to_rgba8(), [255, 0, 0, 255]); + assert_eq!(Color::parse_css("rgb(255 0 0 / none)").unwrap().to_rgba8(), [255, 0, 0, 0]); + assert_eq!(Color::parse_css("hsl(none 100% 50%)").unwrap().to_hex(), "FF0000"); + assert_eq!(Color::parse_css("hsl(120 none 50%)").unwrap().to_hex(), "808080"); + assert_eq!(Color::parse_css("hsl(120 100% none)").unwrap().to_hex(), "000000"); + assert_eq!(Color::parse_css("hsl(120 100% 50% / none)").unwrap().to_rgba8(), [0, 255, 0, 0]); + assert_eq!(Color::parse_css("oklch(0.5 0.1 20 / none)").unwrap().a, 0.0); + assert_eq!(Color::parse_css("lch(50 50 50 / none)").unwrap().a, 0.0); + // An omitted alpha still defaults to opaque. + assert_eq!(Color::parse_css("rgb(none none none)").unwrap().a, 1.0); +} + +#[test] +fn to_css_keeps_the_8_bit_alpha_for_any_alpha() { + // Three decimals of the alpha can still round across an 8-bit step (0.0055 -> "0.006" reads + // back as 2/255, not 1/255); the text must always read back to the same 8-bit alpha. + for i in 0..=10_000u32 { + let a = i as f32 / 10_000.0; + let c = Color::new(0.1, 0.2, 0.3, a); + let css = c.to_css(); + assert_eq!(Color::parse_css(&css).map(|b| b.to_rgba8()), Some(c.to_rgba8()), "alpha {a}: {css}"); + } + let c = Color::new(0.1, 0.2, 0.3, 0.0055); + assert_eq!(Color::parse_css(&c.to_css()).unwrap().to_rgba8()[3], 1, "{}", c.to_css()); + // Still the short forms where they are exact. + assert_eq!(Color::new(1.0, 0.0, 0.0, 0.5).to_css(), "rgba(255, 0, 0, 0.50)"); + assert_eq!(Color::from_rgba8(255, 0, 0, 85).to_css(), "rgba(255, 0, 0, 0.333)"); +} + +#[test] +fn to_css_sanitizes_an_unclamped_alpha() { + // The RGB channels go through `to_rgba8` and are sanitized; the alpha must be too, or a colour + // built field-by-field prints `rgba(0, 0, 0, NaN)` / `rgba(0, 0, 0, -0.50)`, which is not CSS. + for a in [f32::NAN, -0.5, f32::NEG_INFINITY] { + let c = Color { r: 0.0, g: 0.0, b: 0.0, a }; + let css = c.to_css(); + assert_eq!(Color::parse_css(&css).map(|b| b.to_rgba8()), Some([0, 0, 0, 0]), "alpha {a}: {css}"); + } + assert_eq!(Color { r: 1.0, g: 0.0, b: 0.0, a: f32::INFINITY }.to_css(), "#FF0000"); +} From 467607762616424b9345c8f1cefe09198e6e2d8e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 00:16:56 -0400 Subject: [PATCH 005/102] SVG color-mix(): a missing alpha is taken from the other colour before the mix Review follow-up on #1773: with a none alpha now zero when a colour is rendered on its own (CSS Color 4 section 4.4), color-mix() needs the carry-forward rule of CSS Color 5 section 4.1, else color-mix(in srgb, rgb(255 0 0 / none), blue) came out half transparent instead of opaque purple. The operand reports a missing alpha and mix() fills it from the other colour; both missing stays zero. Co-Authored-By: Claude Fable 5.1 --- crates/svg/src/import/css_color.rs | 33 ++++++++++++++++++------ crates/svg/src/import/css_color_tests.rs | 6 +++++ 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/crates/svg/src/import/css_color.rs b/crates/svg/src/import/css_color.rs index 40bf0ab40..e330959fe 100644 --- a/crates/svg/src/import/css_color.rs +++ b/crates/svg/src/import/css_color.rs @@ -219,9 +219,16 @@ fn mix(args: &str, profile: ColorProfile, depth: usize) -> Eval { ["in", ..] => (Space::Srgb, Some("only srgb, oklab and oklch mixes are read: it was mixed in sRGB")), _ => return Err("color-mix() starts with `in` and a colour space"), }; - let (a, pa, why_a) = operand(first, profile, depth)?; - let (b, pb, why_b) = operand(second, profile, depth)?; + let (a, pa, why_a, a_none) = operand(first, profile, depth)?; + let (b, pb, why_b, b_none) = operand(second, profile, depth)?; why = why.or(why_a).or(why_b); + // A missing alpha (`/ none`) is carried over from the other colour before the mix (CSS Color 5 + // section 4.1); rendered on its own the same colour is transparent. + let (a, b) = match (a_none, b_none) { + (true, false) => (a.with_alpha(b.a), b), + (false, true) => (a, b.with_alpha(a.a)), + _ => (a, b), + }; if [pa, pb].into_iter().flatten().any(|p| !(0.0..=100.0).contains(&p)) { return Err("mix percentages are between 0% and 100%"); } @@ -239,8 +246,11 @@ fn mix(args: &str, profile: ColorProfile, depth: usize) -> Eval { Ok((mixed.with_alpha(mixed.a * (sum / 100.0).min(1.0)), why)) } -/// One colour of a mix and its percentage (before or after it). -fn operand(s: &str, profile: ColorProfile, depth: usize) -> Result<(Color, Option, Option<&'static str>), &'static str> { +/// One colour of a mix: the colour, its percentage (before or after it), a note, and whether its +/// alpha is missing (`rgb(255 0 0 / none)`), which [`mix`] fills from the other colour. +type Operand = (Color, Option, Option<&'static str>, bool); + +fn operand(s: &str, profile: ColorProfile, depth: usize) -> Result { let words = split_top(s, char::is_whitespace); let pct = |w: &str| w.strip_suffix('%').and_then(|p| p.parse::().ok()).filter(|p| p.is_finite()); let (color, p) = match words.as_slice() { @@ -249,12 +259,19 @@ fn operand(s: &str, profile: ColorProfile, depth: usize) -> Result<(Color, Optio [p, c] if pct(p).is_some() => (*c, pct(p)), _ => return Err("a mix colour is a colour and an optional percentage"), }; - let (c, why) = if color.starts_with("color(") || color.starts_with("color-mix(") { - eval(color, profile, depth + 1)? + let (c, why, alpha_missing) = if color.starts_with("color(") || color.starts_with("color-mix(") { + let (c, why) = eval(color, profile, depth + 1)?; + (c, why, false) } else { - (Color::parse_css(color).ok_or("a mix colour isn't read")?, None) + (Color::parse_css(color).ok_or("a mix colour isn't read")?, None, alpha_is_none(color)) }; - Ok((c, p, why)) + Ok((c, p, why, alpha_missing)) +} + +/// Whether a colour function's text (already lower case) gives its alpha as `none`: what follows +/// its last `/`. +fn alpha_is_none(color: &str) -> bool { + color.rsplit_once('/').is_some_and(|(_, rest)| rest.trim().trim_end_matches(')').trim_end() == "none") } /// `a` and `b` mixed `t` of the way to `b`, premultiplied by their alpha. diff --git a/crates/svg/src/import/css_color_tests.rs b/crates/svg/src/import/css_color_tests.rs index dbf3856a0..1c7177e1c 100644 --- a/crates/svg/src/import/css_color_tests.rs +++ b/crates/svg/src/import/css_color_tests.rs @@ -73,6 +73,12 @@ fn color_mix_in_srgb_oklab_and_oklch() { // Percentages under 100% lower the alpha; alphas mix premultiplied. assert_eq!(rgba8(fill("color-mix(in srgb, red 20%, blue 20%)").0), Some([128, 0, 128, 102])); assert_eq!(rgba8(fill("color-mix(in srgb, red, transparent)").0), Some([255, 0, 0, 128])); + // A missing alpha (`/ none`) takes the other colour's before the mix (CSS Color 5 section 4.1); + // on its own the same colour renders transparent. + assert_eq!(rgba8(fill("color-mix(in srgb, rgb(255 0 0 / none), blue)").0), Some([128, 0, 128, 255])); + assert_eq!(rgba8(fill("color-mix(in srgb, red, rgb(0 0 255 / none) 50%)").0), Some([128, 0, 128, 255])); + assert_eq!(rgba8(fill("color-mix(in srgb, rgb(255 0 0 / none), rgb(0 0 255 / 50%))").0), Some([128, 0, 128, 128])); + assert_eq!(rgba8(fill("color-mix(in srgb, rgb(255 0 0 / none), rgb(0 0 255 / none))").0), Some([128, 0, 128, 0]), "both missing: zero"); // Nested, with color() inside. assert_eq!(rgba8(fill("color-mix(in srgb, color-mix(in srgb, red, blue), color(srgb 0 1 0) 0%)").0), Some([128, 0, 128, 255])); } From 16d97cf8e96ab81868e192e1e78930f47d01c67c Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 00:33:58 -0400 Subject: [PATCH 006/102] M6: SVG import: a stretched image stays stretched, and a dash offset on a closed outline is kept Found while testing crates/svg import (no existing issue), each with a test that fails before and passes after. An took ImageScaleMode::Fill, which keeps the picture aspect and crops; a box of a different aspect now takes a whole-picture Crop, which the renderer draws as a stretch (SVG 2 section 8.6). A stroke-dashoffset equal to half the first dash was skipped on every shape because an open line starts half a dash in by itself; a closed outline runs its pattern from its start, so the exemption now applies to open outlines only (SVG 2 section 13.5.6). Co-Authored-By: Claude Fable 5.1 --- crates/svg/src/import.rs | 72 +++++++++++++++++++----- crates/svg/src/import/structure_tests.rs | 39 +++++++++++++ crates/svg/src/import/text.rs | 2 +- 3 files changed, 99 insertions(+), 14 deletions(-) diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 71c6c3b05..ed390ca4a 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -374,8 +374,11 @@ fn path(cx: &mut Ctx, p: &usvg::Path, parent: NodeId, base: Affine) { let local = to_bez(p.data()); let (fill, stroke) = (p.fill(), p.stroke()); let shaped = shape::recognize(&local, stroke.is_none()).and_then(|prim| primitive(prim, world)); - let (kind, transform, w, h, radius) = match shaped { - Some(s) => s, + let (kind, transform, w, h, radius, closed_outline) = match shaped { + Some((kind, transform, w, h, radius)) => { + let closed_outline = !matches!(kind, NodeKind::Line); + (kind, transform, w, h, radius, closed_outline) + } None => { let mut path = local; path.apply_affine(world); @@ -406,7 +409,10 @@ fn path(cx: &mut Ctx, p: &usvg::Path, parent: NodeId, base: Affine) { let fill_only = Node::new(cx.doc.alloc_id(), vector(&closed, true), format!("{} fill", layer_name(p.id(), "Vector")), bb.width(), bb.height()); let stroke_only = Node::new(cx.doc.alloc_id(), vector(&snapped, false), layer_name(p.id(), "Vector"), bb.width(), bb.height()); - let mut layers = [paint_path(cx, p, fill_only, at, world, true, false), paint_path(cx, p, stroke_only, at, world, false, true)]; + let mut layers = [ + paint_path(cx, p, fill_only, at, world, Paints { fill: true, stroke: false, closed: true }), + paint_path(cx, p, stroke_only, at, world, Paints { fill: false, stroke: true, closed: every_subpath_closed(&snapped) }), + ]; if p.paint_order() == usvg::PaintOrder::StrokeAndFill { layers.reverse(); } @@ -415,7 +421,8 @@ fn path(cx: &mut Ctx, p: &usvg::Path, parent: NodeId, base: Affine) { } return; } - (vector(if fill.is_some() { &closed } else { &path }, fill.is_some()), at, bb.width(), bb.height(), 0.0) + let outline = if fill.is_some() { &closed } else { &path }; + (vector(outline, fill.is_some()), at, bb.width(), bb.height(), 0.0, every_subpath_closed(outline)) } }; let fallback = match kind { @@ -426,19 +433,28 @@ fn path(cx: &mut Ctx, p: &usvg::Path, parent: NodeId, base: Affine) { }; let mut n = Node::new(cx.doc.alloc_id(), kind, layer_name(p.id(), fallback), w, h); n.corners.radii = [radius; 4]; - let n = paint_path(cx, p, n, transform, world, true, true); + let n = paint_path(cx, p, n, transform, world, Paints { fill: true, stroke: true, closed: closed_outline }); cx.add(n, parent); } +/// Which of a path's paints a layer takes, and whether its stroked outline closes on itself (see +/// [`stroke_props`]). +#[derive(Clone, Copy)] +struct Paints { + fill: bool, + stroke: bool, + closed: bool, +} + /// Layer `n` of path `p` placed at `transform`, with the path's fill and / or stroke. -fn paint_path(cx: &mut Ctx, p: &usvg::Path, mut n: Node, transform: Affine, world: Affine, with_fill: bool, with_stroke: bool) -> Node { +fn paint_path(cx: &mut Ctx, p: &usvg::Path, mut n: Node, transform: Affine, world: Affine, paints: Paints) -> Node { n.transform = transform; let target = Target { to_node: transform.inverse() * world, size: (n.width, n.height) }; - n.fills = p.fill().filter(|_| with_fill).and_then(|f| paint::paint(cx, f.paint(), f.opacity().get(), target)).into_iter().collect(); + n.fills = p.fill().filter(|_| paints.fill).and_then(|f| paint::paint(cx, f.paint(), f.opacity().get(), target)).into_iter().collect(); n.strokes.clear(); - if let Some(s) = p.stroke().filter(|_| with_stroke) { + if let Some(s) = p.stroke().filter(|_| paints.stroke) { n.strokes = paint::paint(cx, s.paint(), s.opacity().get(), target).into_iter().collect(); - n.stroke = stroke_props(s, length_scale(world)); + n.stroke = stroke_props(s, length_scale(world), paints.closed); // A stroke painted under the fill shows only its outer half. if p.paint_order() == usvg::PaintOrder::StrokeAndFill && !n.fills.is_empty() && figcraft_doc::geometry::is_closed(&n) { n.stroke.align = StrokeAlign::Outside; @@ -521,7 +537,27 @@ fn primitive(prim: Prim, world: Affine) -> Option<(NodeKind, Affine, f64, f64, f } } -pub(crate) fn stroke_props(s: &usvg::Stroke, k: f64) -> figcraft_doc::StrokeProps { +/// Whether every subpath of `path` closes on itself (and a dash pattern on it runs from its start, +/// as on any closed outline; an open one starts half a dash in). +fn every_subpath_closed(path: &BezPath) -> bool { + use figcraft_geom::kurbo::PathEl; + let els = path.elements(); + let mut closed = true; + for e in els { + match e { + PathEl::MoveTo(_) if !closed => return false, + PathEl::ClosePath => closed = true, + _ => closed = false, + } + } + !els.is_empty() && closed +} + +/// The stroke of `s` on a layer whose lengths `world` scales by `k`; `closed` says whether its +/// outline closes on itself: a closed outline runs a dash pattern from its start, so an offset into +/// the pattern rotates it, while an open line starts half a dash in by itself (and export writes +/// that offset), so that one is already there. +pub(crate) fn stroke_props(s: &usvg::Stroke, k: f64, closed: bool) -> figcraft_doc::StrokeProps { let cap = match s.linecap() { usvg::LineCap::Round => StrokeCap::Round, usvg::LineCap::Square => StrokeCap::Square, @@ -530,8 +566,8 @@ pub(crate) fn stroke_props(s: &usvg::Stroke, k: f64) -> figcraft_doc::StrokeProp let mut dashes: Vec = s.dasharray().unwrap_or(&[]).iter().map(|v| f64::from(*v) * k).collect(); if !dashes.is_empty() { let offset = f64::from(s.dashoffset()) * k; - // Half a dash in is how a line starts by itself (and how export writes one). - if dashes.first().is_none_or(|d| (d / 2.0 - offset).abs() > 1e-3) { + let half_dash_in = !closed && dashes.first().is_some_and(|d| (d / 2.0 - offset).abs() <= 1e-3); + if !half_dash_in { dashes = dash_offset(&dashes, offset, cap == StrokeCap::None).unwrap_or(dashes); } } @@ -608,7 +644,17 @@ fn image(cx: &mut Ctx, img: &usvg::Image, id: &str, parent: NodeId, base: Affine let hash = add_image(cx.doc, bytes, iw, ih); let mut n = Node::new(cx.doc.alloc_id(), NodeKind::Rectangle, layer_name(id, "Image"), w, h); n.transform = transform; - n.fills = vec![Paint::image(hash, ImageScaleMode::Fill)]; + let mut fill = Paint::image(hash, ImageScaleMode::Fill); + // usvg sizes the box to the picture (`meet` and `slice` are in the transform), so a box of + // another shape is `preserveAspectRatio="none"`: the picture stretched edge to edge. A Fill + // would keep its shape and crop it; a crop of the whole picture stretches it. + if (w * ih - h * iw).abs() > 1e-6 * (w * ih).max(h * iw) + && let figcraft_color::PaintKind::Image(ip) = &mut fill.kind + { + ip.scale_mode = ImageScaleMode::Crop; + ip.crop = Some(Affine::IDENTITY.as_coeffs()); + } + n.fills = vec![fill]; cx.add(n, parent); } diff --git a/crates/svg/src/import/structure_tests.rs b/crates/svg/src/import/structure_tests.rs index adeedb005..ee76c2238 100644 --- a/crates/svg/src/import/structure_tests.rs +++ b/crates/svg/src/import/structure_tests.rs @@ -129,6 +129,45 @@ fn strokes_scale_with_their_layer() { assert_eq!((l.width, l.stroke.weight, l.stroke.dashes.clone()), (30.0, 6.0, vec![12.0, 6.0])); } +/// `stroke-dashoffset` is how far into the pattern the stroke starts. A closed outline runs the +/// pattern from its start, so the offset rotates the pattern; an open line starts half a dash in by +/// itself (see `figcraft_pathops::width::line_dashes`), so an offset of half the first dash is +/// already there and only that one is left out. +#[test] +fn a_closed_outline_keeps_a_dash_offset_of_half_a_dash() { + let (d, f) = import( + r##""##, + ); + // Two in: a dash of 2 is left, then the gap, then the pattern as it is (`dash_offset`). + let rotated = vec![2.0, 2.0, 2.0, 0.0]; + assert_eq!(node(&d, f, "r").stroke.dashes, rotated, "rectangle"); + assert_eq!(node(&d, f, "p").stroke.dashes, rotated, "closed path"); + assert_eq!(node(&d, f, "c").stroke.dashes, rotated, "circle"); + assert_eq!(node(&d, f, "l").stroke.dashes, vec![4.0, 2.0], "an open line starts half a dash in anyway"); +} + +/// `preserveAspectRatio="none"` stretches a picture into its box edge to edge. usvg sizes the +/// box to the picture for `meet` and `slice` (the fit is in the transform), so a box of another +/// shape is a stretch: a Fill, which keeps the picture's shape and crops it, would show the +/// middle of the picture instead. +#[test] +fn an_image_stretched_into_its_box_stays_stretched() { + use figcraft_color::{ImageScaleMode, PaintKind}; + let (d, f) = + import(&format!(r##""##)); + let n = node(&d, f, "pic"); + assert_eq!((n.width, n.height), (40.0, 40.0)); + let Some(PaintKind::Image(ip)) = n.fills.first().map(|p| &p.kind) else { panic!("{:?}", n.fills) }; + // The 4 × 2 picture's pixels map onto the whole 40 × 40 box: 10 across, 20 down. + let m = figcraft_render::paint::image_transform(ip, 4.0, 2.0, n.width, n.height); + assert_eq!((m.sx, m.ky, m.kx, m.sy, m.tx, m.ty), (10.0, 0.0, 0.0, 20.0, 0.0, 0.0), "{ip:?}"); + // With the aspect kept (the default) the box is the picture's own shape and a Fill is exact. + let (d, f) = import(&format!(r##""##)); + let n = node(&d, f, "pic"); + assert_eq!((n.width, n.height), (40.0, 20.0)); + assert!(matches!(n.fills.first().map(|p| &p.kind), Some(PaintKind::Image(i)) if i.scale_mode == ImageScaleMode::Fill), "{:?}", n.fills); +} + #[test] fn linked_files_are_never_read() { let dir = std::env::temp_dir().join("figcraft-svg-linked"); diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index b651f859b..cee54bbd8 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -340,7 +340,7 @@ fn add_layer(cx: &mut Ctx, layer: TextLayer<'_, '_, '_>) { n.fills = base_fill; if let Some(st) = spans.first().and_then(|sp| sp.stroke()) { n.strokes = paint(cx, st.paint(), st.opacity().get(), target).into_iter().collect(); - n.stroke = super::stroke_props(st, s); + n.stroke = super::stroke_props(st, s, true); } cx.add(n, parent); } From 8b6c92796eb3492968ae8fdfaadb207496892101 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 00:39:38 -0400 Subject: [PATCH 007/102] SVG color-mix(): every missing component is carried over, through nested mixes too Review follow-up on #1773: the carry-forward now covers red, green and blue in an sRGB mix (converted first in another space, so zero there, per CSS Color 5 section 4.1 on analogous components) as well as the alpha in every mix, and a component missing in both colours stays missing in the result, so an enclosing mix carries it from its other colour. Co-Authored-By: Claude Fable 5.1 --- crates/svg/src/import/css_color.rs | 87 ++++++++++++++++++------ crates/svg/src/import/css_color_tests.rs | 7 ++ 2 files changed, 72 insertions(+), 22 deletions(-) diff --git a/crates/svg/src/import/css_color.rs b/crates/svg/src/import/css_color.rs index e330959fe..9301275ed 100644 --- a/crates/svg/src/import/css_color.rs +++ b/crates/svg/src/import/css_color.rs @@ -27,8 +27,50 @@ const GREY_CHROMA: f32 = 0.000_2; /// The attributes that can hold a colour (with `style`, which can hold any property). const COLOR_ATTRS: [&str; 8] = ["fill", "stroke", "stop-color", "flood-color", "lighting-color", "color", "solid-color", "style"]; -/// A colour read from a call, with why it is only an approximation; or why it can't be read. -type Eval = Result<(Color, Option<&'static str>), &'static str>; +/// A colour read from a call, with why it is only an approximation (or why it can't be read) and +/// which of its components a mix should treat as missing. +type Eval = Result<(Color, Option<&'static str>, Missing), &'static str>; + +/// Which components a colour gave as `none`: red, green, blue and alpha. A mix takes a missing +/// component from its other colour before interpolating (CSS Color 5 section 4.1): red, green and +/// blue only in an sRGB mix (in another space they are converted first, and a missing one is 0), +/// the alpha in every mix. Missing in both colours, a component stays missing (and 0). +#[derive(Clone, Copy)] +struct Missing { + r: bool, + g: bool, + b: bool, + a: bool, +} + +impl Missing { + const NONE: Self = Self { r: false, g: false, b: false, a: false }; + + /// What a colour function's text (lower case) gives as `none`: the four values of `rgb()` or + /// `rgba()`, else only an alpha after a `/`. + fn of(color: &str) -> Self { + let rgb = color.strip_prefix("rgba(").or_else(|| color.strip_prefix("rgb(")).and_then(|r| r.strip_suffix(')')); + match rgb { + Some(inner) => { + let parts = split_top(inner, |c| c == ',' || c == '/' || c.is_whitespace()); + let at = |i: usize| parts.get(i).is_some_and(|p| *p == "none"); + Self { r: at(0), g: at(1), b: at(2), a: at(3) } + } + None => Self { a: alpha_is_none(color), ..Self::NONE }, + } + } +} + +/// Fill a component missing on one side from the other; true when it is missing on both. +fn carry(a: &mut f32, b: &mut f32, a_missing: bool, b_missing: bool) -> bool { + match (a_missing, b_missing) { + (true, false) => *a = *b, + (false, true) => *b = *a, + (true, true) => return true, + (false, false) => {} + } + false +} /// `data` with its `color()` and `color-mix()` calls replaced by colours usvg reads, and notes on /// those it read only approximately or not at all; `None` when there are none (or `data` isn't @@ -90,8 +132,8 @@ fn rewrite_calls(text: &str, range: Range, profile: ColorProfile, edits: }; let call = s.get(start..end).unwrap_or_default(); let color = match eval(call, profile, 0) { - Ok((c, None)) => c, - Ok((c, Some(why))) => { + Ok((c, None, _)) => c, + Ok((c, Some(why), _)) => { notes.push(note(call, why)); c } @@ -181,7 +223,7 @@ fn color_fn(args: &str, profile: ColorProfile) -> Eval { "display-p3" => (ColorProfile::DisplayP3, None), _ => (ColorProfile::Srgb, Some("only the srgb and display-p3 spaces are read: its values were taken as sRGB")), }; - Ok((from.conversion_to(profile).apply(c), why)) + Ok((from.conversion_to(profile).apply(c), why, Missing::NONE)) } /// A CSS number, a percentage (100% is 1) or `none` (0); finite only. @@ -219,15 +261,17 @@ fn mix(args: &str, profile: ColorProfile, depth: usize) -> Eval { ["in", ..] => (Space::Srgb, Some("only srgb, oklab and oklch mixes are read: it was mixed in sRGB")), _ => return Err("color-mix() starts with `in` and a colour space"), }; - let (a, pa, why_a, a_none) = operand(first, profile, depth)?; - let (b, pb, why_b, b_none) = operand(second, profile, depth)?; + let (mut a, pa, why_a, ma) = operand(first, profile, depth)?; + let (mut b, pb, why_b, mb) = operand(second, profile, depth)?; why = why.or(why_a).or(why_b); - // A missing alpha (`/ none`) is carried over from the other colour before the mix (CSS Color 5 - // section 4.1); rendered on its own the same colour is transparent. - let (a, b) = match (a_none, b_none) { - (true, false) => (a.with_alpha(b.a), b), - (false, true) => (a, b.with_alpha(a.a)), - _ => (a, b), + // Missing components are carried over from the other colour before the mix (see `Missing`); + // rendered on its own, the same colour has them at 0. + let srgb = matches!(space, Space::Srgb); + let missing = Missing { + r: srgb && carry(&mut a.r, &mut b.r, ma.r, mb.r), + g: srgb && carry(&mut a.g, &mut b.g, ma.g, mb.g), + b: srgb && carry(&mut a.b, &mut b.b, ma.b, mb.b), + a: carry(&mut a.a, &mut b.a, ma.a, mb.a), }; if [pa, pb].into_iter().flatten().any(|p| !(0.0..=100.0).contains(&p)) { return Err("mix percentages are between 0% and 100%"); @@ -243,12 +287,12 @@ fn mix(args: &str, profile: ColorProfile, depth: usize) -> Eval { return Err("mix percentages add up to 0%"); } let mixed = interpolate(space, a, b, pb / sum); - Ok((mixed.with_alpha(mixed.a * (sum / 100.0).min(1.0)), why)) + Ok((mixed.with_alpha(mixed.a * (sum / 100.0).min(1.0)), why, missing)) } -/// One colour of a mix: the colour, its percentage (before or after it), a note, and whether its -/// alpha is missing (`rgb(255 0 0 / none)`), which [`mix`] fills from the other colour. -type Operand = (Color, Option, Option<&'static str>, bool); +/// One colour of a mix: the colour, its percentage (before or after it), a note, and the +/// components it gave as `none` (see [`Missing`]). +type Operand = (Color, Option, Option<&'static str>, Missing); fn operand(s: &str, profile: ColorProfile, depth: usize) -> Result { let words = split_top(s, char::is_whitespace); @@ -259,13 +303,12 @@ fn operand(s: &str, profile: ColorProfile, depth: usize) -> Result (*c, pct(p)), _ => return Err("a mix colour is a colour and an optional percentage"), }; - let (c, why, alpha_missing) = if color.starts_with("color(") || color.starts_with("color-mix(") { - let (c, why) = eval(color, profile, depth + 1)?; - (c, why, false) + let (c, why, missing) = if color.starts_with("color(") || color.starts_with("color-mix(") { + eval(color, profile, depth + 1)? } else { - (Color::parse_css(color).ok_or("a mix colour isn't read")?, None, alpha_is_none(color)) + (Color::parse_css(color).ok_or("a mix colour isn't read")?, None, Missing::of(color)) }; - Ok((c, p, why, alpha_missing)) + Ok((c, p, why, missing)) } /// Whether a colour function's text (already lower case) gives its alpha as `none`: what follows diff --git a/crates/svg/src/import/css_color_tests.rs b/crates/svg/src/import/css_color_tests.rs index 1c7177e1c..ee66b42da 100644 --- a/crates/svg/src/import/css_color_tests.rs +++ b/crates/svg/src/import/css_color_tests.rs @@ -79,6 +79,13 @@ fn color_mix_in_srgb_oklab_and_oklch() { assert_eq!(rgba8(fill("color-mix(in srgb, red, rgb(0 0 255 / none) 50%)").0), Some([128, 0, 128, 255])); assert_eq!(rgba8(fill("color-mix(in srgb, rgb(255 0 0 / none), rgb(0 0 255 / 50%))").0), Some([128, 0, 128, 128])); assert_eq!(rgba8(fill("color-mix(in srgb, rgb(255 0 0 / none), rgb(0 0 255 / none))").0), Some([128, 0, 128, 0]), "both missing: zero"); + // A missing red, green or blue is carried over as well in an sRGB mix; in another space the + // converted channels are plain zeros (only analogous components carry, CSS Color 5 section 4.1). + assert_eq!(rgba8(fill("color-mix(in srgb, rgb(none 0 0), red)").0), Some([255, 0, 0, 255])); + assert_eq!(rgba8(fill("color-mix(in srgb, rgb(none 0 0), rgb(255 none 0))").0), Some([255, 0, 0, 255])); + assert_eq!(rgba8(fill("color-mix(in oklab, rgb(none 0 0), red)").0), rgba8(fill("color-mix(in oklab, black, red)").0)); + // Missing in both stays missing through a nested mix and is carried in the outer one. + assert_eq!(rgba8(fill("color-mix(in srgb, color-mix(in srgb, rgb(0 255 0 / none), rgb(0 255 0 / none)), red)").0), Some([128, 128, 0, 255])); // Nested, with color() inside. assert_eq!(rgba8(fill("color-mix(in srgb, color-mix(in srgb, red, blue), color(srgb 0 1 0) 0%)").0), Some([128, 0, 128, 255])); } From f797cbe0291f3e862ceb00914c6ab62529df9c7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Max=20Mittelst=C3=A4dt?= <62167861+TheGalitube@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:39:49 +0000 Subject: [PATCH 008/102] Reject duplicate Kiwi field IDs Found while testing crates/format/src/fig/kiwi.rs:615 Co-Authored-By: GPT-5.6-Luna Co-Authored-By: GPT-6-Luna --- crates/format/src/fig/kiwi.rs | 6 ++++++ crates/format/src/fig/tests.rs | 5 +++++ 2 files changed, 11 insertions(+) diff --git a/crates/format/src/fig/kiwi.rs b/crates/format/src/fig/kiwi.rs index d34b3774d..26e8284e4 100644 --- a/crates/format/src/fig/kiwi.rs +++ b/crates/format/src/fig/kiwi.rs @@ -270,6 +270,9 @@ impl Schema { let ty = r.var_int()?; let array = r.byte()? & 1 != 0; let value = r.var_uint()?; + if kind == Kind::Message && fields.iter().any(|f: &Field| f.value == value) { + return err(format!("schema: duplicate field id {value} in {name}")); + } raw_types.push(ty); fields.push(Field { name: fname, ty: None, array, value }); } @@ -621,6 +624,9 @@ impl Schema { } .ok_or_else(|| KiwiError(format!("schema text: unknown type {base}")))?; let (name, value) = numbered(n.trim(), id)?; + if *kind == "message" && fields.iter().any(|f: &Field| f.value == value) { + return err(format!("schema text: duplicate field id {value} in {name}")); + } fields.push(Field { name, ty: Some(ty), array: t.ends_with("[]"), value }); } (if *kind == "struct" { Kind::Struct } else { Kind::Message }, fields) diff --git a/crates/format/src/fig/tests.rs b/crates/format/src/fig/tests.rs index 657f2f81d..50c50c3d0 100644 --- a/crates/format/src/fig/tests.rs +++ b/crates/format/src/fig/tests.rs @@ -562,6 +562,11 @@ fn oversized_grid_track_lists_warn_and_use_default_tracks() { assert!(warnings.iter().any(|w| w.contains("grid track list exceeds 1000 entries")), "{warnings:?}"); } +#[test] +fn duplicate_explicit_field_ids_are_ambiguous() { + assert!(Schema::parse("message M uint a=1, uint b=1").is_err()); +} + #[test] fn kiwi_round_trip() { let sc = schema(); From d72f0961867826c6bf9983b40734ada6e1dab70e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 11:54:35 -0500 Subject: [PATCH 009/102] M8: color-mix(): a none in color() is a missing component too Co-Authored-By: Claude Fable 5.1 --- crates/svg/src/import/css_color.rs | 5 ++++- crates/svg/src/import/css_color_tests.rs | 9 +++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/svg/src/import/css_color.rs b/crates/svg/src/import/css_color.rs index 9301275ed..715883de8 100644 --- a/crates/svg/src/import/css_color.rs +++ b/crates/svg/src/import/css_color.rs @@ -218,12 +218,15 @@ fn color_fn(args: &str, profile: ColorProfile) -> Eval { None => 1.0, }; let c = Color::new(value(r)?, value(g)?, value(b)?, a); + // A `none` is 0 here and missing in a mix: reds, greens and blues are analogous across the RGB + // spaces (CSS Color 4 section 12.2), so a missing channel stays missing through the conversion. + let missing = Missing { r: *r == "none", g: *g == "none", b: *b == "none", a: alpha == Some("none") }; let (from, why) = match *space { "srgb" => (ColorProfile::Srgb, None), "display-p3" => (ColorProfile::DisplayP3, None), _ => (ColorProfile::Srgb, Some("only the srgb and display-p3 spaces are read: its values were taken as sRGB")), }; - Ok((from.conversion_to(profile).apply(c), why, Missing::NONE)) + Ok((from.conversion_to(profile).apply(c), why, missing)) } /// A CSS number, a percentage (100% is 1) or `none` (0); finite only. diff --git a/crates/svg/src/import/css_color_tests.rs b/crates/svg/src/import/css_color_tests.rs index ee66b42da..c327fee01 100644 --- a/crates/svg/src/import/css_color_tests.rs +++ b/crates/svg/src/import/css_color_tests.rs @@ -86,6 +86,15 @@ fn color_mix_in_srgb_oklab_and_oklch() { assert_eq!(rgba8(fill("color-mix(in oklab, rgb(none 0 0), red)").0), rgba8(fill("color-mix(in oklab, black, red)").0)); // Missing in both stays missing through a nested mix and is carried in the outer one. assert_eq!(rgba8(fill("color-mix(in srgb, color-mix(in srgb, rgb(0 255 0 / none), rgb(0 255 0 / none)), red)").0), Some([128, 128, 0, 255])); + // `color()` gives its `none` values the same way, in either of its spaces (reds, greens and + // blues are analogous across RGB spaces, CSS Color 4 section 12.2). + assert_eq!(rgba8(fill("color-mix(in srgb, color(srgb 1 0 0 / none), blue)").0), Some([128, 0, 128, 255])); + assert_eq!(rgba8(fill("color-mix(in srgb, color(srgb none 0 0), red)").0), Some([255, 0, 0, 255])); + assert_eq!(rgba8(fill("color-mix(in srgb, color(display-p3 none 0 0), red)").0), Some([255, 0, 0, 255])); + assert_eq!( + rgba8(fill("color-mix(in srgb, color-mix(in srgb, color(srgb 0 1 0 / none), color(srgb 0 1 0 / none)), red)").0), + Some([128, 128, 0, 255]) + ); // Nested, with color() inside. assert_eq!(rgba8(fill("color-mix(in srgb, color-mix(in srgb, red, blue), color(srgb 0 1 0) 0%)").0), Some([128, 0, 128, 255])); } From 8bc405edbccc73ed07f9373bf1c173a7e9b22bee Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 12:16:33 -0500 Subject: [PATCH 010/102] SVG import: the dash offset fix alone, with open-path, mixed-subpath and text tests The stretched-image fix moved to its own PR. Co-Authored-By: Claude Fable 5.1 --- crates/svg/src/import.rs | 12 +------ crates/svg/src/import/structure_tests.rs | 41 +++++++++++++----------- 2 files changed, 23 insertions(+), 30 deletions(-) diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index ed390ca4a..e154ab1c9 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -644,17 +644,7 @@ fn image(cx: &mut Ctx, img: &usvg::Image, id: &str, parent: NodeId, base: Affine let hash = add_image(cx.doc, bytes, iw, ih); let mut n = Node::new(cx.doc.alloc_id(), NodeKind::Rectangle, layer_name(id, "Image"), w, h); n.transform = transform; - let mut fill = Paint::image(hash, ImageScaleMode::Fill); - // usvg sizes the box to the picture (`meet` and `slice` are in the transform), so a box of - // another shape is `preserveAspectRatio="none"`: the picture stretched edge to edge. A Fill - // would keep its shape and crop it; a crop of the whole picture stretches it. - if (w * ih - h * iw).abs() > 1e-6 * (w * ih).max(h * iw) - && let figcraft_color::PaintKind::Image(ip) = &mut fill.kind - { - ip.scale_mode = ImageScaleMode::Crop; - ip.crop = Some(Affine::IDENTITY.as_coeffs()); - } - n.fills = vec![fill]; + n.fills = vec![Paint::image(hash, ImageScaleMode::Fill)]; cx.add(n, parent); } diff --git a/crates/svg/src/import/structure_tests.rs b/crates/svg/src/import/structure_tests.rs index ee76c2238..500675fe4 100644 --- a/crates/svg/src/import/structure_tests.rs +++ b/crates/svg/src/import/structure_tests.rs @@ -146,26 +146,29 @@ fn a_closed_outline_keeps_a_dash_offset_of_half_a_dash() { assert_eq!(node(&d, f, "l").stroke.dashes, vec![4.0, 2.0], "an open line starts half a dash in anyway"); } -/// `preserveAspectRatio="none"` stretches a picture into its box edge to edge. usvg sizes the -/// box to the picture for `meet` and `slice` (the fit is in the transform), so a box of another -/// shape is a stretch: a Fill, which keeps the picture's shape and crops it, would show the -/// middle of the picture instead. +/// An open path is a line in this respect: half a dash in is where it starts anyway, so that +/// offset is left out, and any other is applied; an outline with an open subpath among closed +/// ones is open. #[test] -fn an_image_stretched_into_its_box_stays_stretched() { - use figcraft_color::{ImageScaleMode, PaintKind}; - let (d, f) = - import(&format!(r##""##)); - let n = node(&d, f, "pic"); - assert_eq!((n.width, n.height), (40.0, 40.0)); - let Some(PaintKind::Image(ip)) = n.fills.first().map(|p| &p.kind) else { panic!("{:?}", n.fills) }; - // The 4 × 2 picture's pixels map onto the whole 40 × 40 box: 10 across, 20 down. - let m = figcraft_render::paint::image_transform(ip, 4.0, 2.0, n.width, n.height); - assert_eq!((m.sx, m.ky, m.kx, m.sy, m.tx, m.ty), (10.0, 0.0, 0.0, 20.0, 0.0, 0.0), "{ip:?}"); - // With the aspect kept (the default) the box is the picture's own shape and a Fill is exact. - let (d, f) = import(&format!(r##""##)); - let n = node(&d, f, "pic"); - assert_eq!((n.width, n.height), (40.0, 20.0)); - assert!(matches!(n.fills.first().map(|p| &p.kind), Some(PaintKind::Image(i)) if i.scale_mode == ImageScaleMode::Fill), "{:?}", n.fills); +fn an_open_path_starts_half_a_dash_in_and_takes_other_offsets() { + let (d, f) = import( + r##""##, + ); + assert_eq!(node(&d, f, "half").stroke.dashes, vec![4.0, 2.0], "half a dash in is where an open path starts"); + assert_eq!(node(&d, f, "one").stroke.dashes, vec![3.0, 2.0, 1.0, 0.0], "one in: three of the first dash are left"); + assert_eq!(node(&d, f, "mixed").stroke.dashes, vec![4.0, 2.0], "an open subpath makes the outline open"); +} + +/// A text stroke runs along glyph contours, which close, so its offset is applied as on a shape. +#[test] +fn a_text_stroke_keeps_a_dash_offset_of_half_a_dash() { + if figcraft_text::fontdb::find_face("Inter", "Regular").is_none() { + return; + } + let (d, f) = import( + r##"T"##, + ); + assert_eq!(node(&d, f, "t").stroke.dashes, vec![2.0, 2.0, 2.0, 0.0]); } #[test] From 15bd733886ee1978e35aeb5ec831057596b61f9e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 23:51:07 -0500 Subject: [PATCH 011/102] Number fields: Alt held over the field scrubs it, as the label does Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/field_tests.rs | 23 +++++++++++++++++++ .../ui-egui/src/panels/typography/spacing.rs | 2 +- crates/ui-egui/src/widgets.rs | 23 +++++++++++++------ docs/ui-parity.md | 5 ++-- 4 files changed, 43 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 566f0828b..91fbae2b2 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -1194,3 +1194,26 @@ fn sidebar_field_text_stays_in_place_on_focus() { assert!((before.center().y - after.center().y).abs() <= 0.5, "numeric={numeric}: before={before:?}, after={after:?}"); } } + +/// "You can also hover the input field itself and hold down the modifier key: Mac: ⌥ Option +/// Windows: Alt" to scrub it (Adjust alignment, rotation, position, and dimensions). Alt is what +/// makes the drag a scrub there, not the fine rate: a point moves a step, as on the label. Without +/// Alt a drag on the field is no click, so it neither edits nor moves anything. +#[test] +fn alt_held_over_a_field_scrubs_it() { + let (mut u, a, _) = setup(); + let (at, _) = field(&mut u, "X"); + let steps = undo_steps(&u); + // Alt is held as the pointer arrives over the field, a frame before the press (the field takes + // a drag only once it has seen Alt; egui assigns a press by the frame before it). + let alt = Modifiers { alt: true, ..Modifiers::NONE }; + u.frame_with(vec![Event::PointerMoved(at)], alt); + drag(&mut u, at, 25.0, alt); + assert_eq!(geom(&u, a).0, 35.0, "a step a point: X from 10"); + assert_eq!(undo_steps(&u), steps + 1, "one undo step for the whole scrub"); + assert_eq!(field(&mut u, "X").1, "35", "the field shows it and isn't editing"); + let (at, _) = field(&mut u, "X"); + drag(&mut u, at, 25.0, Modifiers::NONE); + assert_eq!(geom(&u, a).0, 35.0, "without Alt the field doesn't scrub"); + assert_eq!(undo_steps(&u), steps + 1); +} diff --git a/crates/ui-egui/src/panels/typography/spacing.rs b/crates/ui-egui/src/panels/typography/spacing.rs index 5ffaf22a2..2adc119df 100644 --- a/crates/ui-egui/src/panels/typography/spacing.rs +++ b/crates/ui-egui/src/panels/typography/spacing.rs @@ -58,7 +58,7 @@ pub(super) fn spacing_input(ui: &mut Ui, field: &SpacingField, value: &str, widt ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); } let numeric = value.trim_end_matches('%').parse::().ok(); - match widgets::scrub(ui, field.id, &response, numeric, 1.0) { + match widgets::scrub(ui, field.id, &response, numeric, 1.0, true) { Some(FieldEdit::Scrub(v, done)) => Some(SpacingEdit::Scrub(v, done)), _ => typed.map(SpacingEdit::Typed), } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index c7e20bb1d..4ed92eb0d 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -132,8 +132,9 @@ pub fn scrubbed(from: f64, amount: f64, quantum: f64) -> f64 { } /// The shared label-scrub gesture, including changing modifier rates and raw edge motion. -/// Callers supply the hit area and apply live values until the final `Scrub(_, true)`. -pub(crate) fn scrub(ui: &Ui, id: Id, response: &Response, value: Option, step: f64) -> Option { +/// Callers supply the hit area and apply live values until the final `Scrub(_, true)`. `fine_on_alt`: +/// Alt gives tenths (off where Alt is what makes the drag a scrub at all). +pub(crate) fn scrub(ui: &Ui, id: Id, response: &Response, value: Option, step: f64, fine_on_alt: bool) -> Option { let v = value?; // Where the scrub began and how far it has taken the value (the modifiers can change on // the way: each stretch counts at its own rate). @@ -150,7 +151,7 @@ pub(crate) fn scrub(ui: &Ui, id: Id, response: &Response, value: Option, st // does too. Elsewhere the scrub just stops there. let raw = p.motion().map_or(0.0, |m| m.x / i.pixels_per_point); let at_edge = moved == 0.0 && p.hover_pos().is_none_or(|at| at.x <= 1.0 || at.x >= i.content_rect().max.x - 1.0); - (f64::from(if at_edge { raw } else { moved }), i.modifiers.shift, i.modifiers.alt) + (f64::from(if at_edge { raw } else { moved }), i.modifiers.shift, i.modifiers.alt && fine_on_alt) }); // The frame the button goes up moves nothing: the scrub ends where the last one left it. if response.dragged() { @@ -265,7 +266,12 @@ fn number_field_impl( let edit_rect = Rect::from_min_max(pos2(rect.min.x + lead_w, rect.min.y), rect.max); let editing_id = id.with("editing"); let mut editing: Option = ui.data(|d| d.get_temp(editing_id)); - let field_resp = ui.interact(edit_rect, id.with("field"), Sense::click()); + // Alt held over the field scrubs it too, as the label always does: "hover the input field + // itself and hold down the modifier key" (Adjust alignment, rotation, position, and + // dimensions). The drag sense stays on until a scrub begun that way is let go. + let field_id = id.with("field"); + let alt_scrub = editing.is_none() && (ui.input(|i| i.modifiers.alt) || ui.ctx().is_being_dragged(field_id)); + let field_resp = ui.interact(edit_rect, field_id, if alt_scrub { Sense::CLICK | Sense::DRAG } else { Sense::click() }); a11y::number(&field_resp, lead.name(), value, suffix, empty.text()); a11y::ring_around(ui, rect, &field_resp); // The label scrubs with the pointer; the keyboard stops at the value only. @@ -291,10 +297,13 @@ fn number_field_impl( } Lead::None | Lead::Named(_) => {} } - if lead_resp.hovered() || lead_resp.dragged() { + if lead_resp.hovered() || lead_resp.dragged() || (alt_scrub && (field_resp.hovered() || field_resp.dragged())) { ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); } - if let Some(edit) = scrub(ui, id, &lead_resp, value, step) { + // On the field, Alt is what makes the drag a scrub, so it is not the fine rate there. + if let Some(edit) = + scrub(ui, id, &lead_resp, value, step, true).or_else(|| alt_scrub.then(|| scrub(ui, id, &field_resp, value, step, false)).flatten()) + { out = Some(Edit::All(edit)); } let (key_step, key_big) = key_steps(ui.ctx(), suffix, step); @@ -340,7 +349,7 @@ fn number_field_impl( } // Typing on a field the keyboard reached (Tab) edits it: the editor takes the typed text. let typed_now = editing.is_none() && on_field && ui.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Text(_)))); - let started = editing.is_none() && (field_resp.clicked() || typed_now); + let started = editing.is_none() && ((field_resp.clicked() && !alt_scrub) || typed_now); // The text the field would commit to no effect: what it showed when the edit began, or the // value the arrows last stepped it to. let kept_id = id.with("kept"); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 0286fd37d..6f453111b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -70,7 +70,7 @@ interaction feel not yet compared. | Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing | | Measure (Alt hover, Cmd+Alt nested, Shift+Alt padding/gaps) | done | labels never overlap; the arrows still nudge while measuring (Shift: the big step) and the distances follow; the selection's handles and size label hide while measuring (`measure_nudge_tests`, #894) | | Pixel grid snapping, pixel preview, 2x preview | done | moves, resizes and new shapes land on whole pixels; the pixel grid shows from 400% (`view_behaviour_tests`) | -| Numeric fields: arithmetic, scrubbing by dragging the label, mixed values | done | Numeric panels use `widgets::number_field`; Corner smoothing has an original code-drawn icon, a 24 pt drag target and an accessible name, with live changes, fractional values preserved across consecutive drags, Shift/Alt rates, 0–100% clamping and one-step undo/redo (`corner_individual_tests`); Typography line height, letter spacing and paragraph spacing share its leading-icon scrub logic (#373), retaining their existing unit parsing, Auto/Mixed values, variable chips and selected-character targeting (`typography_scrub_tests`). Scrubbing the label: a step a point (1 px; 1% of opacity, 1° of rotation), ten with Shift, a tenth with Alt, each stretch at the rate held while it was dragged, one undo step when let go; past the edge of the screen it goes on where the platform reports the mouse's own motion (desktop), otherwise it stops there. Arrow keys: Up/Down step a pixel field by the small nudge and Shift by the big nudge (the preferences), other fields by their own step and ten of it; they work while typing (from what is typed) and with the keyboard on the field. Typing: `+ - * /`, brackets, units (`px`, `°`, `%`, `x`, `ms`), a decimal comma; `+10`, `*2`, `/4` are relative to the value, and `50%`, `+10%`, `-10%` too in a field that isn't a percentage. Enter, Tab or a click elsewhere commits (Tab and Shift+Tab move to the next and previous control), Escape restores; a field left as it was commits nothing (no undo step, and a rounded display isn't written back). Mixed values show "Mixed": a number sets them all, a relative edit or an arrow key goes to each layer from its own value in one undo step, for X, Y, W, H, rotation, opacity, corner radius and stroke weight (elsewhere `+10` on Mixed sets 10 and `*2` does nothing) (`field_tests`). Left: scrubbing a Mixed field (nothing happens), `x2`-style suffix edits, the pointer isn't wrapped to the other side of the screen; rates not compared with Figma's | +| Numeric fields: arithmetic, scrubbing by dragging the label (or the field itself with Alt held), mixed values | done | Numeric panels use `widgets::number_field`; Corner smoothing has an original code-drawn icon, a 24 pt drag target and an accessible name, with live changes, fractional values preserved across consecutive drags, Shift/Alt rates, 0–100% clamping and one-step undo/redo (`corner_individual_tests`); Typography line height, letter spacing and paragraph spacing share its leading-icon scrub logic (#373), retaining their existing unit parsing, Auto/Mixed values, variable chips and selected-character targeting (`typography_scrub_tests`). Scrubbing the label: a step a point (1 px; 1% of opacity, 1° of rotation), ten with Shift, a tenth with Alt, each stretch at the rate held while it was dragged, one undo step when let go; past the edge of the screen it goes on where the platform reports the mouse's own motion (desktop), otherwise it stops there. Arrow keys: Up/Down step a pixel field by the small nudge and Shift by the big nudge (the preferences), other fields by their own step and ten of it; they work while typing (from what is typed) and with the keyboard on the field. Typing: `+ - * /`, brackets, units (`px`, `°`, `%`, `x`, `ms`), a decimal comma; `+10`, `*2`, `/4` are relative to the value, and `50%`, `+10%`, `-10%` too in a field that isn't a percentage. Enter, Tab or a click elsewhere commits (Tab and Shift+Tab move to the next and previous control), Escape restores; a field left as it was commits nothing (no undo step, and a rounded display isn't written back). Mixed values show "Mixed": a number sets them all, a relative edit or an arrow key goes to each layer from its own value in one undo step, for X, Y, W, H, rotation, opacity, corner radius and stroke weight (elsewhere `+10` on Mixed sets 10 and `*2` does nothing) (`field_tests`). Left: scrubbing a Mixed field (nothing happens), `x2`-style suffix edits, the pointer isn't wrapped to the other side of the screen; rates not compared with Figma's | | Transform box at small sizes | done | a press inside a layer smaller than its handles moves it, the nearest handle wins, handles answer just outside and are hidden under 16 px on screen; cursors follow each handle and the box's rotation | | Locked layers | done | selectable from the layers panel; no handles, not dragged with the rest of a selection | | Smart selection spacing | partial | with layers in a row, a column or an aligned grid selected, the Layout section shows horizontal and vertical spacing ("Mixed" until set; typed, scrubbed, fractional and negative) and pink handles in the gaps on the canvas drag them, one undo step, Escape cancels (`arrange.spacing`; sizes, parents and offsets within each track kept; at most 2,000 layers; flow children, locked layers and layers inside instances left out). A ring at each layer's centre drags it to another place in a regular row, column or complete top-left-aligned grid: the others close up and make room around it with the gaps kept, and with Cmd/Ctrl held the two layers swap places instead, previewed live while dragging (`selection_reorder_tests`; no ring on a layer under 16 px on screen). Not covered: reordering irregular grids, and several marked layers moved together. Checked by its author on macOS and in the app on Windows (#402) | @@ -176,6 +176,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-01 | patch | Number fields: dragging the field itself with Alt held scrubs it ("You can also hover the input field itself and hold down the modifier key: Mac: ⌥ Option Windows: Alt", Adjust alignment, rotation, position, and dimensions), with the resize cursor and the label's rates (Alt is the enabler there, so it isn't the fine rate); a click with Alt doesn't open the editor. Found by a documentation audit of the ui-parity rows. Test: `field_tests::alt_held_over_a_field_scrubs_it`. Counts unchanged | | 2026-10-31 | minor | M1, #1682: as the help center describes the colour picker, choosing Image no longer opens a file dialog at once: the tab shows a checkered placeholder and Upload from computer until there is a file. An image paint shows its asset preview with the same button. A file dropped on the open picker replaces the image and keeps the fill mode, crop, position and adjustments; on the placeholder it becomes the paint's image, filling the layer. While a file is dragged the picker says it takes it instead of the window saying Drop to import. New command `image.replace {ids?, target?, index?, data | path}`, through the same size cap and decoder as `image.place`; one undo step. Dropped files in the browser arrive as `data`. A native window or a browser doesn't say where a dragged file is, so a drop with no known position goes to the open picker, and one known to be over the canvas imports as before. Left: the Fill and Stroke swatches in the Design panel don't take a drop, since their place can't be told during a drag; pasting into the picker isn't documented and isn't added. Tests: `colorpicker_image_tests`, `image_crop_tests::replacing_an_image_keeps_its_fill_mode_crop_and_adjustments`. Numbers unchanged | | 2026-10-30 | minor | Gap 4: the keyboard's Menu key opens the context menu, as Shift+F10 does (at the focused layer row or below the canvas selection, with the keyboard in the menu). egui already reported the key; FigCraft's keymap had no name or binding for it. `view.contextMenu` now takes `Menu` too, and the Context menus row is done (`layers_keyboard_tests`). Stale rows corrected: smart-selection spacing has had reorder rings since the "M1: smart-selection drag reordering" landing (the row is still partial: irregular grids and several marked layers aren't covered), and gap 4 and the parity summary quoted shortcut counts from before the last bindings (now 128 bound, none missing, 57 undocumented pinned, as `shortcut_parity_tests` counts). | | 2026-10-30 | minor | M4, gap 4: the eyedropper with Cmd/Ctrl+Shift held makes a colour style or variable of the colour it picks, as the reference app's eyedropper does, instead of filling the selection. It asks the UI for a Create from color window (`dialog.createFromColor`; the control channel never opens it). The window shows the colour and offers Style or Variable, a name (the next free "Color n") and, for a variable, a collection: the file's first, or a new one made with it in the same undo step. Create runs `style.create` or `variable.create`. Tests: `eyedropper_create_tests`, `sampled_color_tests`. | From 55821565ac0a3ecc36268a72fa5a2aec9430bb53 Mon Sep 17 00:00:00 2001 From: samhyun Date: Mon, 2 Nov 2026 09:58:03 +0900 Subject: [PATCH 012/102] M8: a spread round a stroke with corners keeps its whole shadow A dashed stroke is cut into dashes with corners wherever they fall round the outline, and a width profile or a brush can give the stroke corners of its own. A drop shadow's spread mitres those corners out, but a whole ellipse or a box still counted as growing by exactly its spread, so the shadow was cut off at the layer's edge (up to 255 levels). Such a node now gets the room a star does. Whether the outline's own mitres end on its box is a check of its own, which the stroke's reach keeps using, so a node with no spread keeps its bounds. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/node.rs | 22 ++++++++++--- crates/render/src/spread_tests.rs | 55 +++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 3ac81afdb..e24057f7b 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -944,7 +944,7 @@ impl Node { if self.stroke.cap_start.is_arrow() || self.stroke.cap_end.is_arrow() || point_arrows { w.max(self.stroke.weight) * 3.0 } else { w }; // Right-angled or smooth outlines (boxes, whole ellipses) end their mitres on the grown // box; an arc's corners don't. - let miter = if self.grows_by_exactly_its_spread() { 1.0 } else { self.stroke.miter_limit.clamp(1.0, 4.0) }; + let miter = if self.outline_mitres_end_on_its_box() { 1.0 } else { self.stroke.miter_limit.clamp(1.0, 4.0) }; base.max(if matches!(self.kind, NodeKind::Line | NodeKind::Vector { .. }) { caps } else { 0.0 }) * miter } else { 0.0 @@ -960,9 +960,10 @@ impl Node { !(matches!(self.kind, NodeKind::Group) || (matches!(self.kind, NodeKind::Text(_)) && self.has_visible_stroke())) } - /// Whether a spread grows this node's outline by exactly the spread (no sharp corners). An arc - /// (an ellipse that doesn't go all the way round) has corners where its ends meet its sides. - fn grows_by_exactly_its_spread(&self) -> bool { + /// Whether this node's outline has no sharp corners (right-angled ones aside), so mitres along + /// it end on its box grown by as much: a box or a whole ellipse. An arc (an ellipse that doesn't + /// go all the way round) has corners where its ends meet its sides. + fn outline_mitres_end_on_its_box(&self) -> bool { match self.kind { NodeKind::Rectangle | NodeKind::Section { .. } => true, NodeKind::Ellipse { sweep, .. } => figcraft_geom::full_sweep(sweep), @@ -970,9 +971,20 @@ impl Node { } } + /// Whether a spread grows this node by exactly the spread: its outline mitres end on its box + /// (see [`Node::outline_mitres_end_on_its_box`]), and so does its stroke. A dashed stroke is + /// cut into dashes with corners wherever they fall round the outline, and a width profile or a + /// brush can give the stroke corners of its own, which the spread mitres out. + fn grows_by_exactly_its_spread(&self) -> bool { + let s = &self.stroke; + let cornered = self.has_visible_stroke() && (!s.dashes.is_empty() || s.profile().is_some() || s.brush.is_some()); + !cornered && self.outline_mitres_end_on_its_box() + } + /// How much further than its spread a drop shadow can reach at the outline's sharp corners: /// spread moves the edges out in parallel and they meet in a mitre (see - /// [`SPREAD_MITER_LIMIT`]). Rectangles, frames and whole ellipses grow by exactly the spread. + /// [`SPREAD_MITER_LIMIT`]). Rectangles, frames and whole ellipses grow by exactly the spread, + /// unless their stroke has corners (see [`Node::grows_by_exactly_its_spread`]). fn spread_miter_reach(&self) -> f64 { if self.grows_by_exactly_its_spread() { return 0.0; diff --git a/crates/render/src/spread_tests.rs b/crates/render/src/spread_tests.rs index 6b30766fc..ec41dd8dd 100644 --- a/crates/render/src/spread_tests.rs +++ b/crates/render/src/spread_tests.rs @@ -192,3 +192,58 @@ fn arc_stroke_mitres_are_not_cut_off() { assert!(worst <= 2, "{align:?}: {worst} levels cut off"); } } + +/// A dashed stroke is cut into separate dashes with square ends, a width profile can step its +/// width and a brush lays down shapes of its own: round a whole ellipse or a rounded box, a spread +/// mitres out at their corners, past the box grown by the spread, and keeps its whole shadow. +#[test] +fn stroke_corners_spread_mitres_are_not_cut_off() { + use figcraft_doc::{Brush, Node, StrokeAlign, StrokeCap, WidthProfile}; + type Style = fn(&mut Node); + let strokes: [(&str, Style); 4] = [ + ("dashed", |n| n.stroke.dashes = vec![30.0, 30.0]), + ("dashed with square caps", |n| (n.stroke.dashes, n.stroke.dash_cap) = (vec![30.0, 30.0], Some(StrokeCap::Square))), + ("stepped", |n| n.stroke.width_profile = Some(WidthProfile::new([(0.0, 1.0), (0.25, 4.0), (0.26, 0.2), (0.75, 4.0)]))), + ("starry", |n| n.stroke.brush = Some(Brush::new("stars"))), + ]; + let shapes = [(NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }, 0.0), (NodeKind::Rectangle, 100.0)]; + for (kind, radius) in shapes { + for (name, style) in strokes { + for align in [StrokeAlign::Outside, StrokeAlign::Center] { + let make = |effects: Vec| { + let (mut d, n) = shape(kind.clone(), effects); + let node = d.get_mut(n).unwrap(); + node.corners.radii = [radius; 4]; + node.strokes = vec![Paint::solid(Color::WHITE)]; + (node.stroke.weight, node.stroke.align) = (20.0, align); + style(node); + (d, n) + }; + let (d, n) = make(vec![EffectKind::DropShadow(shadow(30.0))]); + let clear = Shadow { color: Color::new(0.0, 0.0, 0.0, 0.0), ..shadow(120.0) }; + let (roomy, m) = make(vec![EffectKind::DropShadow(shadow(30.0)), EffectKind::DropShadow(clear)]); + let (a, b) = (render(&d, n), render(&roomy, m)); + let worst = a.data().chunks(4).zip(b.data().chunks(4)).map(|(p, q)| p[3].abs_diff(q[3])).max().unwrap_or(0); + // The stroke lands a little differently on a layer of another size, even when + // both have room to spare: up to 16 levels at a pixel or two. Cut off is 255. + assert!(worst <= 16, "{kind:?} radius {radius}, {name} {align:?}: {worst} levels cut off"); + } + } + } +} + +/// Without a spread, a dashed stroke reaches no further than a solid one: the bounds an export +/// goes by stay the box grown by the stroke. +#[test] +fn a_dashed_stroke_without_a_spread_keeps_its_bounds() { + use figcraft_doc::StrokeAlign; + for kind in [NodeKind::Rectangle, NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }] { + let (mut d, n) = shape(kind.clone(), vec![]); + let node = d.get_mut(n).unwrap(); + node.strokes = vec![Paint::solid(Color::WHITE)]; + (node.stroke.weight, node.stroke.align) = (20.0, StrokeAlign::Outside); + node.stroke.dashes = vec![30.0, 30.0]; + let b = crate::export_bounds(&d, n).unwrap(); + assert_eq!((b.x0, b.y0, b.x1, b.y1), (80.0, 80.0, 320.0, 320.0), "{kind:?}"); + } +} From 3c9d943ff21c3d7b8fb40b1f5cb1a85539bd7205 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 00:42:22 -0500 Subject: [PATCH 013/102] Field scrub: the field always senses drags; Alt as the drag begins makes it a scrub until the button is let go Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/field_tests.rs | 13 +++++++++++++ crates/ui-egui/src/widgets.rs | 16 +++++++++++----- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 91fbae2b2..4e3dfb35d 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -1216,4 +1216,17 @@ fn alt_held_over_a_field_scrubs_it() { drag(&mut u, at, 25.0, Modifiers::NONE); assert_eq!(geom(&u, a).0, 35.0, "without Alt the field doesn't scrub"); assert_eq!(undo_steps(&u), steps + 1); + // Alt and the press in the same frame still scrub, and Alt let go before the button still + // ends the scrub with its undo step. + let (at, _) = field(&mut u, "X"); + let press = |pressed: bool, m: Modifiers, p: Pos2| Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: m }; + u.frame_with(vec![Event::PointerMoved(at), press(true, alt, at)], alt); + for k in 1..=10 { + u.frame_with(vec![Event::PointerMoved(pos2(at.x + 2.0 * k as f32, at.y))], alt); + } + let to = pos2(at.x + 20.0, at.y); + u.frame_with(vec![Event::PointerMoved(to), press(false, Modifiers::NONE, to)], Modifiers::NONE); + u.frame(vec![]); + assert_eq!(geom(&u, a).0, 55.0, "twenty more"); + assert_eq!(undo_steps(&u), steps + 2, "committed when the button went up, without Alt"); } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 4ed92eb0d..7db22abc0 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -268,10 +268,16 @@ fn number_field_impl( let mut editing: Option = ui.data(|d| d.get_temp(editing_id)); // Alt held over the field scrubs it too, as the label always does: "hover the input field // itself and hold down the modifier key" (Adjust alignment, rotation, position, and - // dimensions). The drag sense stays on until a scrub begun that way is let go. + // dimensions). The field always senses drags (egui assigns a press by the frame before it, so + // a sense that waits for Alt would miss a press that arrives with it); Alt as the drag begins + // is what makes it a scrub, and that holds until the button is let go, Alt released or not. let field_id = id.with("field"); - let alt_scrub = editing.is_none() && (ui.input(|i| i.modifiers.alt) || ui.ctx().is_being_dragged(field_id)); - let field_resp = ui.interact(edit_rect, field_id, if alt_scrub { Sense::CLICK | Sense::DRAG } else { Sense::click() }); + let field_resp = ui.interact(edit_rect, field_id, Sense::click_and_drag()); + let alt_now = ui.input(|i| i.modifiers.alt); + let scrubbing_id = id.with("altscrub"); + let alt_scrub = + editing.is_none() && if field_resp.drag_started() { alt_now } else { ui.data(|d| d.get_temp::(scrubbing_id)).unwrap_or(false) }; + ui.data_mut(|d| d.insert_temp(scrubbing_id, alt_scrub && field_resp.dragged() && !field_resp.drag_stopped())); a11y::number(&field_resp, lead.name(), value, suffix, empty.text()); a11y::ring_around(ui, rect, &field_resp); // The label scrubs with the pointer; the keyboard stops at the value only. @@ -297,7 +303,7 @@ fn number_field_impl( } Lead::None | Lead::Named(_) => {} } - if lead_resp.hovered() || lead_resp.dragged() || (alt_scrub && (field_resp.hovered() || field_resp.dragged())) { + if lead_resp.hovered() || lead_resp.dragged() || (alt_now && editing.is_none() && field_resp.hovered()) || (alt_scrub && field_resp.dragged()) { ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); } // On the field, Alt is what makes the drag a scrub, so it is not the fine rate there. @@ -349,7 +355,7 @@ fn number_field_impl( } // Typing on a field the keyboard reached (Tab) edits it: the editor takes the typed text. let typed_now = editing.is_none() && on_field && ui.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Text(_)))); - let started = editing.is_none() && ((field_resp.clicked() && !alt_scrub) || typed_now); + let started = editing.is_none() && ((field_resp.clicked() && !alt_now) || typed_now); // The text the field would commit to no effect: what it showed when the edit began, or the // value the arrows last stepped it to. let kept_id = id.with("kept"); From abf2eb9b3a19692e0296297e6f1b7d69bc48ea6b Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 01:24:32 -0500 Subject: [PATCH 014/102] M1: the Fill section shows a text's characters' fills, mixed when they differ, and a layer fill edit reaches every character (#1856) Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/cmd/edit/props.rs | 6 ++ crates/engine/src/cmd/lists.rs | 51 +++++++++- crates/engine/src/cmd/props.rs | 3 + crates/engine/src/text_fill_tests.rs | 67 +++++++++++- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/panels/right/paints.rs | 3 +- crates/ui-egui/src/text_mixed_fill_tests.rs | 107 ++++++++++++++++++++ crates/ui-egui/src/widgets/colorpicker.rs | 3 +- docs/ui-parity.md | 4 +- 9 files changed, 240 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/text_mixed_fill_tests.rs diff --git a/crates/engine/src/cmd/edit/props.rs b/crates/engine/src/cmd/edit/props.rs index da19b1eec..b31312a01 100644 --- a/crates/engine/src/cmd/edit/props.rs +++ b/crates/engine/src/cmd/edit/props.rs @@ -267,6 +267,9 @@ pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) -> let doc = s.doc_mut()?; for i in ids { let n = doc.get_mut(i)?; + if fills { + crate::cmd::lists::take_character_fills(n); + } let frameish = n.kind.is_frame_like(); let list = if fills { &mut n.fills } else { &mut n.strokes }; if add { @@ -298,6 +301,9 @@ pub(super) fn paint_set(s: &mut Session, p: &Value, fills: bool) -> Result Option> { + let NodeKind::Text(t) = &n.kind else { return Some(n.fills.clone()) }; + let mut spans = t.spans().into_iter().map(|(_, _, st)| st.fills.as_ref().unwrap_or(&n.fills)); + let first = spans.next().unwrap_or(&n.fills).clone(); + spans.all(|f| *f == first).then_some(first) +} + +/// Before a layer-level edit of a text's fills (the Fill section, `fill.*`, `node.set`): the +/// characters' own fills go, so the edit shows on every one of them. One list they all shared +/// becomes the layer's first, so the edit starts from what the characters showed; characters +/// that differed fall back to the layer's fills, which the edit then replaces ("Click + to +/// replace mixed content"). Not a text, or no character with fills of its own: nothing changes. +pub(crate) fn take_character_fills(n: &mut Node) { + let NodeKind::Text(t) = &n.kind else { return }; + if t.style.fills.is_none() && t.runs.iter().all(|r| r.style.fills.is_none()) { + return; + } + if let Some(shared) = character_fills(n) + && shared != n.fills + { + let old = std::mem::replace(&mut n.fills, shared); + for (i, p) in old.iter().enumerate() { + rebind_edited_paint(n, true, i, p); + } + } + if let NodeKind::Text(t) = &mut n.kind { + t.style.fills = None; + for r in &mut t.runs { + r.style.fills = None; + } + t.normalize(); + } +} + /// Where item `k` lands when the item at `from` moves to `to`. pub fn moved_index(k: usize, from: usize, to: usize) -> usize { if k == from { @@ -250,11 +289,19 @@ fn move_item(s: &mut Session, p: &Value, cmd: &str, list: BoundList) -> Result= len || to >= len || from == to { continue; } let n = s.doc_mut()?.get_mut(id)?; + if list == BoundList::Fills { + take_character_fills(n); + } let moved = match list { BoundList::Fills => reorder(&mut n.fills, from, to), BoundList::Strokes => reorder(&mut n.strokes, from, to), diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index fbf80fc1b..670ee73ab 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -376,6 +376,9 @@ fn layout_mut<'a>(cmd: &str, k: &str, n: &'a mut Node) -> Result<&'a mut AutoLay /// Replace a node's fills (or strokes). Bindings on the paints whose bound values the new list /// changed let go, as an explicit edit does (see `lists::rebind_edited_paint`). fn set_paints(n: &mut Node, fills: bool, paints: Vec) { + if fills { + super::lists::take_character_fills(n); + } let old = std::mem::replace(if fills { &mut n.fills } else { &mut n.strokes }, paints); for (i, p) in old.iter().enumerate() { super::lists::rebind_edited_paint(n, fills, i, p); diff --git a/crates/engine/src/text_fill_tests.rs b/crates/engine/src/text_fill_tests.rs index 8501a6ce5..6ef49b9e3 100644 --- a/crates/engine/src/text_fill_tests.rs +++ b/crates/engine/src/text_fill_tests.rs @@ -1,10 +1,75 @@ -//! Range fills on text: set on a range, cleared back to the layer's fill. +//! Range fills on text: set on a range, cleared back to the layer's fill; a layer-level fill edit +//! reaches every character. use serde_json::json; use crate::Session; +use crate::cmd::lists::character_fills; use crate::params::id_of; +/// The fill each character of `t` shows, as hex. +fn fills_shown(s: &Session, t: figcraft_doc::NodeId) -> Vec { + let n = s.doc().unwrap().node(t).unwrap().clone(); + let tx = n.kind.text().unwrap().clone(); + (0..tx.char_count()) + .map(|i| { + tx.style_at(i) + .fills + .clone() + .unwrap_or_else(|| n.fills.clone()) + .iter() + .map(|p| p.solid_color().unwrap().to_hex()) + .collect::>() + .join("+") + }) + .collect() +} + +/// A text styled on a range, or on all of its characters, keeps those fills until the layer's +/// fill is edited: then every character takes the layer's fills, in one undo step (#1856). +#[test] +fn a_layer_fill_edit_reaches_every_character() { + let mut s = Session::new(); + let t = id_of(&s.execute("text.create", &json!({"text": "Hello", "x": 0, "y": 0})).unwrap()["id"]).unwrap(); + s.execute("fill.set", &json!({"ids": [t], "color": "#FF0000"})).unwrap(); + let node = |s: &Session| s.doc().unwrap().node(t).unwrap().clone(); + assert_eq!(character_fills(&node(&s)).map(|f| f.len()), Some(1), "one shared list"); + // "ello" yellow: the characters differ, the layer's fill is mixed, the canvas keeps both. + s.execute("text.style", &json!({"id": t, "start": 1, "end": 5, "textFills": ["#FFFF00"]})).unwrap(); + assert_eq!(fills_shown(&s, t), ["FF0000", "FFFF00", "FFFF00", "FFFF00", "FFFF00"]); + assert_eq!(character_fills(&node(&s)), None, "mixed"); + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + assert_eq!(fills_shown(&s, t), ["FF0000", "FFFF00", "FFFF00", "FFFF00", "FFFF00"], "reselecting changes nothing"); + // The layer's fill set: every character takes it, their own fills are gone. + let steps = s.ds().unwrap().history.undo.len(); + s.execute("fill.set", &json!({"ids": [t], "color": "#0000FF"})).unwrap(); + assert_eq!(fills_shown(&s, t), ["0000FF"; 5]); + assert!(node(&s).kind.text().unwrap().runs.is_empty(), "no character keeps fills of its own"); + assert_eq!(s.ds().unwrap().history.undo.len(), steps + 1, "one undo step"); + s.undo().unwrap(); + assert_eq!(fills_shown(&s, t), ["FF0000", "FFFF00", "FFFF00", "FFFF00", "FFFF00"], "undo puts the characters' fills back"); + s.redo().unwrap(); + // All of the characters styled while editing: they share a list the layer doesn't have yet. + // A fill added at the layer goes on top of that list, not the layer's old one. + s.execute("text.style", &json!({"id": t, "start": 0, "end": 5, "textFills": ["#00FF00"]})).unwrap(); + assert_eq!(fills_shown(&s, t), ["00FF00"; 5]); + assert_eq!(character_fills(&node(&s)).map(|f| f.len()), Some(1), "one shared list, the characters'"); + assert_eq!(node(&s).fills[0].solid_color().unwrap().to_hex(), "0000FF", "the layer's own list is older"); + s.execute("fill.add", &json!({"ids": [t], "color": "#FF00FF"})).unwrap(); + assert_eq!(fills_shown(&s, t), ["00FF00+FF00FF"; 5]); + assert!(node(&s).kind.text().unwrap().runs.is_empty()); + assert_eq!(node(&s).fills.len(), 2, "the layer's list is the characters' now"); + // `node.set` with a fill, and a mixed text again: both reach every character. + s.execute("text.style", &json!({"id": t, "start": 1, "end": 5, "textFills": ["#FFFF00"]})).unwrap(); + s.execute("node.set", &json!({"id": t, "props": {"fill": "#123456"}})).unwrap(); + assert_eq!(fills_shown(&s, t), ["123456"; 5]); + // A rectangle is left alone by all of this. + let r = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"]).unwrap(); + s.execute("fill.set", &json!({"ids": [r], "color": "#ABCDEF"})).unwrap(); + assert_eq!(character_fills(s.doc().unwrap().node(r).unwrap()).map(|f| f.len()), Some(1)); +} + #[test] fn range_fill_sets_and_clears() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7ecb64d22..4186ba7c5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -243,6 +243,8 @@ mod table_paste_tests; #[cfg(test)] mod text_enter_tests; #[cfg(test)] +mod text_mixed_fill_tests; +#[cfg(test)] mod titlebar_tests; #[cfg(test)] mod ui_params_tests; diff --git a/crates/ui-egui/src/panels/right/paints.rs b/crates/ui-egui/src/panels/right/paints.rs index 58423d252..06e23eaf7 100644 --- a/crates/ui-egui/src/panels/right/paints.rs +++ b/crates/ui-egui/src/panels/right/paints.rs @@ -293,7 +293,8 @@ pub(super) fn paints(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeI } let t = Tokens::get(ui.ctx()); let ids = sel.to_vec(); - let list = common(doc, sel, |n| if fills { n.fills.clone() } else { n.strokes.clone() }); + // A text's fills are what its characters show: one list they share, or mixed (#1856). + let list = common(doc, sel, |n| if fills { figcraft_engine::cmd::lists::character_fills(n) } else { Some(n.strokes.clone()) }).flatten(); let title = if fills { tr("Fill") } else { tr("Stroke") }; let empty = list.as_ref().is_none_or(|l| l.is_empty()); let slot = if fills { StyleSlot::Fill } else { StyleSlot::Stroke }; diff --git a/crates/ui-egui/src/text_mixed_fill_tests.rs b/crates/ui-egui/src/text_mixed_fill_tests.rs new file mode 100644 index 000000000..b494c267d --- /dev/null +++ b/crates/ui-egui/src/text_mixed_fill_tests.rs @@ -0,0 +1,107 @@ +//! The Fill section on a text whose characters were coloured while editing (#1856), driven +//! through egui headless: characters with different fills show as mixed content and + replaces +//! them on every character; characters that all share fills the layer doesn't have show those. + +use egui::accesskit::Role; +use egui::{Pos2, pos2}; +use figcraft_doc::NodeId; +use figcraft_engine::Session; +use serde_json::json; + +use crate::layers_drag_tests::Ui; + +const NOTE: &str = "Click + to replace mixed content"; + +/// A red "Hello" with its characters from `from` on coloured yellow while editing, selected. +fn ui(from: usize) -> (Ui, NodeId) { + let mut s = Session::new(); + let t = NodeId(s.execute("text.create", &json!({"text": "Hello", "x": 0, "y": 0})).unwrap()["id"].as_u64().unwrap()); + s.execute("fill.set", &json!({"ids": [t], "color": "#FF0000"})).unwrap(); + s.execute("text.style", &json!({"id": t, "start": from, "end": 5, "textFills": ["#FFFF00"]})).unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + let mut u = Ui::new(s); + u.ctx.enable_accesskit(); + u.frame(vec![]); + (u, t) +} + +/// The accessible controls after a frame: role, label, value and centre. +fn controls(u: &mut Ui) -> Vec<(Role, String, String, Pos2)> { + u.frame(vec![]); + let out = u.frame_output(vec![]); + let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes; + nodes + .iter() + .map(|(_, n)| { + let at = n.bounds().map_or(pos2(0.0, 0.0), |b| pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)); + (n.role(), n.label().unwrap_or_default().to_string(), n.value().unwrap_or_default().to_string(), at) + }) + .collect() +} + +/// What the Fill section shows: its hex rows top first, whether the mixed-content note is there +/// (only a paint section shows it, and the strokes here are never mixed), and its + button. The +/// section's rows lie between its + and the Stroke section's; Selection colors is further down. +fn fill_section(c: &[(Role, String, String, Pos2)]) -> (Vec, bool, Pos2) { + let button = |name: &str| { + c.iter().find(|(r, l, _, _)| *r == Role::Button && l == name).map(|(_, _, _, p)| *p).unwrap_or_else(|| panic!("no {name} button: {c:?}")) + }; + let (top, bottom) = (button("Add fill"), button("Add stroke")); + let mut rows: Vec<(f32, String)> = + c.iter().filter(|(r, _, _, p)| *r == Role::TextInput && p.y > top.y && p.y < bottom.y).map(|(_, _, v, p)| (p.y, v.clone())).collect(); + rows.sort_by(|a, b| a.0.total_cmp(&b.0)); + let note = c.iter().any(|(_, l, v, _)| l == NOTE || v == NOTE); + (rows.into_iter().map(|(_, v)| v).collect(), note, top) +} + +fn fills_shown(u: &Ui, t: NodeId) -> Vec { + let n = u.app.session.doc().unwrap().node(t).unwrap().clone(); + let tx = n.kind.text().unwrap().clone(); + (0..tx.char_count()) + .map(|i| { + tx.style_at(i) + .fills + .clone() + .unwrap_or_else(|| n.fills.clone()) + .iter() + .map(|p| p.solid_color().unwrap().to_hex()) + .collect::>() + .join("+") + }) + .collect() +} + +#[test] +fn differently_coloured_characters_show_as_mixed_content_and_plus_replaces_them() { + let (mut u, t) = ui(1); + let c = controls(&mut u); + let (rows, note, plus) = fill_section(&c); + assert!(note, "the Fill section shows the note: {c:?}"); + assert!(rows.is_empty(), "no row for the layer's own red: {rows:?}"); + // + adds a fill on top of the layer's: every character shows the layer's fills now. + let steps = u.app.session.ds().unwrap().history.undo.len(); + u.button(plus, true); + u.button(plus, false); + u.frame(vec![]); + let n = u.app.session.doc().unwrap().node(t).unwrap().clone(); + assert_eq!(n.fills.len(), 2, "the new fill on the layer's: {:?}", n.fills); + assert!(n.kind.text().unwrap().runs.is_empty(), "no character keeps fills of its own"); + assert!(fills_shown(&u, t).iter().all(|f| f == "FF0000+D9D9D9"), "{:?}", fills_shown(&u, t)); + assert_eq!(u.app.session.ds().unwrap().history.undo.len(), steps + 1, "one undo step"); + let c = controls(&mut u); + let (rows, note, _) = fill_section(&c); + assert!(!note, "no note once the characters agree: {c:?}"); + assert_eq!(rows, ["D9D9D9", "FF0000"], "the new fill above the layer's red: {c:?}"); +} + +#[test] +fn characters_sharing_fills_the_layer_lacks_show_theirs() { + let (mut u, t) = ui(0); + let n = u.app.session.doc().unwrap().node(t).unwrap().clone(); + assert_eq!(n.fills[0].solid_color().unwrap().to_hex(), "FF0000", "the layer still has its old fill"); + assert_eq!(fills_shown(&u, t), ["FFFF00"; 5]); + let c = controls(&mut u); + let (rows, note, _) = fill_section(&c); + assert_eq!(rows, ["FFFF00"], "the characters' yellow is the row, not the layer's red: {c:?}"); + assert!(!note, "{c:?}"); +} diff --git a/crates/ui-egui/src/widgets/colorpicker.rs b/crates/ui-egui/src/widgets/colorpicker.rs index 5fbcc7b40..3bd322031 100644 --- a/crates/ui-egui/src/widgets/colorpicker.rs +++ b/crates/ui-egui/src/widgets/colorpicker.rs @@ -92,7 +92,8 @@ fn current_paint(app: &FigApp, target: &PickerTarget) -> Option { }, PickerTarget::Paint { fills, index, ids } => { let n = doc.node(*ids.first()?)?; - let list = if *fills { &n.fills } else { &n.strokes }; + // A text's fills are its characters' (none to pick while they differ). + let list = if *fills { figcraft_engine::cmd::lists::character_fills(n)? } else { n.strokes.clone() }; list.get(*index).cloned() } PickerTarget::Effect { ids, index, secondary } => doc.node(*ids.first()?)?.effects.get(*index)?.color(*secondary).map(Paint::solid), diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3963e4624..0f1b5f3f2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** patch (the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -33,6 +33,7 @@ interaction feel not yet compared. | Colour picker placement and dismissal | done | Opens 8 pt beside the sidebar at the opening control, lifted to fit the screen; outside presses (including the sidebar), Escape and X close it. Reopening resets a dragged position; eyedropper sampling keeps it open. | | Colour picker image well | partial | the Image tab shows a checkered placeholder and Upload from computer until there is a file (no dialog at once); an image paint shows its asset preview; a file dropped on the open picker replaces the image, keeping the fill mode, crop, position and adjustments (`image.replace`). Layers' fills and strokes only (text ranges, styles and selection colours keep Upload). The Fill and Stroke swatches take no drop: a dragged file's position isn't known, so a drop with none goes to the open picker | | Colour picker on a new fill or stroke | done | + opens the picker on the new paint when the selection shares one paint list; on a mixed selection + adds a paint to each layer and no picker opens (#404) | +| Fill section on a text with coloured characters | done | a text's Fill section shows what its characters show: characters coloured differently while editing are mixed content ("Click + to replace mixed content", as a mixed selection; the developer documentation's `fills`: "Text nodes can have multiple sets of fills if some characters are colored differently than others"), and characters that all share fills the layer doesn't have show those. Any layer-level fill edit (a row, its picker, +, reordering, `fill.*`, `node.set`) reaches every character, starting from the list they showed; the characters' own fills go in the same undo step (`text_mixed_fill_tests`, engine `text_fill_tests`; #1856). A range selected while editing keeps its own Fill row | | Blend mode menus: the layer's (Design panel) and each paint's (colour picker) | done | Pass through and Normal are distinct (Normal isolates a group's or frame's children); paints have no pass-through; plus darker drawn exactly on the canvas | ## Layers and Assets panels @@ -176,6 +177,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-02 | patch | Fill section: a text whose characters were coloured differently while editing shows mixed content, as a mixed selection does ("Text nodes can have multiple sets of fills if some characters are colored differently than others", the developer documentation's `fills`); characters that all share fills the layer doesn't have (all of them styled while editing) show those instead of the layer's older list; and a layer-level fill edit (a row, its picker, +, reordering, `fill.*`, `node.set`) reaches every character, their own fills going in the same undo step. The section used to show the layer's own fill, a single colour the canvas no longer showed (#1856). Tests: `text_mixed_fill_tests`, engine `text_fill_tests`. Numbers unchanged | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Shift+Alt+= and - make the interface larger and smaller through the sizes Preferences offers, and Cmd/Ctrl+Shift+Alt+0 puts it back to the system's size ("Adjust the scale of the Figma UI [...] Reset to Default: Control ⇧Shift Alt 0; Make Larger: Control ⇧Shift Alt =; Make Smaller: Control ⇧Shift Alt -", Accessibility at Figma); the size is kept at once, as one picked in Preferences is. `pref.uiScaleUp`, `pref.uiScaleDown`, `pref.uiScaleReset`; the sizes list now lives in the engine (`UI_SCALE_SIZES`) and Preferences reads it from there. Found by a documentation audit of the shortcuts. Test: `keymap_tests::the_interface_size_keys_step_through_the_preferences_sizes`. Documented rows 130 → 133, bound 129 → 132 | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Alt+↑/↓ (and ←/→) rotate the selection one degree at a time, 15 with Shift ("Press ⌘Command ⌥Option ↑/ ↓ on Mac or Control Alt ↑/↓ on Windows to rotate an object one degree at a time", Accessibility at Figma); they resized by the nudge before, which Cmd/Ctrl+arrows without Alt still do. Down and right turn clockwise, up and left back (the documentation is silent on the direction). In the shortcuts panel's Transform tab, over the control channel's `ui.key` too. Found by a documentation audit of the shortcuts. Test: `shortcut_keys_tests::cmd_alt_arrows_rotate_a_degree_and_fifteen_with_shift`. Documented rows 129 → 130, bound 128 → 129 | | 2026-11-01 | patch | Shortcuts: the Layers panel opens with Ctrl+1 as well as Alt+1 on Windows and Linux ("Mac: Option 1 Windows: Ctrl 1" in Select layers and objects; "Windows: Alt 1" in Explore the navigation bar and left sidebar). macOS keeps Option+1. Found by a documentation audit of the shortcuts (every chord driven over the control channel). Tests: `keymap_tests::the_layers_panel_answers_both_of_its_documented_windows_keys`, the parity row. Counts unchanged | From 9783af934712ed03a9d4ccfcc8df8ac17a32dd7b Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 01:27:48 -0500 Subject: [PATCH 015/102] Field scrub: the field senses drags only with Alt held or a scrub going on, so a touch swipe stays the scroll area's Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/field_tests.rs | 26 +++++++++++++++++++++++--- crates/ui-egui/src/widgets.rs | 14 ++++++++------ 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 4e3dfb35d..e9aabcacb 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -1216,11 +1216,11 @@ fn alt_held_over_a_field_scrubs_it() { drag(&mut u, at, 25.0, Modifiers::NONE); assert_eq!(geom(&u, a).0, 35.0, "without Alt the field doesn't scrub"); assert_eq!(undo_steps(&u), steps + 1); - // Alt and the press in the same frame still scrub, and Alt let go before the button still - // ends the scrub with its undo step. + // Alt let go before the button still ends the scrub with its undo step. let (at, _) = field(&mut u, "X"); let press = |pressed: bool, m: Modifiers, p: Pos2| Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: m }; - u.frame_with(vec![Event::PointerMoved(at), press(true, alt, at)], alt); + u.frame_with(vec![Event::PointerMoved(at)], alt); + u.frame_with(vec![press(true, alt, at)], alt); for k in 1..=10 { u.frame_with(vec![Event::PointerMoved(pos2(at.x + 2.0 * k as f32, at.y))], alt); } @@ -1229,4 +1229,24 @@ fn alt_held_over_a_field_scrubs_it() { u.frame(vec![]); assert_eq!(geom(&u, a).0, 55.0, "twenty more"); assert_eq!(undo_steps(&u), steps + 2, "committed when the button went up, without Alt"); + // Without Alt the field doesn't take the drag at all (a touch swipe over it is the panel's to + // scroll): the press is a click of the field's, not a drag. + let (at, _) = field(&mut u, "X"); + let field_id = Id::unique("pos_x").with("field"); + u.frame_with(vec![Event::PointerMoved(at)], Modifiers::NONE); + u.frame_with(vec![press(true, Modifiers::NONE, at)], Modifiers::NONE); + u.frame_with(vec![Event::PointerMoved(pos2(at.x + 10.0, at.y))], Modifiers::NONE); + assert!(!u.ctx.is_being_dragged(field_id), "a plain press on the field isn't a drag of the field's"); + u.frame_with(vec![Event::PointerMoved(pos2(at.x + 10.0, at.y)), press(false, Modifiers::NONE, pos2(at.x + 10.0, at.y))], Modifiers::NONE); + u.frame(vec![]); + assert_eq!(geom(&u, a).0, 55.0, "nothing scrubbed"); + // With Alt held over it, the field does take the drag. + let (at, _) = field(&mut u, "X"); + u.frame_with(vec![Event::PointerMoved(at)], alt); + u.frame_with(vec![press(true, alt, at)], alt); + u.frame_with(vec![Event::PointerMoved(pos2(at.x + 10.0, at.y))], alt); + assert!(u.ctx.is_being_dragged(field_id), "with Alt the drag is the field's"); + u.frame_with(vec![Event::PointerMoved(pos2(at.x + 10.0, at.y)), press(false, alt, pos2(at.x + 10.0, at.y))], alt); + u.frame(vec![]); + assert_eq!(geom(&u, a).0, 65.0, "ten more"); } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 7db22abc0..58733ce79 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -268,15 +268,17 @@ fn number_field_impl( let mut editing: Option = ui.data(|d| d.get_temp(editing_id)); // Alt held over the field scrubs it too, as the label always does: "hover the input field // itself and hold down the modifier key" (Adjust alignment, rotation, position, and - // dimensions). The field always senses drags (egui assigns a press by the frame before it, so - // a sense that waits for Alt would miss a press that arrives with it); Alt as the drag begins - // is what makes it a scrub, and that holds until the button is let go, Alt released or not. + // dimensions). The field senses drags only while Alt is held, or while a scrub begun that way + // goes on (Alt released or not), so a plain press or a touch swipe on it stays the scroll + // area's; egui assigns a press by the frame before it, so Alt is held over the field before + // the press, as a hand does. Alt as the drag begins is what makes it a scrub. let field_id = id.with("field"); - let field_resp = ui.interact(edit_rect, field_id, Sense::click_and_drag()); let alt_now = ui.input(|i| i.modifiers.alt); let scrubbing_id = id.with("altscrub"); - let alt_scrub = - editing.is_none() && if field_resp.drag_started() { alt_now } else { ui.data(|d| d.get_temp::(scrubbing_id)).unwrap_or(false) }; + let scrubbing = ui.data(|d| d.get_temp::(scrubbing_id)).unwrap_or(false); + let field_sense = if editing.is_none() && (alt_now || scrubbing) { Sense::click_and_drag() } else { Sense::click() }; + let field_resp = ui.interact(edit_rect, field_id, field_sense); + let alt_scrub = editing.is_none() && if field_resp.drag_started() { alt_now } else { scrubbing }; ui.data_mut(|d| d.insert_temp(scrubbing_id, alt_scrub && field_resp.dragged() && !field_resp.drag_stopped())); a11y::number(&field_resp, lead.name(), value, suffix, empty.text()); a11y::ring_around(ui, rect, &field_resp); From 8fb53baa64c73aa3721e636e944a1e9b5db67da9 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 02:02:35 -0500 Subject: [PATCH 016/102] SVG import: a filled and stroked path with an open subpath is tested through its split Co-Authored-By: Claude Fable 5.1 --- crates/svg/src/import/structure_tests.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/svg/src/import/structure_tests.rs b/crates/svg/src/import/structure_tests.rs index a44590470..fbc9976ae 100644 --- a/crates/svg/src/import/structure_tests.rs +++ b/crates/svg/src/import/structure_tests.rs @@ -159,6 +159,27 @@ fn an_open_path_starts_half_a_dash_in_and_takes_other_offsets() { assert_eq!(node(&d, f, "mixed").stroke.dashes, vec![4.0, 2.0], "an open subpath makes the outline open"); } +/// A filled and stroked path with an open subpath becomes a fill layer and a stroke layer: the +/// stroke layer is open, so it starts half a dash in like any open path and that offset is left +/// out; a filled and stroked path that closes stays one layer whose offset is applied. +#[test] +fn a_filled_and_stroked_open_path_splits_and_its_stroke_layer_is_open() { + let (d, f) = import( + r##""##, + ); + for id in ["both", "bothmixed"] { + let stroke_layer = node(&d, f, id); + assert!(stroke_layer.fills.is_empty() && !stroke_layer.strokes.is_empty(), "{id}: the stroke layer carries the stroke alone"); + assert_eq!(stroke_layer.stroke.dashes, vec![4.0, 2.0], "{id}: an open stroke layer starts half a dash in by itself"); + let fill_layer = node(&d, f, &format!("{id} fill")); + assert!(!fill_layer.fills.is_empty() && fill_layer.strokes.is_empty(), "{id}: the fill layer carries the fill alone"); + } + let one = node(&d, f, "bothclosed"); + assert!(!one.fills.is_empty() && !one.strokes.is_empty(), "a closed path keeps fill and stroke on one layer"); + assert_eq!(one.stroke.dashes, vec![2.0, 2.0, 2.0, 0.0], "and its offset rotates the pattern"); + assert!(d.subtree(f).into_iter().filter_map(|i| d.node(i)).all(|n| n.name != "bothclosed fill"), "no split for a closed path"); +} + /// A text stroke runs along glyph contours, which close, so its offset is applied as on a shape. #[test] fn a_text_stroke_keeps_a_dash_offset_of_half_a_dash() { From badbe64440f3c033d7929e63eabf54f7a0e3d51d Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 03:23:36 -0500 Subject: [PATCH 017/102] Fill section: a removal that names no paint leaves the characters' fills, and Copy fill and Crop image use the list the rows show Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/cmd/edit/props.rs | 10 +++++++++- crates/engine/src/cmd/image.rs | 4 ++++ crates/engine/src/cmd/lists.rs | 11 +++++++++-- crates/engine/src/text_fill_tests.rs | 9 +++++++++ 4 files changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/edit/props.rs b/crates/engine/src/cmd/edit/props.rs index b31312a01..9b6921d3f 100644 --- a/crates/engine/src/cmd/edit/props.rs +++ b/crates/engine/src/cmd/edit/props.rs @@ -267,6 +267,13 @@ pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) -> let doc = s.doc_mut()?; for i in ids { let n = doc.get_mut(i)?; + // A removal that names no paint changes nothing, the characters' own fills included. + if !add { + let shown = if fills { crate::cmd::lists::character_fills(n).map_or(n.fills.len(), |f| f.len()) } else { n.strokes.len() }; + if index.unwrap_or(shown.saturating_sub(1)) >= shown { + continue; + } + } if fills { crate::cmd::lists::take_character_fills(n); } @@ -350,7 +357,8 @@ pub(super) fn paint_copy(s: &mut Session, p: &Value, fills: bool) -> Result Result { // A selection with nothing to crop is refused as unavailable, not as bad input. let refuse = |why: &str| EngineError::Disabled(cmd.into(), why.into()); let [id] = ids[..] else { return Err(refuse("select one layer to crop its image")) }; + // A text's fills are its characters' (the Design panel's rows): the crop edits that list. + if crate::cmd::lists::has_character_fills(s.doc()?.get(id)?) { + crate::cmd::lists::take_character_fills(s.doc_mut()?.get_mut(id)?); + } let doc = s.doc()?; let n = doc.get(id)?; let index = match get(p, "index") { diff --git a/crates/engine/src/cmd/lists.rs b/crates/engine/src/cmd/lists.rs index 8f4cb37b3..455a02567 100644 --- a/crates/engine/src/cmd/lists.rs +++ b/crates/engine/src/cmd/lists.rs @@ -201,14 +201,21 @@ pub fn character_fills(n: &Node) -> Option> { spans.all(|f| *f == first).then_some(first) } +/// Whether any character of a text carries fills of its own (on its base style or a run). +pub(crate) fn has_character_fills(n: &Node) -> bool { + match &n.kind { + NodeKind::Text(t) => t.style.fills.is_some() || t.runs.iter().any(|r| r.style.fills.is_some()), + _ => false, + } +} + /// Before a layer-level edit of a text's fills (the Fill section, `fill.*`, `node.set`): the /// characters' own fills go, so the edit shows on every one of them. One list they all shared /// becomes the layer's first, so the edit starts from what the characters showed; characters /// that differed fall back to the layer's fills, which the edit then replaces ("Click + to /// replace mixed content"). Not a text, or no character with fills of its own: nothing changes. pub(crate) fn take_character_fills(n: &mut Node) { - let NodeKind::Text(t) = &n.kind else { return }; - if t.style.fills.is_none() && t.runs.iter().all(|r| r.style.fills.is_none()) { + if !has_character_fills(n) { return; } if let Some(shared) = character_fills(n) diff --git a/crates/engine/src/text_fill_tests.rs b/crates/engine/src/text_fill_tests.rs index 6ef49b9e3..3e77b47d8 100644 --- a/crates/engine/src/text_fill_tests.rs +++ b/crates/engine/src/text_fill_tests.rs @@ -64,6 +64,15 @@ fn a_layer_fill_edit_reaches_every_character() { s.execute("text.style", &json!({"id": t, "start": 1, "end": 5, "textFills": ["#FFFF00"]})).unwrap(); s.execute("node.set", &json!({"id": t, "props": {"fill": "#123456"}})).unwrap(); assert_eq!(fills_shown(&s, t), ["123456"; 5]); + // A removal that names no paint leaves the characters' own fills alone; a copy takes the fill + // the characters show, the list the Design panel's rows are. + s.execute("text.style", &json!({"id": t, "start": 1, "end": 5, "textFills": ["#FFFF00"]})).unwrap(); + s.execute("fill.remove", &json!({"ids": [t], "index": 7})).unwrap(); + assert_eq!(fills_shown(&s, t), ["123456", "FFFF00", "FFFF00", "FFFF00", "FFFF00"], "nothing removed, nothing taken"); + s.execute("text.style", &json!({"id": t, "start": 0, "end": 5, "textFills": ["#00FF00"]})).unwrap(); + s.execute("fill.copy", &json!({"id": t})).unwrap(); + let copied = s.clipboard.paint.clone().and_then(|(_, p)| p.solid_color()).map(|c| c.to_hex()); + assert_eq!(copied.as_deref(), Some("00FF00"), "the characters' fill is copied, not the layer's older one"); // A rectangle is left alone by all of this. let r = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"]).unwrap(); s.execute("fill.set", &json!({"ids": [r], "color": "#ABCDEF"})).unwrap(); From 96cd54b5568ccbd45f572f8dceaafe416424f162 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 04:09:51 -0500 Subject: [PATCH 018/102] Fill section: mixed text has no fill rows to remove or crop, and a crop lifts the characters' fills only when it edits Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/cmd/edit/props.rs | 6 ++++-- crates/engine/src/cmd/image.rs | 17 ++++++++++------- crates/engine/src/text_fill_tests.rs | 10 ++++++++++ 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/edit/props.rs b/crates/engine/src/cmd/edit/props.rs index 9b6921d3f..2ec716818 100644 --- a/crates/engine/src/cmd/edit/props.rs +++ b/crates/engine/src/cmd/edit/props.rs @@ -267,9 +267,11 @@ pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) -> let doc = s.doc_mut()?; for i in ids { let n = doc.get_mut(i)?; - // A removal that names no paint changes nothing, the characters' own fills included. + // A removal that names no paint among the rows shown changes nothing, the characters' own + // fills included; characters coloured differently show no rows at all ("Click + to + // replace mixed content"). if !add { - let shown = if fills { crate::cmd::lists::character_fills(n).map_or(n.fills.len(), |f| f.len()) } else { n.strokes.len() }; + let shown = if fills { crate::cmd::lists::character_fills(n).map_or(0, |f| f.len()) } else { n.strokes.len() }; if index.unwrap_or(shown.saturating_sub(1)) >= shown { continue; } diff --git a/crates/engine/src/cmd/image.rs b/crates/engine/src/cmd/image.rs index 9f6b942a4..865e4d19a 100644 --- a/crates/engine/src/cmd/image.rs +++ b/crates/engine/src/cmd/image.rs @@ -184,9 +184,10 @@ fn replace(s: &mut Session, p: &Value) -> Result { Ok(json!({"image": image, "width": width, "height": height, "changed": changed})) } -/// The index of a layer's top visible image fill (fills paint bottom to top). +/// The index of a layer's top visible image fill among the fills it shows (fills paint bottom to +/// top): a text's characters' shared list, so none while they are coloured differently. pub fn top_image_fill(n: &Node) -> Option { - n.fills.iter().rposition(|f| f.visible && matches!(f.kind, PaintKind::Image(_))) + crate::cmd::lists::character_fills(n)?.iter().rposition(|f| f.visible && matches!(f.kind, PaintKind::Image(_))) } fn crop(s: &mut Session, p: &Value) -> Result { @@ -195,17 +196,17 @@ fn crop(s: &mut Session, p: &Value) -> Result { // A selection with nothing to crop is refused as unavailable, not as bad input. let refuse = |why: &str| EngineError::Disabled(cmd.into(), why.into()); let [id] = ids[..] else { return Err(refuse("select one layer to crop its image")) }; - // A text's fills are its characters' (the Design panel's rows): the crop edits that list. - if crate::cmd::lists::has_character_fills(s.doc()?.get(id)?) { - crate::cmd::lists::take_character_fills(s.doc_mut()?.get_mut(id)?); - } let doc = s.doc()?; let n = doc.get(id)?; + // A text's fills are its characters' (the Design panel's rows): the crop edits that list, and + // characters coloured differently have no row to crop ("Click + to replace mixed content"). + let shown = + crate::cmd::lists::character_fills(n).ok_or_else(|| refuse("the characters have different fills, so there is no one fill to crop"))?; let index = match get(p, "index") { None | Some(Value::Null) => top_image_fill(n).ok_or_else(|| refuse("the layer has no image fill to crop"))?, Some(_) => req_index(cmd, p, "index")?, }; - let mut paint = n.fills.get(index).cloned().ok_or_else(|| bad(cmd, "no fill at that index"))?; + let mut paint = shown.get(index).cloned().ok_or_else(|| bad(cmd, "no fill at that index"))?; let PaintKind::Image(img) = &mut paint.kind else { return Err(bad(cmd, "that fill is not an image")) }; // An image already in Crop mode only enters crop mode: no edit, no undo step. if img.scale_mode != ImageScaleMode::Crop { @@ -213,6 +214,8 @@ fn crop(s: &mut Session, p: &Value) -> Result { img.crop = Some(img.placement_crop(f64::from(data.width), f64::from(data.height), n.width, n.height)); img.scale_mode = ImageScaleMode::Crop; let n = s.doc_mut()?.get_mut(id)?; + // The characters' shared list becomes the layer's, so the crop shows on every one of them. + crate::cmd::lists::take_character_fills(n); if let Some(f) = n.fills.get_mut(index) { *f = paint; } diff --git a/crates/engine/src/text_fill_tests.rs b/crates/engine/src/text_fill_tests.rs index 3e77b47d8..348fcc9e7 100644 --- a/crates/engine/src/text_fill_tests.rs +++ b/crates/engine/src/text_fill_tests.rs @@ -69,6 +69,16 @@ fn a_layer_fill_edit_reaches_every_character() { s.execute("text.style", &json!({"id": t, "start": 1, "end": 5, "textFills": ["#FFFF00"]})).unwrap(); s.execute("fill.remove", &json!({"ids": [t], "index": 7})).unwrap(); assert_eq!(fills_shown(&s, t), ["123456", "FFFF00", "FFFF00", "FFFF00", "FFFF00"], "nothing removed, nothing taken"); + // Characters coloured differently show no fill rows at all: a removal with or without an + // index leaves the layer's hidden fill and the characters' own alone, and there is no row to + // crop (the command is unavailable, as the menu has it). + s.execute("fill.remove", &json!({"ids": [t], "index": 0})).unwrap(); + s.execute("fill.remove", &json!({"ids": [t]})).unwrap(); + assert_eq!(fills_shown(&s, t), ["123456", "FFFF00", "FFFF00", "FFFF00", "FFFF00"], "mixed: nothing to remove"); + assert_eq!(node(&s).fills.len(), 1, "the layer's own fill stays"); + assert!(matches!(s.execute("image.crop", &json!({"ids": [t]})), Err(crate::EngineError::Disabled(..))), "mixed: nothing to crop"); + assert_eq!(fills_shown(&s, t), ["123456", "FFFF00", "FFFF00", "FFFF00", "FFFF00"], "and nothing taken"); + assert_eq!(crate::cmd::image::top_image_fill(&node(&s)), None, "the menu finds no image to crop either"); s.execute("text.style", &json!({"id": t, "start": 0, "end": 5, "textFills": ["#00FF00"]})).unwrap(); s.execute("fill.copy", &json!({"id": t})).unwrap(); let copied = s.clipboard.paint.clone().and_then(|(_, p)| p.solid_color()).map(|c| c.to_hex()); From 367f188b348f0e575b30b804665d3451c416839b Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 04:39:07 -0500 Subject: [PATCH 019/102] M6: the arrows show and move a placement crosshair with a shape or frame tool chosen, and Enter places there (#1839) Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/canvas/tools.rs | 4 ++ crates/engine/src/canvas/tools/keys.rs | 15 +++++++- crates/engine/src/canvas/tools/pointer.rs | 1 + crates/engine/src/cmd/view.rs | 25 ++++++++++++ crates/engine/src/keymap.rs | 1 + crates/engine/src/lib.rs | 2 + crates/engine/src/place_crosshair_tests.rs | 45 ++++++++++++++++++++++ crates/ui-egui/locales/en.toml | 1 + crates/ui-egui/src/canvas/overlays.rs | 13 +++++++ crates/ui-egui/src/control.rs | 6 +++ crates/ui-egui/src/shortcut_keys_tests.rs | 22 +++++++++++ crates/ui-egui/src/shortcuts.rs | 6 ++- docs/ui-parity.md | 5 ++- 13 files changed, 141 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/place_crosshair_tests.rs diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index c68276fd3..cf8fb30b4 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -589,6 +589,10 @@ pub struct ToolState { pub picked: Option, /// The widget layers whose hover styles show while the pointer is over them (a live preview). pub(crate) widget_hover: Vec, + /// The placement crosshair: where Enter puts the next shape or frame once the arrows have + /// shown it (in the middle of the view) and moved it (`tool.crosshair`), in page coordinates. + /// Placing, Escape and a tool change take it away. + pub place_at: Option, } impl ToolState { diff --git a/crates/engine/src/canvas/tools/keys.rs b/crates/engine/src/canvas/tools/keys.rs index 21606b222..4f4d58915 100644 --- a/crates/engine/src/canvas/tools/keys.rs +++ b/crates/engine/src/canvas/tools/keys.rs @@ -84,8 +84,11 @@ impl Session { if self.tool.busy() { return refuse("finish the drag first"); } + // The crosshair the arrows moved goes with the placement, which lands on it when no point + // is given. + let crosshair = self.tool.place_at.take(); let v = &self.ds()?.view; - let (c, zoom) = (at.unwrap_or(Point::new(v.cx, v.cy)), v.zoom); + let (c, zoom) = (at.or(crosshair).unwrap_or(Point::new(v.cx, v.cy)), v.zoom); let (w, h) = tool.click_size(); let ev = |kind| PointerEvent::at(kind, c.x - w / 2.0, c.y - h / 2.0, zoom); let r = self.pointer(&ev(PointerKind::Down)).and_then(|()| self.pointer(&ev(PointerKind::Up))); @@ -111,6 +114,13 @@ impl Session { self.tool.overlay = Overlay::default(); return self.cancel_interaction(); } + // The placement crosshair goes first; the tool stays. + if self.tool.place_at.take().is_some() { + if let Ok(ds) = self.ds_mut() { + ds.revision += 1; + } + return Ok(()); + } if self.end_origin_edit() { return Ok(()); } @@ -174,6 +184,7 @@ impl Session { /// Snapshot of tool state for the UI / inspect. pub fn tool_info(&self) -> serde_json::Value { let shapes: Vec = self.shape_handles().into_iter().map(|(h, at)| json!({"handle": h, "at": at})).collect(); - json!({"tool": self.tool.tool.id(), "busy": self.tool.busy(), "overlay": self.tool.overlay, "arcHandles": self.arc_handles(), "shapeHandles": shapes}) + let crosshair = self.tool.place_at.map(|p| [p.x, p.y]); + json!({"tool": self.tool.tool.id(), "busy": self.tool.busy(), "overlay": self.tool.overlay, "arcHandles": self.arc_handles(), "shapeHandles": shapes, "crosshair": crosshair}) } } diff --git a/crates/engine/src/canvas/tools/pointer.rs b/crates/engine/src/canvas/tools/pointer.rs index 1493604dc..90dc1540b 100644 --- a/crates/engine/src/canvas/tools/pointer.rs +++ b/crates/engine/src/canvas/tools/pointer.rs @@ -79,6 +79,7 @@ impl Session { self.tool.tool = t; self.tool.gesture = Gesture::None; self.tool.pick_only = false; + self.tool.place_at = None; // The tool's cursor shows before the pointer moves. self.tool.overlay = Overlay { builder_remove: self.tool.builder_remove && t == ToolId::ShapeBuilder, cursor: t.cursor(), ..Overlay::default() }; diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 1fc2ef22a..20379a7ba 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -522,6 +522,31 @@ pub fn specs() -> Vec { tool(s, t) } ), + spec!( + "tool.crosshair", + "Move the placement crosshair", + "{dx?, dy? (arrow-key steps, e.g. 1 or -1), big? (the large nudge, like Shift)} — the arrows with a shape or frame tool chosen and nothing selected: the first shows the crosshair in the middle of the view, the next move it by the nudge amount; Enter (`tool.place`) puts the object there", + false, + |s, p| { + if !s.tool.tool.draws_shape() { + return Err(EngineError::Disabled("tool.crosshair".into(), "choose a shape or frame tool first".into())); + } + let step = if boolean(p, "big").unwrap_or(false) { s.prefs.nudge_big } else { s.prefs.nudge_small }; + let dir = |k| num(p, k).filter(|v| v.is_finite()).unwrap_or(0.0).clamp(-100.0, 100.0) * step; + let (dx, dy) = (dir("dx"), dir("dy")); + let v = &s.ds()?.view; + // "It will appear in the middle of the viewport": the first arrow shows it there. + let at = match s.tool.place_at { + Some(c) => figcraft_geom::Point::new(c.x + dx, c.y + dy), + None => figcraft_geom::Point::new(v.cx, v.cy), + }; + s.tool.place_at = Some(at); + if let Ok(ds) = s.ds_mut() { + ds.revision += 1; + } + Ok(json!({"x": at.x, "y": at.y})) + } + ), spec!( "tool.place", "Place with the tool", diff --git a/crates/engine/src/keymap.rs b/crates/engine/src/keymap.rs index a0f0bc4b6..77b6f7efe 100644 --- a/crates/engine/src/keymap.rs +++ b/crates/engine/src/keymap.rs @@ -353,6 +353,7 @@ pub static GESTURES: &[(Group, &str, &str, &str)] = &[ (Tools, "Pan with nothing selected (Shift: farther)", "← ↑ → ↓", "← ↑ → ↓"), (Transform, "Rotate a degree (Shift: 15)", "⌥⌘ ← ↑ → ↓", "Ctrl+Alt+← ↑ → ↓"), (Tools, "Place a shape or frame (its tool chosen)", "↵", "Enter"), + (Tools, "Show and move the placement crosshair (its tool chosen, nothing selected)", "← ↑ → ↓", "← ↑ → ↓"), (Zoom, "Zoom tool: click to zoom in, drag an area", "Hold Z", "Hold Z"), (Zoom, "Zoom tool: zoom out", "Hold ⌥Z", "Hold Alt+Z"), (Zoom, "Zoom around the pointer", "⌘ scroll", "Ctrl+scroll"), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 0da532b25..e4bf41d26 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -463,6 +463,8 @@ mod penpot_export_tests; #[cfg(test)] mod pixel_preview_tests; #[cfg(test)] +mod place_crosshair_tests; +#[cfg(test)] mod placed_image_size_tests; #[cfg(test)] mod playground_tests; diff --git a/crates/engine/src/place_crosshair_tests.rs b/crates/engine/src/place_crosshair_tests.rs new file mode 100644 index 000000000..a2aafba10 --- /dev/null +++ b/crates/engine/src/place_crosshair_tests.rs @@ -0,0 +1,45 @@ +//! The placement crosshair: the arrows with a shape or frame tool chosen show it in the middle of +//! the view and move it, and Enter places the object there ("Use the arrow keys to activate the +//! crosshair cursor. It will appear in the middle of the viewport indicating where the new object +//! will be placed." / "Use the arrow keys to move the crosshair around the canvas or board, then +//! press Return/Enter to place the object.", Accessibility at Figma, #1839). + +use serde_json::json; + +use crate::Session; + +#[test] +fn the_arrows_show_and_move_the_crosshair_and_enter_places_there() { + let mut s = Session::new(); + s.execute("view.set", &json!({"zoom": 1.0, "cx": 300, "cy": 200})).unwrap(); + assert!(s.execute("tool.crosshair", &json!({"dx": 1})).is_err(), "a shape or frame tool first"); + s.execute("tool.rectangle", &json!({})).unwrap(); + // The first arrow shows the crosshair in the middle of the view, unmoved; the next move it by + // the nudge amounts. + let r = s.execute("tool.crosshair", &json!({"dx": 1, "dy": 0})).unwrap(); + assert_eq!((r["x"].as_f64(), r["y"].as_f64()), (Some(300.0), Some(200.0))); + s.execute("tool.crosshair", &json!({"dx": 1, "dy": 0})).unwrap(); + let r = s.execute("tool.crosshair", &json!({"dx": 0, "dy": -1, "big": true})).unwrap(); + assert_eq!((r["x"].as_f64(), r["y"].as_f64()), (Some(301.0), Some(190.0)), "a nudge, then a big nudge"); + assert_eq!(s.tool_info()["crosshair"], json!([301.0, 190.0])); + let v = &s.ds().unwrap().view; + assert_eq!((v.cx, v.cy), (300.0, 200.0), "the view hasn't panned"); + // Enter: the rectangle is centred on the crosshair, which goes. + let placed = s.execute("tool.place", &json!({})).unwrap(); + let id = crate::params::id_of(&placed["ids"][0]).unwrap(); + let b = s.doc().unwrap().world_bounds(id).unwrap(); + assert_eq!((b.center().x, b.center().y), (301.0, 190.0)); + assert_eq!(s.tool.place_at, None); + assert!(s.tool_info()["crosshair"].is_null()); + // Escape takes a shown crosshair away before anything else, the tool staying; a tool change + // takes it away too. + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("tool.rectangle", &json!({})).unwrap(); + s.execute("tool.crosshair", &json!({})).unwrap(); + assert!(s.tool.place_at.is_some()); + s.escape().unwrap(); + assert_eq!((s.tool.place_at, s.tool.tool), (None, crate::ToolId::Rectangle)); + s.execute("tool.crosshair", &json!({})).unwrap(); + s.execute("tool.ellipse", &json!({})).unwrap(); + assert_eq!(s.tool.place_at, None); +} diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index c44635a2a..89cee56eb 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -1073,6 +1073,7 @@ name = "English" "Pages: {pages}" = "Pages: {pages}" "Paint bucket" = "Paint bucket" "Pan the canvas" = "Pan the canvas" +"Show and move the placement crosshair (its tool chosen, nothing selected)" = "Show and move the placement crosshair (its tool chosen, nothing selected)" "Pan with nothing selected (Shift: farther)" = "Pan with nothing selected (Shift: farther)" "Panels" = "Panels" "Paper" = "Paper" diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 483a180b9..efdf3ad63 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -145,6 +145,7 @@ pub(super) fn overlays(app: &FigApp, painter: &egui::Painter, t: &Tokens) -> Vec } // Pen path. pen_overlay(app, painter, zoom); + crosshair_overlay(app, painter); // Eraser brush (vector edit mode). if let Some([x, y, r]) = ov.brush { let c = app.to_screen(x, y); @@ -416,6 +417,18 @@ fn attach_points(app: &FigApp, painter: &egui::Painter, points: &[([f64; 2], boo } } +/// The placement crosshair the arrows showed and moved: where Enter puts the next shape or frame. +fn crosshair_overlay(app: &FigApp, painter: &egui::Painter) { + let Some(p) = app.session.tool.place_at.filter(|_| app.session.tool.tool.draws_shape()) else { return }; + let c = app.to_screen(p.x, p.y); + let col = accent(painter); + for d in [vec2(1.0, 0.0), vec2(0.0, 1.0)] { + painter.line_segment([c - d * 12.0, c - d * 3.0], stroke(col, 1.5)); + painter.line_segment([c + d * 3.0, c + d * 12.0], stroke(col, 1.5)); + } + painter.circle_stroke(c, 3.0, stroke(col, 1.5)); +} + fn pen_overlay(app: &FigApp, painter: &egui::Painter, zoom: f64) { let ov = &app.session.tool.overlay; if !ov.pen.is_empty() { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 322d9032c..405d6dfa7 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1004,6 +1004,12 @@ fn ui_key(app: &mut FigApp, ctx: &Context, p: &Value) -> Result { "ArrowUp" => (0, -1), _ => (0, 1), }; + // A shape or frame tool chosen and nothing selected: the arrows show and move the + // placement crosshair, as the window's key path does. + if app.session.selection().is_empty() && app.session.tool.tool.draws_shape() && !app.session.tool.dev_mode && !(m.cmd || m.ctrl || m.alt) + { + return app.session.execute("tool.crosshair", &json!({"dx": dx, "dy": dy, "big": m.shift})).map_err(|e| e.to_string()); + } let (cmd, params) = if (m.cmd || m.ctrl) && m.alt { // Rotate a degree, 15 with Shift: down and right clockwise, up and left back, about // the selection's rotation origin; nothing while points are being edited. diff --git a/crates/ui-egui/src/shortcut_keys_tests.rs b/crates/ui-egui/src/shortcut_keys_tests.rs index 6907cac5a..dbe6ab3b9 100644 --- a/crates/ui-egui/src/shortcut_keys_tests.rs +++ b/crates/ui-egui/src/shortcut_keys_tests.rs @@ -54,6 +54,28 @@ fn arrows_pan_the_view_when_nothing_is_selected() { assert_eq!(u.app.session.doc().unwrap().world_bounds(r).unwrap().x0, 1.0); } +/// With a shape or frame tool chosen and nothing selected, the arrows show the placement crosshair +/// in the middle of the view and move it (Shift: the large nudge) instead of panning, and Enter +/// places the object there (Accessibility at Figma, #1839). +#[test] +fn arrows_show_and_move_the_placement_crosshair_with_a_shape_tool() { + let mut u = Ui::new(Session::new()); + u.app.run("select.set", json!({"ids": []})); + u.app.run("view.set", json!({"zoom": 2.0, "cx": 100, "cy": 50})); + u.app.run("tool.rectangle", json!({})); + press(&mut u, Key::ArrowRight, Modifiers::NONE); + assert_eq!(view(&u), (100.0, 50.0, 2.0), "no pan: the crosshair shows instead"); + assert_eq!(u.app.session.tool.place_at.map(|p| (p.x, p.y)), Some((100.0, 50.0)), "in the middle of the view"); + press(&mut u, Key::ArrowDown, Modifiers::SHIFT); + assert_eq!(u.app.session.tool.place_at.map(|p| (p.x, p.y)), Some((100.0, 60.0)), "moved by the large nudge"); + press(&mut u, Key::Enter, Modifiers::NONE); + let sel = u.app.session.selection(); + let b = u.app.session.doc().unwrap().world_bounds(sel[0]).unwrap(); + assert_eq!((b.center().x, b.center().y), (100.0, 60.0), "placed at the crosshair"); + assert!(u.app.session.tool.place_at.is_none(), "which goes with the placement"); + assert_eq!(view(&u), (100.0, 50.0, 2.0)); +} + #[test] fn keyboard_box_selection_key_and_cmd_arrows() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index f44adb68e..5f756e160 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -480,7 +480,11 @@ fn key_event(app: &mut FigApp, key: Key, physical: Option, m: Modifiers, re _ => (0.0, 0.0), }; if (dx, dy) != (0.0, 0.0) { - if app.session.selection().is_empty() { + if app.session.selection().is_empty() && app.session.tool.tool.draws_shape() && !app.session.tool.dev_mode && !m.command && !m.alt { + // A shape or frame tool chosen: the arrows show the placement crosshair in the middle + // of the view and move it; Enter places there (Accessibility at Figma). + app.run("tool.crosshair", json!({"dx": dx, "dy": dy, "big": m.shift})); + } else if app.session.selection().is_empty() { app.run("view.pan", json!({"dx": dx, "dy": dy, "big": m.shift})); } else if crate::menus::dev_mode_refuses(app, "transform.nudge") { // Dev Mode: said so, nothing moves. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3963e4624..87af3f3e3 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** patch (with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -61,7 +61,7 @@ interaction feel not yet compared. | Rotate just outside a corner; Shift in 15° steps | done | rotated handle box when layers share a rotation | | Flip, rotate 90° | done | | | Rotation origin (Alt+R) | done | a handle at the selection's centre to drag (snaps to the box's corners, edge middles and centre), double-click puts it back, Escape or Alt+R hides it; the corner handles, the rotation field, Rotate 90°/180° and `transform.rotate` turn about it; it follows the layers and lasts as long as the selection, not saved (the documentation doesn't say; pinned) | -| Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. No crosshair to move with the arrows first | +| Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | | Scale tool (K): handles about an anchor, live factor, panel | done | | @@ -176,6 +176,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-02 | patch | M6, #1839: with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it by the nudge amounts (`tool.crosshair`), Enter places the object there (`tool.place`), Escape or a tool change takes it away; the canvas draws the crosshair and `ui.inspect` reports it (`tool.crosshair`), the Keyboard shortcuts panel lists the gesture ("Use the arrow keys to activate the crosshair cursor...", Accessibility at Figma). Tests: `place_crosshair_tests`, `shortcut_keys_tests::arrows_show_and_move_the_placement_crosshair_with_a_shape_tool`. | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Shift+Alt+= and - make the interface larger and smaller through the sizes Preferences offers, and Cmd/Ctrl+Shift+Alt+0 puts it back to the system's size ("Adjust the scale of the Figma UI [...] Reset to Default: Control ⇧Shift Alt 0; Make Larger: Control ⇧Shift Alt =; Make Smaller: Control ⇧Shift Alt -", Accessibility at Figma); the size is kept at once, as one picked in Preferences is. `pref.uiScaleUp`, `pref.uiScaleDown`, `pref.uiScaleReset`; the sizes list now lives in the engine (`UI_SCALE_SIZES`) and Preferences reads it from there. Found by a documentation audit of the shortcuts. Test: `keymap_tests::the_interface_size_keys_step_through_the_preferences_sizes`. Documented rows 130 → 133, bound 129 → 132 | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Alt+↑/↓ (and ←/→) rotate the selection one degree at a time, 15 with Shift ("Press ⌘Command ⌥Option ↑/ ↓ on Mac or Control Alt ↑/↓ on Windows to rotate an object one degree at a time", Accessibility at Figma); they resized by the nudge before, which Cmd/Ctrl+arrows without Alt still do. Down and right turn clockwise, up and left back (the documentation is silent on the direction). In the shortcuts panel's Transform tab, over the control channel's `ui.key` too. Found by a documentation audit of the shortcuts. Test: `shortcut_keys_tests::cmd_alt_arrows_rotate_a_degree_and_fifteen_with_shift`. Documented rows 129 → 130, bound 128 → 129 | | 2026-11-01 | patch | Shortcuts: the Layers panel opens with Ctrl+1 as well as Alt+1 on Windows and Linux ("Mac: Option 1 Windows: Ctrl 1" in Select layers and objects; "Windows: Alt 1" in Explore the navigation bar and left sidebar). macOS keeps Option+1. Found by a documentation audit of the shortcuts (every chord driven over the control channel). Tests: `keymap_tests::the_layers_panel_answers_both_of_its_documented_windows_keys`, the parity row. Counts unchanged | From 56ad0ba14fa299885fcc2bbdd345f13f9f7e2a9a Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 05:08:41 -0500 Subject: [PATCH 020/102] Placement crosshair: kept with its page and document, gone with a pointer placement, kept when the same tool is chosen again Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/canvas/tools.rs | 7 ++-- crates/engine/src/canvas/tools/draw.rs | 2 ++ crates/engine/src/canvas/tools/keys.rs | 19 ++++++++--- crates/engine/src/canvas/tools/pointer.rs | 5 ++- crates/engine/src/cmd/view.rs | 13 +++++--- crates/engine/src/place_crosshair_tests.rs | 37 ++++++++++++++++++++++ crates/ui-egui/src/canvas/overlays.rs | 2 +- 7 files changed, 73 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index cf8fb30b4..9bc4bef2a 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -590,9 +590,12 @@ pub struct ToolState { /// The widget layers whose hover styles show while the pointer is over them (a live preview). pub(crate) widget_hover: Vec, /// The placement crosshair: where Enter puts the next shape or frame once the arrows have - /// shown it (in the middle of the view) and moved it (`tool.crosshair`), in page coordinates. - /// Placing, Escape and a tool change take it away. + /// shown it (in the middle of the view) and moved it (`tool.crosshair`), in page coordinates + /// of the document and page in `place_on` (elsewhere it isn't shown: `Session::crosshair`). + /// Placing, Escape and a change of tool take it away. pub place_at: Option, + /// The document (uid) and page the crosshair was shown on. + pub(crate) place_on: Option<(u64, NodeId)>, } impl ToolState { diff --git a/crates/engine/src/canvas/tools/draw.rs b/crates/engine/src/canvas/tools/draw.rs index d59a2b904..7831c6fad 100644 --- a/crates/engine/src/canvas/tools/draw.rs +++ b/crates/engine/src/canvas/tools/draw.rs @@ -209,6 +209,8 @@ impl Session { crate::normalize(ds.doc_mut(), &before); } self.commit_interaction()?; + // A placement by the pointer takes the placement crosshair with it, as Enter does. + self.tool.place_at = None; if !self.prefs.keep_tool { self.set_tool(ToolId::Move); } diff --git a/crates/engine/src/canvas/tools/keys.rs b/crates/engine/src/canvas/tools/keys.rs index 4f4d58915..07a91557b 100644 --- a/crates/engine/src/canvas/tools/keys.rs +++ b/crates/engine/src/canvas/tools/keys.rs @@ -86,7 +86,8 @@ impl Session { } // The crosshair the arrows moved goes with the placement, which lands on it when no point // is given. - let crosshair = self.tool.place_at.take(); + let crosshair = self.crosshair(); + self.tool.place_at = None; let v = &self.ds()?.view; let (c, zoom) = (at.or(crosshair).unwrap_or(Point::new(v.cx, v.cy)), v.zoom); let (w, h) = tool.click_size(); @@ -114,8 +115,11 @@ impl Session { self.tool.overlay = Overlay::default(); return self.cancel_interaction(); } - // The placement crosshair goes first; the tool stays. - if self.tool.place_at.take().is_some() { + // The placement crosshair goes first; the tool stays. One left on another page or + // document goes quietly. + let shown = self.crosshair().is_some(); + self.tool.place_at = None; + if shown { if let Ok(ds) = self.ds_mut() { ds.revision += 1; } @@ -184,7 +188,14 @@ impl Session { /// Snapshot of tool state for the UI / inspect. pub fn tool_info(&self) -> serde_json::Value { let shapes: Vec = self.shape_handles().into_iter().map(|(h, at)| json!({"handle": h, "at": at})).collect(); - let crosshair = self.tool.place_at.map(|p| [p.x, p.y]); + let crosshair = self.crosshair().map(|p| [p.x, p.y]); json!({"tool": self.tool.tool.id(), "busy": self.tool.busy(), "overlay": self.tool.overlay, "arcHandles": self.arc_handles(), "shapeHandles": shapes, "crosshair": crosshair}) } + + /// The placement crosshair, while the document and page it was shown on are the ones in + /// front (`ToolState::place_at`). + pub fn crosshair(&self) -> Option { + let here = self.ds().ok().map(|d| (d.uid, d.page)); + self.tool.place_at.filter(|_| here.is_some() && here == self.tool.place_on) + } } diff --git a/crates/engine/src/canvas/tools/pointer.rs b/crates/engine/src/canvas/tools/pointer.rs index 90dc1540b..5696832ab 100644 --- a/crates/engine/src/canvas/tools/pointer.rs +++ b/crates/engine/src/canvas/tools/pointer.rs @@ -76,10 +76,13 @@ impl Session { if !matches!(t, ToolId::Move | ToolId::Scale | ToolId::Hand) && self.ds().is_ok_and(|d| d.vector_edit.is_some()) { let _ = crate::vectoredit::end(self); } + // The placement crosshair goes with a change of tool, not with the same tool chosen again. + if self.tool.tool != t { + self.tool.place_at = None; + } self.tool.tool = t; self.tool.gesture = Gesture::None; self.tool.pick_only = false; - self.tool.place_at = None; // The tool's cursor shows before the pointer moves. self.tool.overlay = Overlay { builder_remove: self.tool.builder_remove && t == ToolId::ShapeBuilder, cursor: t.cursor(), ..Overlay::default() }; diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 20379a7ba..e2f8d575b 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -534,13 +534,18 @@ pub fn specs() -> Vec { let step = if boolean(p, "big").unwrap_or(false) { s.prefs.nudge_big } else { s.prefs.nudge_small }; let dir = |k| num(p, k).filter(|v| v.is_finite()).unwrap_or(0.0).clamp(-100.0, 100.0) * step; let (dx, dy) = (dir("dx"), dir("dy")); - let v = &s.ds()?.view; - // "It will appear in the middle of the viewport": the first arrow shows it there. - let at = match s.tool.place_at { + let (uid, page, centre) = { + let ds = s.ds()?; + (ds.uid, ds.page, figcraft_geom::Point::new(ds.view.cx, ds.view.cy)) + }; + // "It will appear in the middle of the viewport": the first arrow shows it there (a + // crosshair left on another page or document starts over). + let at = match s.crosshair() { Some(c) => figcraft_geom::Point::new(c.x + dx, c.y + dy), - None => figcraft_geom::Point::new(v.cx, v.cy), + None => centre, }; s.tool.place_at = Some(at); + s.tool.place_on = Some((uid, page)); if let Ok(ds) = s.ds_mut() { ds.revision += 1; } diff --git a/crates/engine/src/place_crosshair_tests.rs b/crates/engine/src/place_crosshair_tests.rs index a2aafba10..9bd89dc90 100644 --- a/crates/engine/src/place_crosshair_tests.rs +++ b/crates/engine/src/place_crosshair_tests.rs @@ -7,6 +7,7 @@ use serde_json::json; use crate::Session; +use crate::tools::{PointerEvent, PointerKind}; #[test] fn the_arrows_show_and_move_the_crosshair_and_enter_places_there() { @@ -43,3 +44,39 @@ fn the_arrows_show_and_move_the_crosshair_and_enter_places_there() { s.execute("tool.ellipse", &json!({})).unwrap(); assert_eq!(s.tool.place_at, None); } + +#[test] +fn the_crosshair_keeps_its_page_and_goes_with_a_pointer_placement_but_not_the_same_tool_again() { + let mut s = Session::new(); + s.execute("view.set", &json!({"zoom": 1.0, "cx": 300, "cy": 200})).unwrap(); + s.execute("tool.rectangle", &json!({})).unwrap(); + s.execute("tool.crosshair", &json!({"dx": 1})).unwrap(); + s.execute("tool.crosshair", &json!({"dx": 1})).unwrap(); + // The tool already chosen named again keeps the crosshair: `tool.place {tool}` lands on it. + let placed = s.execute("tool.place", &json!({"tool": "rectangle"})).unwrap(); + let id = crate::params::id_of(&placed["ids"][0]).unwrap(); + assert_eq!(s.doc().unwrap().world_bounds(id).unwrap().center().x, 301.0); + // A click places too (the tool kept by the preference) and takes the crosshair with it. + s.prefs.keep_tool = true; + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("tool.rectangle", &json!({})).unwrap(); + s.execute("tool.crosshair", &json!({})).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::Down, 600.0, 600.0, 1.0)).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::Up, 600.0, 600.0, 1.0)).unwrap(); + assert_eq!((s.tool.tool, s.tool.place_at), (crate::ToolId::Rectangle, None), "placed by the pointer: the crosshair goes, the tool stays"); + // Another page in front: the crosshair shown on the first isn't there, Escape has nothing to + // take, and the next arrow starts over in the middle of this page's view. + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("tool.crosshair", &json!({"dx": 5})).unwrap(); + s.execute("page.add", &json!({})).unwrap(); + s.execute("page.select", &json!({"index": 1})).unwrap(); + s.execute("tool.rectangle", &json!({})).unwrap(); + assert_eq!(s.crosshair(), None); + assert!(s.tool_info()["crosshair"].is_null()); + s.escape().unwrap(); + assert_eq!(s.tool.tool, crate::ToolId::Move, "Escape went on to the tool"); + s.execute("tool.rectangle", &json!({})).unwrap(); + let r = s.execute("tool.crosshair", &json!({"dx": 1})).unwrap(); + let v = &s.ds().unwrap().view; + assert_eq!((r["x"].as_f64(), r["y"].as_f64()), (Some(v.cx), Some(v.cy)), "shown afresh in the middle of this page's view"); +} diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index efdf3ad63..6079fabfa 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -419,7 +419,7 @@ fn attach_points(app: &FigApp, painter: &egui::Painter, points: &[([f64; 2], boo /// The placement crosshair the arrows showed and moved: where Enter puts the next shape or frame. fn crosshair_overlay(app: &FigApp, painter: &egui::Painter) { - let Some(p) = app.session.tool.place_at.filter(|_| app.session.tool.tool.draws_shape()) else { return }; + let Some(p) = app.session.crosshair().filter(|_| app.session.tool.tool.draws_shape()) else { return }; let c = app.to_screen(p.x, p.y); let col = accent(painter); for d in [vec2(1.0, 0.0), vec2(0.0, 1.0)] { From 99d5e3e5881631bd12fb086e8b91bc0aebecd0b5 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 06:05:20 -0500 Subject: [PATCH 021/102] Formatting after the merge Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7247eccdf..20e5847b0 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -242,9 +242,9 @@ mod style_props_tests; mod table_paste_tests; #[cfg(test)] mod text_enter_tests; +mod text_link_tests; #[cfg(test)] mod text_mixed_fill_tests; -mod text_link_tests; #[cfg(test)] mod titlebar_tests; #[cfg(test)] From 695ca0752874c94138bd5e362136bf28850a3c42 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 06:43:02 -0500 Subject: [PATCH 022/102] M3: text styles carry paragraph spacing and indent, the list style and the OpenType features (#1829) ParagraphStyle beside TextStyle in StyleKind::Text: style.create takes it from the layer or a value, style.apply sets it (the list on the paragraphs touched for a range), style.update moves it, editing it unlinks, .fig files keep it with the style; tests in styles_behaviour_tests and fig_export_assets_tests. Co-Authored-By: Claude Fable 5.1 --- crates/doc/src/colors.rs | 2 +- crates/doc/src/lib.rs | 2 +- crates/doc/src/styles.rs | 22 ++++- crates/doc/src/text.rs | 68 ++++++++++++++ crates/engine/src/assets/style_vars.rs | 4 +- crates/engine/src/cmd/file/load.rs | 6 +- crates/engine/src/cmd/styles.rs | 94 ++++++++++++++++--- crates/engine/src/content/synthetic_ds.rs | 4 +- crates/engine/src/fig_export_assets_tests.rs | 21 +++++ crates/engine/src/fonts.rs | 2 +- crates/engine/src/fonts/tests.rs | 5 +- crates/engine/src/sketch_import_tests.rs | 2 +- crates/engine/src/styles_behaviour_tests.rs | 65 ++++++++++++- crates/engine/src/text_style_picker_tests.rs | 4 +- crates/format/src/fig/assets_tests.rs | 4 +- crates/format/src/fig/export/assets.rs | 7 +- crates/format/src/fig/text_skip_ink_tests.rs | 6 +- crates/format/src/fig/text_style_tests.rs | 2 +- crates/format/src/penpot.rs | 12 +-- crates/format/src/rest.rs | 10 +- crates/format/src/rest/tests.rs | 2 +- crates/format/src/sketch/shared_tests.rs | 2 +- crates/ui-egui/src/widgets/style_picker.rs | 41 +++++++- .../ui-egui/src/widgets/style_picker/tests.rs | 8 +- docs/components-parity.md | 5 +- docs/mcp.md | 12 ++- 26 files changed, 346 insertions(+), 66 deletions(-) diff --git a/crates/doc/src/colors.rs b/crates/doc/src/colors.rs index f4681601b..bd4dfdbab 100644 --- a/crates/doc/src/colors.rs +++ b/crates/doc/src/colors.rs @@ -79,7 +79,7 @@ impl Style { pub fn for_each_color_mut(&mut self, f: &mut ColorVisitor) { match &mut self.kind { StyleKind::Paint { paints } => paints.iter_mut().for_each(|p| p.for_each_color_mut(f)), - StyleKind::Text { style } => style.for_each_color_mut(f), + StyleKind::Text { style, .. } => style.for_each_color_mut(f), StyleKind::Effect { effects } => effects.iter_mut().for_each(|e| e.for_each_color_mut(f)), StyleKind::Grid { grids } => grids.iter_mut().for_each(|g| f(&mut g.color)), } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 89eb97269..eecb64af2 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -1206,7 +1206,7 @@ impl Document { .styles .iter() .filter_map(|s| match &s.kind { - StyleKind::Text { style } => Some((s.id.clone(), style.clone())), + StyleKind::Text { style, .. } => Some((s.id.clone(), style.clone())), _ => None, }) .collect(); diff --git a/crates/doc/src/styles.rs b/crates/doc/src/styles.rs index f3893077e..b10806e33 100644 --- a/crates/doc/src/styles.rs +++ b/crates/doc/src/styles.rs @@ -1,7 +1,7 @@ //! Shared styles and variables. use crate::props::{Effect, LayoutGrid}; -use crate::text::TextStyle; +use crate::text::{ParagraphStyle, TextStyle}; use figcraft_color::{Color, Paint}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; @@ -14,10 +14,22 @@ pub type ModeId = String; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "camelCase")] pub enum StyleKind { - Paint { paints: Vec }, - Text { style: TextStyle }, - Effect { effects: Vec }, - Grid { grids: Vec }, + Paint { + paints: Vec, + }, + Text { + style: TextStyle, + /// What the style sets at the paragraph and layer level (#1829); boxed to keep the enum + /// small. + #[serde(default, skip_serializing_if = "crate::node::is_default")] + paragraph: Box, + }, + Effect { + effects: Vec, + }, + Grid { + grids: Vec, + }, } impl StyleKind { diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 0c41d3c9a..76771c80c 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -291,6 +291,23 @@ pub struct TextStyle { pub style_id: Option, } +/// What a text style sets at the paragraph and layer level, beside its character style +/// ([`TextStyle`]): paragraph spacing and indent, the list style and the OpenType features +/// ("Supported in text styles": "Paragraph spacing and indentation", "Lists", "OpenType +/// features", Create and apply text styles). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct ParagraphStyle { + #[serde(skip_serializing_if = "crate::node::is_default")] + pub paragraph_spacing: f64, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub paragraph_indent: f64, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub list: ListStyle, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub features: std::collections::BTreeMap, +} + /// The font new text starts in. A build can name another (`FIGCRAFT_DEFAULT_FONT="Noto Sans Thai"`, /// for a distribution whose users mostly write a script Inter lacks); empty means Inter. pub const DEFAULT_FONT: &str = match option_env!("FIGCRAFT_DEFAULT_FONT") { @@ -843,6 +860,57 @@ impl TextData { (a..=b).all(|p| self.para_list(p).list == first.list && self.para_list(p).indent == first.indent).then_some(first) } + /// What a text style made from this text sets at the paragraph and layer level: the paragraph + /// spacing and indent, the list style (the one every paragraph shares; the base one when they + /// differ) and the OpenType features. + pub fn paragraph_style(&self) -> ParagraphStyle { + let list = match self.paragraphs.first() { + Some(first) if self.paragraphs.iter().all(|p| p.list == first.list) => first.list, + _ => self.list, + }; + ParagraphStyle { paragraph_spacing: self.paragraph_spacing, paragraph_indent: self.paragraph_indent, list, features: self.features.clone() } + } + + /// Take what text style `ps` sets at the paragraph and layer level: the spacing, indent and + /// features on the layer, the list style on every paragraph. + pub fn take_paragraph_style(&mut self, ps: &ParagraphStyle) { + let len = self.char_count(); + self.take_paragraph_style_in(0, len, ps); + } + + /// As [`take_paragraph_style`](Self::take_paragraph_style), with the list style going to the + /// paragraphs chars `start..end` touch only; the spacing, indent and features are the + /// layer's, as in Figma. + pub fn take_paragraph_style_in(&mut self, start: usize, end: usize, ps: &ParagraphStyle) { + self.paragraph_spacing = ps.paragraph_spacing; + self.paragraph_indent = ps.paragraph_indent; + self.features.clone_from(&ps.features); + self.set_para_lists(start, end, |pl| pl.list = ps.list); + } + + /// Follow text style `id`'s paragraph-level definition wherever chars link to it. + pub fn update_paragraph_style(&mut self, id: &str, ps: &ParagraphStyle) { + let linked: Vec<(usize, usize)> = + self.spans().into_iter().filter(|(_, _, s)| s.style_id.as_deref() == Some(id)).map(|(a, b, _)| (a, b)).collect(); + for (a, b) in linked { + self.take_paragraph_style_in(a, b, ps); + } + } + + /// Whether chars `start..end` show what text style `ps` sets at the paragraph and layer + /// level: the layer's spacing, indent and features, and their paragraphs' list style. + pub fn shows_paragraph_style_in(&self, start: usize, end: usize, ps: &ParagraphStyle) -> bool { + self.paragraph_spacing == ps.paragraph_spacing + && self.paragraph_indent == ps.paragraph_indent + && self.features == ps.features + && self.common_para_list(start, end).is_some_and(|pl| pl.list == ps.list) + } + + /// Whether the whole text shows what text style `ps` sets at the paragraph and layer level. + pub fn shows_paragraph_style(&self, ps: &ParagraphStyle) -> bool { + self.shows_paragraph_style_in(0, self.char_count(), ps) + } + /// Link chars `start..end` (all of them when the range is empty or the whole text) to text /// style `id`, defined as `def`. pub fn link_text_style(&mut self, start: usize, end: usize, def: &TextStyle, id: &str) { diff --git a/crates/engine/src/assets/style_vars.rs b/crates/engine/src/assets/style_vars.rs index 7fb30fd06..12db4eaa8 100644 --- a/crates/engine/src/assets/style_vars.rs +++ b/crates/engine/src/assets/style_vars.rs @@ -113,7 +113,7 @@ fn resolved(vars: &Variables, st: &Style, modes: &Modes) -> StyleKind { (StyleKind::Grid { grids }, Some((BoundList::Grids, i, field)), VariableValue::Number(x)) => { crate::cmd::lists::set_grid_field(grids, i, field, *x); } - (StyleKind::Text { style }, None, _) => set_text_field(style, key, &val), + (StyleKind::Text { style, .. }, None, _) => set_text_field(style, key, &val), _ => {} } } @@ -206,7 +206,7 @@ pub fn refresh(doc: &mut Document, before: Option<&Document>, only: Option<&BTre && was.is_none_or(|w| w.kind == n.kind) { for st in doc.styles.iter().filter(|s| !s.bound.is_empty()) { - if let StyleKind::Text { style } = kind_for(doc, st, id).as_ref() { + if let StyleKind::Text { style, .. } = kind_for(doc, st, id).as_ref() { t.update_text_style(&st.id, style); } } diff --git a/crates/engine/src/cmd/file/load.rs b/crates/engine/src/cmd/file/load.rs index 5033a057e..3e917d5dd 100644 --- a/crates/engine/src/cmd/file/load.rs +++ b/crates/engine/src/cmd/file/load.rs @@ -250,7 +250,7 @@ fn match_font_families(doc: &mut Document) { } // Shared text styles too, so they stay like the layers linked to them. for st in &mut doc.styles { - if let StyleKind::Text { style } = &mut st.kind { + if let StyleKind::Text { style, .. } = &mut st.kind { fix(style); } } @@ -294,7 +294,7 @@ fn platform_tracking(doc: &mut Document) { } } for st in &mut doc.styles { - if let StyleKind::Text { style } = &mut st.kind { + if let StyleKind::Text { style, .. } = &mut st.kind { track(style); } } @@ -365,7 +365,7 @@ fn sketch_line_heights(doc: &mut Document) { } } for st in &mut doc.styles { - if let StyleKind::Text { style } = &mut st.kind { + if let StyleKind::Text { style, .. } = &mut st.kind { set(style); } } diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index 99d4521e4..313062a68 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -3,6 +3,7 @@ use std::collections::BTreeMap; use figcraft_color::{Color, Paint, PaintKind}; +use figcraft_doc::ParagraphStyle; use figcraft_doc::{ Collection, CollectionId, Document, Effect, EffectKind, Mode, ModeId, Node, NodeId, NodeKind, Style, StyleId, StyleKind, TextData, TextStyle, Variable, VariableId, VariableType, VariableValue, Variables, trim_num, @@ -261,6 +262,41 @@ fn text_style_of(n: &Node, at: Option) -> Option { Some(at.map_or(&t.style, |a| t.style_at(a)).as_text_style()) } +/// What a text style definition from JSON sets at the paragraph level, in the `node.set` +/// spellings (`paragraphSpacing`, `paragraphIndent`, `listStyle`: none|bulleted|numbered, +/// `features` or `openTypeFeatures`: `{tag: bool}`); keys left out are the defaults. +fn paragraph_style_json(cmd: &str, v: &Value) -> Result { + let Value::Object(m) = v else { return Ok(ParagraphStyle::default()) }; + let mut ps = ParagraphStyle::default(); + let length = + |k: &str, x: &Value| f64_of(x).filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 10_000.0)).ok_or_else(|| bad(cmd, format!("{k}: a number"))); + for (k, x) in m { + match k.as_str() { + "paragraphSpacing" | "paragraph_spacing" => ps.paragraph_spacing = length(k, x)?, + "paragraphIndent" | "paragraph_indent" => ps.paragraph_indent = length(k, x)?, + "listStyle" | "list" => ps.list = super::props::enum_of(x).ok_or_else(|| bad(cmd, "listStyle: none|bulleted|numbered"))?, + "features" | "openTypeFeatures" | "fontFeatures" | "textFeatures" => { + ps.features = super::props::features_of(cmd, x)?.into_iter().filter_map(|(tag, on)| Some((tag, on?))).collect(); + } + _ => {} + } + } + Ok(ps) +} + +/// What a layer's text sets at the paragraph level, the list style being that of the paragraphs +/// chars `range` touch when given (the layer's when they differ). +fn paragraph_style_of(n: &Node, range: Option<(usize, usize)>) -> Option { + let t = n.kind.text()?; + let mut ps = t.paragraph_style(); + if let Some((a, b)) = range + && let Some(pl) = t.common_para_list(a, b) + { + ps.list = pl.list; + } + Some(ps) +} + fn detach(s: &mut Session, p: &Value) -> Result { let cmd = "style.detach"; let which = req_string(cmd, p, "which")?; @@ -295,7 +331,7 @@ fn kind_from_node(t: &str, n: &Node) -> Option { Some(match t { "paint" | "color" | "fill" => StyleKind::Paint { paints: n.fills.clone() }, "stroke" => StyleKind::Paint { paints: n.strokes.clone() }, - "text" => StyleKind::Text { style: text_style_of(n, None)? }, + "text" => StyleKind::Text { style: text_style_of(n, None)?, paragraph: Box::new(paragraph_style_of(n, None)?) }, "effect" => StyleKind::Effect { effects: n.effects.clone() }, "grid" => StyleKind::Grid { grids: n.grids.clone() }, _ => return None, @@ -317,13 +353,17 @@ fn create(s: &mut Session, p: &Value) -> Result { let kind = if let Some(v) = get(p, "value") { match t.as_str() { "paint" | "color" | "fill" => StyleKind::Paint { paints: paints_of(v).ok_or_else(|| bad(cmd, "value: paints"))? }, - "text" => StyleKind::Text { style: text_style_json(cmd, v)? }, + "text" => StyleKind::Text { style: text_style_json(cmd, v)?, paragraph: Box::new(paragraph_style_json(cmd, v)?) }, "effect" => StyleKind::Effect { effects: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, "grid" => StyleKind::Grid { grids: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, _ => return Err(bad(cmd, "type: paint|text|effect|grid")), } - } else if let Some((tid, a, _)) = range { - StyleKind::Text { style: doc.node(tid).and_then(|n| text_style_of(n, Some(a))).ok_or_else(|| bad(cmd, "not a text layer"))? } + } else if let Some((tid, a, b)) = range { + let n = doc.node(tid).ok_or_else(|| bad(cmd, "not a text layer"))?; + StyleKind::Text { + style: text_style_of(n, Some(a)).ok_or_else(|| bad(cmd, "not a text layer"))?, + paragraph: Box::new(paragraph_style_of(n, Some((a, b))).ok_or_else(|| bad(cmd, "not a text layer"))?), + } } else { let n = from.and_then(|f| doc.node(f)).ok_or_else(|| bad(cmd, "pass `value` or select a layer to take it from"))?; kind_from_node(&t, n).ok_or_else(|| bad(cmd, "that layer has no such property"))? @@ -343,7 +383,7 @@ fn create(s: &mut Session, p: &Value) -> Result { }; doc.styles.push(Style { id: sid.clone(), name, description: string(p, "description").unwrap_or_default(), kind: kind.clone(), bound }); // The source layer (or the selected chars) becomes linked to the new style. - if let (Some((tid, a, b)), StyleKind::Text { style }) = (range, &kind) { + if let (Some((tid, a, b)), StyleKind::Text { style, .. }) = (range, &kind) { if let NodeKind::Text(td) = &mut doc.get_mut(tid)?.kind { td.link_text_style(a, b, style, &sid); } @@ -387,11 +427,13 @@ pub fn apply_style_ref(doc: &mut Document, id: NodeId, field: &str, sid: Option< n.grids = grids.clone(); n.styles.grid = Some(id.clone()); } - ("textStyle", Some(Style { kind: StyleKind::Text { style }, id, .. })) => { - // Every char takes the style's typography (their fills and links stay). + ("textStyle", Some(Style { kind: StyleKind::Text { style, paragraph }, id, .. })) => { + // Every char takes the style's typography (their fills and links stay), and the layer + // what the style sets at the paragraph level (#1829). if let NodeKind::Text(t) = &mut n.kind { let len = t.char_count(); t.link_text_style(0, len, style, id); + t.take_paragraph_style(paragraph); } n.styles.text = Some(id.clone()); } @@ -416,7 +458,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { let st = req_string(cmd, p, "style")?; let style = s.doc()?.style(&st).cloned().ok_or_else(|| bad(cmd, format!("no style `{st}`")))?; // Text styles go on chars: a range, the selected chars of the edited text, or whole layers. - if let StyleKind::Text { style: def } = &style.kind { + if let StyleKind::Text { style: def, paragraph } = &style.kind { // A text style is no property of other layers: they're left alone. let doc = s.doc()?; let targets: Vec = @@ -430,6 +472,8 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { Some((a, b)) => { if let NodeKind::Text(t) = &mut doc.get_mut(i)?.kind { t.link_text_style(a, b, def, &style.id); + // The list goes to the paragraphs touched; the rest is the layer's. + t.take_paragraph_style_in(a, b, paragraph); } } None => apply_style_ref(doc, i, "textStyle", Some(&style.id))?, @@ -506,7 +550,7 @@ fn update(s: &mut Session, p: &Value) -> Result { let cur = doc.styles.get(idx).map(|x| x.kind.type_name()).unwrap_or("paint"); Some(match cur { "paint" => StyleKind::Paint { paints: paints_of(v).ok_or_else(|| bad(cmd, "value: paints"))? }, - "text" => StyleKind::Text { style: text_style_json(cmd, v)? }, + "text" => StyleKind::Text { style: text_style_json(cmd, v)?, paragraph: Box::new(paragraph_style_json(cmd, v)?) }, "effect" => StyleKind::Effect { effects: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, _ => StyleKind::Grid { grids: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, }) @@ -651,22 +695,23 @@ fn rename_folder(s: &mut Session, p: &Value) -> Result { /// Re-apply style `sid` to every node (and text chars) linked to it. pub fn propagate_style(doc: &mut Document, sid: &str) { let text_def = match doc.style(sid).map(|s| &s.kind) { - Some(StyleKind::Text { style }) => Some(style.clone()), + Some(StyleKind::Text { style, paragraph }) => Some((style.clone(), paragraph.clone())), _ => None, }; let ids: Vec = doc.ids().collect(); for i in ids { let Some(n) = doc.node(i) else { continue }; - if let Some(def) = &text_def { + if let Some((def, paragraph)) = &text_def { if n.kind.text().is_some_and(|t| t.links_text_style(sid)) { let def = match doc.style(sid).map(|st| crate::style_vars::kind_for(doc, st, i).into_owned()) { - Some(StyleKind::Text { style }) => style, + Some(StyleKind::Text { style, .. }) => style, _ => def.clone(), }; if let Ok(n) = doc.get_mut(i) && let NodeKind::Text(t) = &mut n.kind { t.update_text_style(sid, &def); + t.update_paragraph_style(sid, paragraph); } } continue; @@ -695,7 +740,16 @@ pub fn sync_text_styles(doc: &mut Document, ids: &[NodeId]) { .styles .iter() .filter_map(|s| match &s.kind { - StyleKind::Text { style } => Some((s.id.clone(), style.clone())), + StyleKind::Text { style, .. } => Some((s.id.clone(), style.clone())), + _ => None, + }) + .collect(); + // What each text style sets at the paragraph level (#1829); no variable binds those. + let paras: BTreeMap<&str, &ParagraphStyle> = doc + .styles + .iter() + .filter_map(|s| match &s.kind { + StyleKind::Text { paragraph, .. } => Some((s.id.as_str(), paragraph.as_ref())), _ => None, }) .collect(); @@ -707,7 +761,7 @@ pub fn sync_text_styles(doc: &mut Document, ids: &[NodeId]) { // Styles with bound fields read as this layer sees them. let mut defs = std::borrow::Cow::Borrowed(&defs); for st in &varying { - if let StyleKind::Text { style } = crate::style_vars::kind_for(doc, st, id).into_owned() { + if let StyleKind::Text { style, .. } = crate::style_vars::kind_for(doc, st, id).into_owned() { defs.to_mut().insert(st.id.clone(), style); } } @@ -717,11 +771,23 @@ pub fn sync_text_styles(doc: &mut Document, ids: &[NodeId]) { && t2.text_style_link() == Some(None) && let Some(def) = defs.get(sid) && t2.spans().iter().all(|(_, _, s)| s.shows_text_style(def)) + && paras.get(sid.as_str()).is_some_and(|ps| t2.shows_paragraph_style(ps)) { let len = t2.char_count(); t2.restyle(0, len, |s| s.style_id = Some(sid.clone())); } t2.check_text_styles(|sid| defs.get(sid)); + // Chars whose paragraphs left their style's list, and every char of a layer whose + // paragraph spacing, indent or features were edited, unlink too (#1829). + let gone: Vec<(usize, usize)> = t2 + .spans() + .iter() + .filter(|(a, b, s)| s.style_id.as_deref().is_some_and(|sid| paras.get(sid).is_none_or(|ps| !t2.shows_paragraph_style_in(*a, *b, ps)))) + .map(|(a, b, _)| (*a, *b)) + .collect(); + for (a, b) in gone { + t2.unlink_text_style(a, b); + } let link = t2.text_style_link().flatten().map(str::to_string); if t2 != *t || link != n.styles.text { updates.push((id, link, t2)); diff --git a/crates/engine/src/content/synthetic_ds.rs b/crates/engine/src/content/synthetic_ds.rs index 74558567f..be5268355 100644 --- a/crates/engine/src/content/synthetic_ds.rs +++ b/crates/engine/src/content/synthetic_ds.rs @@ -154,7 +154,7 @@ fn auto_layout(doc: &mut Document, id: NodeId, mode: LayoutMode, gap: f64, pad: fn styled_text(doc: &mut Document, parent: NodeId, chars: &str, name: &str, style: &str) -> DocResult { let id = doc.create(parent, text(chars), name, 0.0, 0.0, 60.0, 16.0)?; let def = doc.styles.iter().find(|s| s.id == style).and_then(|s| match &s.kind { - StyleKind::Text { style } => Some(style.clone()), + StyleKind::Text { style, .. } => Some(style.clone()), _ => None, }); set_node(doc, id, |n| { @@ -242,7 +242,7 @@ fn foundations(doc: &mut Document) -> (CollectionId, ModeId, ModeId) { id: format!("ds:text:{name}"), name: name.into(), description: String::new(), - kind: StyleKind::Text { style }, + kind: StyleKind::Text { style, paragraph: Default::default() }, bound: Default::default(), }); } diff --git a/crates/engine/src/fig_export_assets_tests.rs b/crates/engine/src/fig_export_assets_tests.rs index f5b9f7758..ef88bc680 100644 --- a/crates/engine/src/fig_export_assets_tests.rs +++ b/crates/engine/src/fig_export_assets_tests.rs @@ -122,6 +122,27 @@ fn variables_styles_and_instance_sizes_come_back() { assert!(after.iter().any(|l| l.contains("\"In the dark\"") && l.contains("FFFFFF")), "{after:#?}"); } +/// #1829: a text style's paragraph spacing and indent and its list style go through a `.fig` +/// file with it (the style's sample layer carries them, as a Figma file's does). +#[test] +fn a_text_styles_paragraph_values_come_back_from_a_fig_file() { + let mut s = Session::new(); + let t = id(&run(&mut s, "text.create", json!({"text": "One\nTwo", "x": 0, "y": 0}))); + run(&mut s, "node.set", json!({"ids": [t], "paragraphSpacing": 12, "paragraphIndent": 8, "listStyle": "bulleted"})); + run(&mut s, "style.create", json!({"type": "text", "name": "Audit", "from": t})); + let path = std::env::temp_dir().join(format!("figcraft-fig-text-style-{}.fig", std::process::id())); + run(&mut s, "file.export", json!({"format": "fig", "path": path.to_string_lossy()})); + run(&mut s, "file.open", json!({"path": path.to_string_lossy()})); + let _ = std::fs::remove_file(&path); + let doc = s.doc().unwrap(); + let st = doc.styles.iter().find(|x| x.name == "Audit").unwrap(); + let figcraft_doc::StyleKind::Text { paragraph, .. } = &st.kind else { panic!("{:?}", st.kind) }; + assert_eq!((paragraph.paragraph_spacing, paragraph.paragraph_indent, paragraph.list), (12.0, 8.0, figcraft_doc::ListStyle::Bulleted)); + // The layer the style was made from is linked to it again, showing the same values. + let layer = doc.nodes().find(|n| n.kind.text().is_some()).unwrap(); + assert_eq!(layer.styles.text.as_deref(), Some(st.id.as_str())); +} + #[test] fn every_example_keeps_its_variables_and_styles() { let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples"); diff --git a/crates/engine/src/fonts.rs b/crates/engine/src/fonts.rs index 484e7b88e..e0538db67 100644 --- a/crates/engine/src/fonts.rs +++ b/crates/engine/src/fonts.rs @@ -54,7 +54,7 @@ pub fn missing(doc: &Document) -> Vec { } } for st in &doc.styles { - if let StyleKind::Text { style } = &st.kind { + if let StyleKind::Text { style, .. } = &st.kind { add(&style.font_family, false); } if let Some(var) = st.bound.get("fontFamily") { diff --git a/crates/engine/src/fonts/tests.rs b/crates/engine/src/fonts/tests.rs index 5df9a8540..fc9713535 100644 --- a/crates/engine/src/fonts/tests.rs +++ b/crates/engine/src/fonts/tests.rs @@ -37,7 +37,10 @@ fn lists_families_of_layers_ranges_styles_and_variables_once_each() { id: "S:1".into(), name: "Heading".into(), description: String::new(), - kind: StyleKind::Text { style: TextStyle { font_family: "FigCraft Missing C".into(), ..TextStyle::default() } }, + kind: StyleKind::Text { + style: TextStyle { font_family: "FigCraft Missing C".into(), ..TextStyle::default() }, + paragraph: Default::default(), + }, bound: Default::default(), }); s.execute("variable.createCollection", &json!({"name": "Type", "modes": ["Light", "Dark"]})).unwrap(); diff --git a/crates/engine/src/sketch_import_tests.rs b/crates/engine/src/sketch_import_tests.rs index e05dade6c..b5ddab8b0 100644 --- a/crates/engine/src/sketch_import_tests.rs +++ b/crates/engine/src/sketch_import_tests.rs @@ -520,7 +520,7 @@ fn sketch_shared_text_styles_match_their_layers() { .styles .iter() .find_map(|st| match &st.kind { - figcraft_doc::StyleKind::Text { style } if st.name == "Body" => Some(style.clone()), + figcraft_doc::StyleKind::Text { style, .. } if st.name == "Body" => Some(style.clone()), _ => None, }) .unwrap(); diff --git a/crates/engine/src/styles_behaviour_tests.rs b/crates/engine/src/styles_behaviour_tests.rs index de9da5a5d..f1ebd96de 100644 --- a/crates/engine/src/styles_behaviour_tests.rs +++ b/crates/engine/src/styles_behaviour_tests.rs @@ -5,10 +5,11 @@ //! line; "docs silent" marks behaviour the documentation doesn't describe (pinned as it is). use serde_json::{Value, json}; +use std::collections::BTreeMap; use crate::Session; use crate::params::id_of; -use figcraft_doc::{Node, NodeId}; +use figcraft_doc::{ListStyle, Node, NodeId, ParagraphStyle, StyleKind, TextData}; fn id(v: Value) -> NodeId { id_of(&v["id"]).unwrap() @@ -355,6 +356,68 @@ fn text_styles_go_on_text_layers_and_chars() { assert_eq!(tx.styles.text, None, "mixed: the layer isn't linked as a whole"); } +#[test] +fn text_styles_carry_paragraph_spacing_indent_lists_and_features() { + // "Supported in text styles": "Paragraph spacing and indentation", "Lists" and "OpenType + // features", beside the character properties (Create and apply text styles). A style made + // from a text takes them, applying it sets them, editing one on a styled text unlinks it. + let mut s = Session::new(); + let td = |s: &Session, n: NodeId| -> TextData { node(s, n).kind.text().unwrap().clone() }; + let t = text(&mut s, 0.0); + let props = json!({"characters": "One\nTwo", "paragraphSpacing": 12, "paragraphIndent": 8, "listStyle": "bulleted", "features": {"tnum": true, "liga": false}}); + run(&mut s, "node.set", json!({"id": t, "props": props})); + let st = sid(run(&mut s, "style.create", json!({"type": "text", "name": "Audit", "from": t}))); + let listed = run(&mut s, "style.list", json!({"type": "text"})); + let audit = listed.as_array().unwrap().iter().find(|x| x["id"] == json!(st)).unwrap(); + assert_eq!( + audit["paragraph"], + json!({"paragraph_spacing": 12.0, "paragraph_indent": 8.0, "list": "bulleted", "features": {"liga": false, "tnum": true}}) + ); + // Applying it sets them on a plain text, every paragraph in the list; the layer links. + let t2 = text(&mut s, 300.0); + run(&mut s, "node.set", json!({"id": t2, "props": {"characters": "A\nB\nC"}})); + run(&mut s, "style.apply", json!({"ids": [t2], "style": st})); + let d = td(&s, t2); + assert_eq!((d.paragraph_spacing, d.paragraph_indent), (12.0, 8.0)); + assert!((0..3).all(|p| d.para_list(p).list == ListStyle::Bulleted), "{:?}", d.paragraphs); + assert_eq!(d.features, BTreeMap::from([("liga".to_string(), false), ("tnum".to_string(), true)])); + assert_eq!(node(&s, t2).styles.text.as_deref(), Some(st.as_str())); + // Redefining the style moves its layers' paragraph values with the rest. + let value = json!({"fontSize": 22, "paragraphSpacing": 20, "listStyle": "numbered", "openTypeFeatures": {"tnum": true}}); + run(&mut s, "style.update", json!({"style": st, "value": value})); + let d = td(&s, t2); + assert_eq!((d.paragraph_spacing, d.paragraph_indent, d.para_list(1).list), (20.0, 0.0, ListStyle::Numbered)); + assert_eq!(d.features, BTreeMap::from([("tnum".to_string(), true)])); + assert_eq!(font_size(&s, t2), 22.0); + assert_eq!(node(&s, t2).styles.text.as_deref(), Some(st.as_str()), "still linked after the update"); + // Editing a paragraph value the style sets unlinks the text, as editing its font does. + run(&mut s, "node.set", json!({"id": t2, "props": {"paragraphSpacing": 5}})); + assert_eq!(node(&s, t2).styles.text, None, "paragraph spacing edited: unlinked"); + assert!(td(&s, t2).spans().iter().all(|(_, _, x)| x.style_id.is_none())); + // On a range, the list goes to the paragraphs touched; the spacing is the layer's. Taking + // the paragraph out of the style's list unlinks its chars. + let t3 = text(&mut s, 600.0); + run(&mut s, "node.set", json!({"id": t3, "props": {"characters": "A\nB\nC"}})); + run(&mut s, "style.apply", json!({"ids": [t3], "style": st, "start": 0, "end": 1})); + let d = td(&s, t3); + assert_eq!((d.para_list(0).list, d.para_list(1).list, d.paragraph_spacing), (ListStyle::Numbered, ListStyle::None, 20.0)); + assert_eq!(d.style_at(0).style_id.as_deref(), Some(st.as_str())); + run(&mut s, "node.set", json!({"id": t3, "props": {"start": 0, "end": 1, "listStyle": "none"}})); + assert_eq!(td(&s, t3).style_at(0).style_id, None, "its paragraph left the style's list"); + // A definition given as a value takes the node.set spellings; junk is refused. + let value = json!({"fontSize": 11, "paragraphSpacing": 4, "listStyle": "bulleted", "features": {"liga": false}}); + let st2 = sid(run(&mut s, "style.create", json!({"type": "text", "name": "Note", "value": value}))); + let want = ParagraphStyle { + paragraph_spacing: 4.0, + list: ListStyle::Bulleted, + features: BTreeMap::from([("liga".to_string(), false)]), + ..Default::default() + }; + assert!(matches!(&s.doc().unwrap().style(&st2).unwrap().kind, StyleKind::Text { paragraph, .. } if **paragraph == want)); + assert!(s.execute("style.create", &json!({"type": "text", "name": "Bad", "value": {"listStyle": "dotted"}})).is_err()); + assert!(s.execute("style.create", &json!({"type": "text", "name": "Bad", "value": {"paragraphSpacing": "wide"}})).is_err()); +} + #[test] fn styles_are_organised_by_slash_names_order_and_duplicates() { // Documented: "/" in a name groups styles in folders; moving a style to another folder renames diff --git a/crates/engine/src/text_style_picker_tests.rs b/crates/engine/src/text_style_picker_tests.rs index 6ee8cc2c3..733845a52 100644 --- a/crates/engine/src/text_style_picker_tests.rs +++ b/crates/engine/src/text_style_picker_tests.rs @@ -86,7 +86,7 @@ fn editing_text_applies_to_the_selected_chars() { s.execute("text.style", &json!({"id": t, "start": 6, "end": 11, "fontSize": 20})).unwrap(); let c = s.execute("style.create", &json!({"type": "text", "name": "Type/Caption"})).unwrap()["id"].as_str().unwrap().to_string(); let style = s.doc().unwrap().style(&c).cloned().unwrap(); - let StyleKind::Text { style: def } = style.kind else { panic!("not a text style") }; + let StyleKind::Text { style: def, .. } = style.kind else { panic!("not a text style") }; assert_eq!(def.font_size, 20.0); assert_eq!(def.style_id, None, "definitions link to nothing"); assert_eq!(links(&s, t)[8].as_deref(), Some(c.as_str())); @@ -117,7 +117,7 @@ fn edits_unlink_and_style_edits_follow() { assert_eq!(layer_link(&s, a).as_deref(), Some(h.as_str())); // Redefining the style moves linked chars only. let mut def = match &s.doc().unwrap().style(&h).unwrap().kind { - StyleKind::Text { style } => style.clone(), + StyleKind::Text { style, .. } => style.clone(), _ => panic!("not a text style"), }; def.font_size = 40.0; diff --git a/crates/format/src/fig/assets_tests.rs b/crates/format/src/fig/assets_tests.rs index ce4192008..36c70a687 100644 --- a/crates/format/src/fig/assets_tests.rs +++ b/crates/format/src/fig/assets_tests.rs @@ -225,7 +225,7 @@ fn same_after_round_trip(doc: &Document, what: &str) -> Vec { normalize(&mut n, &|i| i); *paints = n.fills; } - StyleKind::Text { style } => { + StyleKind::Text { style, .. } => { if let NodeKind::Text(td) = &mut n.kind { td.style = style.clone(); } @@ -444,7 +444,7 @@ fn styled() -> Document { bound: Default::default(), }; doc.styles = vec![ - style("s-text", "Heading", StyleKind::Text { style: heading.clone() }), + style("s-text", "Heading", StyleKind::Text { style: heading.clone(), paragraph: Default::default() }), style("s-brand", "Brand/Primary", StyleKind::Paint { paints: vec![solid(0.25, 0.5, 1.0)] }), style("s-unused", "Brand/Unused", StyleKind::Paint { paints: vec![solid(1.0, 0.0, 0.0), solid(0.0, 1.0, 0.0)] }), style("s-shadow", "Elevation/1", StyleKind::Effect { effects: vec![shadow.clone()] }), diff --git a/crates/format/src/fig/export/assets.rs b/crates/format/src/fig/export/assets.rs index 3874b073c..f1df1874d 100644 --- a/crates/format/src/fig/export/assets.rs +++ b/crates/format/src/fig/export/assets.rs @@ -159,7 +159,7 @@ impl<'d> Exporter<'d> { Bound::default() } else { let mut sample = Node::new(NodeId(0), NodeKind::Rectangle, "", 0.0, 0.0); - if let StyleKind::Text { style } = &st.kind { + if let StyleKind::Text { style, .. } = &st.kind { sample.kind = NodeKind::Text(TextData { style: style.as_text_style(), ..TextData::new("Ag") }); } sample.bound.clone_from(&st.bound); @@ -179,8 +179,9 @@ impl<'d> Exporter<'d> { let list = grids.iter().enumerate().map(|(i, g)| layout_grid(g, i, &none)).collect(); f.extend([("fillPaints", arr(Vec::new())), ("layoutGrids", arr(list))]); } - StyleKind::Text { style } => { - let td = TextData { style: style.as_text_style(), ..TextData::new("Ag") }; + StyleKind::Text { style, paragraph } => { + let mut td = TextData { style: style.as_text_style(), ..TextData::new("Ag") }; + td.take_paragraph_style(paragraph); let fills = [Paint::solid(Color::BLACK)]; f.push(("fillPaints", self.paints(style.fills.as_deref().unwrap_or(&fills), true, &none))); self.text(&td, &fills, &mut f); diff --git a/crates/format/src/fig/text_skip_ink_tests.rs b/crates/format/src/fig/text_skip_ink_tests.rs index 485663847..b5285e1b6 100644 --- a/crates/format/src/fig/text_skip_ink_tests.rs +++ b/crates/format/src/fig/text_skip_ink_tests.rs @@ -113,7 +113,7 @@ fn local_skip_ink_override_preserves_shared_style_and_omitted_value_inherits() { let node = doc.nodes().find(|n| n.name == "Label").unwrap(); assert_eq!(node.kind.text().unwrap().style.look().skip_ink, expected); let linked = doc.style(node.styles.text.as_deref().unwrap()).unwrap(); - let StyleKind::Text { style } = &linked.kind else { panic!("linked definition must remain text") }; + let StyleKind::Text { style, .. } = &linked.kind else { panic!("linked definition must remain text") }; assert!(style.look().skip_ink, "local value must not alter definition"); } } @@ -223,7 +223,7 @@ fn export_writes_one_actual_node_value_and_complete_run_values_without_skip_only id: "body".into(), name: "Body".into(), description: String::new(), - kind: StyleKind::Text { style: shared }, + kind: StyleKind::Text { style: shared, paragraph: Default::default() }, bound: Default::default(), }); let id = linked_doc @@ -237,7 +237,7 @@ fn export_writes_one_actual_node_value_and_complete_run_values_without_skip_only let node = back.nodes().find(|n| n.name == "Label").unwrap(); assert!(!node.kind.text().unwrap().style.look().skip_ink); let linked = back.style(node.styles.text.as_deref().unwrap()).unwrap(); - let StyleKind::Text { style } = &linked.kind else { panic!("shared style link must remain text") }; + let StyleKind::Text { style, .. } = &linked.kind else { panic!("shared style link must remain text") }; assert!(style.look().skip_ink, "local false must not alter the shared definition"); } diff --git a/crates/format/src/fig/text_style_tests.rs b/crates/format/src/fig/text_style_tests.rs index 0f08459e6..dadd052c1 100644 --- a/crates/format/src/fig/text_style_tests.rs +++ b/crates/format/src/fig/text_style_tests.rs @@ -85,7 +85,7 @@ fn seen(doc: &Document) -> Seen { assert_eq!((text.style.font_family.as_str(), text.style.font_size), ("Inter", 20.0)); let linked = doc.style(label.styles.text.as_deref().unwrap()).unwrap(); assert_eq!(linked.name, "Shared"); - let StyleKind::Text { style } = &linked.kind else { panic!("the linked definition must stay a text style") }; + let StyleKind::Text { style, .. } = &linked.kind else { panic!("the linked definition must stay a text style") }; Seen { case: text.style.case, decoration: text.style.decoration, diff --git a/crates/format/src/penpot.rs b/crates/format/src/penpot.rs index 6cd8fe53c..a0e50a067 100644 --- a/crates/format/src/penpot.rs +++ b/crates/format/src/penpot.rs @@ -1531,7 +1531,7 @@ fn import_typography_styles( id: format!("penpot:text:{base}:{id}"), name: name.chars().take(256).collect(), description: "Imported from Penpot typography library".into(), - kind: StyleKind::Text { style }, + kind: StyleKind::Text { style, paragraph: Default::default() }, bound: BTreeMap::new(), }); } @@ -1596,7 +1596,7 @@ fn composite_token_style(token: &Value) -> Option { } } let parsed = text_style(&Value::Object(fields), &style); - Some(StyleKind::Text { style: parsed }) + Some(StyleKind::Text { style: parsed, paragraph: Default::default() }) } "boxShadow" | "shadow" => { let parts: Vec<&Value> = if let Some(items) = value.as_array() { items.iter().take(32).collect() } else { vec![value] }; @@ -5927,7 +5927,7 @@ mod tests { let (doc, warnings) = import(&archive_with_design_system(tokens, None, None, None)).unwrap(); assert_eq!(doc.styles.len(), 2); assert!(doc.styles.iter().any(|s| s.name == "Penpot tokens/Core/title" - && matches!(&s.kind, StyleKind::Text { style } + && matches!(&s.kind, StyleKind::Text { style, .. } if style.font_family == "Spicy Rice" && style.font_size == 24.0 && style.line_height == LineHeight::Pixels(32.0)))); assert!(doc.styles.iter().any(|s| s.name == "Penpot tokens/Core/elevation" && matches!(&s.kind, StyleKind::Effect { effects } @@ -5983,10 +5983,8 @@ mod tests { let (doc, warnings) = import(&archive_with_design_system(serde_json::json!({"sets":{}}), Some(typ), Some(color), None)).unwrap(); assert!(warnings.is_empty(), "{warnings:?}"); assert_eq!(doc.styles.len(), 2); - assert!( - doc.styles.iter().any(|s| s.name == "Brand/Heading" - && matches!(&s.kind, StyleKind::Text { style } if style.font_family == "Inter" && style.font_size == 24.0)) - ); + assert!(doc.styles.iter().any(|s| s.name == "Brand/Heading" + && matches!(&s.kind, StyleKind::Text { style, .. } if style.font_family == "Inter" && style.font_size == 24.0))); assert!(doc.styles.iter().any(|s| s.name == "Brand/Primary" && matches!(s.kind, StyleKind::Paint { .. }))); assert_eq!(doc.document_colors.len(), 1); } diff --git a/crates/format/src/rest.rs b/crates/format/src/rest.rs index 4604b73a6..eb9a10112 100644 --- a/crates/format/src/rest.rs +++ b/crates/format/src/rest.rs @@ -913,7 +913,11 @@ impl<'a> Ctx<'a> { Some("FILL") => StyleKind::Paint { paints: props::paints(self, node, "fills").unwrap_or_default() }, Some("EFFECT") => StyleKind::Effect { effects: props::effects(self, node) }, Some("GRID") => StyleKind::Grid { grids: props::layout_grids(node) }, - Some("TEXT") => StyleKind::Text { style: text::text_data(self, node).style.as_text_style() }, + Some("TEXT") => { + // The sample layer carries the paragraph-level values too (#1829). + let td = text::text_data(self, node); + StyleKind::Text { style: td.style.as_text_style(), paragraph: Box::new(td.paragraph_style()) } + } _ => continue, }; let name = text(d, "name").filter(|s| !s.is_empty()).map_or_else(|| format!("Style {id}"), |s| clip_str(s).to_string()); @@ -955,7 +959,9 @@ impl<'a> Ctx<'a> { "effect" | "effects" => (StyleKind::Effect { effects: n.effects.clone() }, &mut n.styles.effect), "grid" | "grids" => (StyleKind::Grid { grids: n.grids.clone() }, &mut n.styles.grid), "text" => match &n.kind { - NodeKind::Text(t) => (StyleKind::Text { style: t.style.as_text_style() }, &mut n.styles.text), + NodeKind::Text(t) => { + (StyleKind::Text { style: t.style.as_text_style(), paragraph: Box::new(t.paragraph_style()) }, &mut n.styles.text) + } _ => continue, }, _ => continue, diff --git a/crates/format/src/rest/tests.rs b/crates/format/src/rest/tests.rs index 050dcbaa6..43c9db6f2 100644 --- a/crates/format/src/rest/tests.rs +++ b/crates/format/src/rest/tests.rs @@ -530,7 +530,7 @@ fn shared_styles_link_with_metadata_names() { let fill = doc.style("S:1").unwrap(); assert_eq!((fill.name.as_str(), fill.description.as_str()), ("Brand/Primary", "Main")); assert!(matches!(&fill.kind, StyleKind::Paint { paints } if paints.len() == 1)); - assert!(matches!(&doc.style("S:2").unwrap().kind, StyleKind::Text { style } if style.font_size == 32.0)); + assert!(matches!(&doc.style("S:2").unwrap().kind, StyleKind::Text { style, .. } if style.font_size == 32.0)); assert!(matches!(&doc.style("Soft").unwrap().kind, StyleKind::Effect { effects } if effects.len() == 1)); let r = named(&doc, "R"); assert_eq!((r.styles.fill.as_deref(), r.styles.effect.as_deref()), (Some("S:1"), Some("S:4"))); diff --git a/crates/format/src/sketch/shared_tests.rs b/crates/format/src/sketch/shared_tests.rs index 240fdb7ea..4636c652e 100644 --- a/crates/format/src/sketch/shared_tests.rs +++ b/crates/format/src/sketch/shared_tests.rs @@ -91,7 +91,7 @@ fn text_style_links() { let sid = n.styles.text.clone().expect("text style linked"); let s = style(&doc, &sid); assert_eq!(s.name, "Heading/H1"); - let StyleKind::Text { style: ts } = &s.kind else { panic!("not a text style") }; + let StyleKind::Text { style: ts, .. } = &s.kind else { panic!("not a text style") }; assert_eq!((ts.font_family.as_str(), ts.font_style.as_str(), ts.font_size), ("Helvetica", "Bold", 32.0)); assert!(n.fills.iter().any(|p| matches!(p.kind, PaintKind::Solid { color } if color.r == 1.0 && color.g == 0.0))); } diff --git a/crates/ui-egui/src/widgets/style_picker.rs b/crates/ui-egui/src/widgets/style_picker.rs index eb2a2b44b..f616ddec7 100644 --- a/crates/ui-egui/src/widgets/style_picker.rs +++ b/crates/ui-egui/src/widgets/style_picker.rs @@ -10,7 +10,9 @@ use egui::{Align2, Color32, CornerRadius, Id, Rect, Response, Sense, Stroke, Ui, pos2, vec2}; use figcraft_color::{Paint, PaintKind}; -use figcraft_doc::{Document, GridKind, Node, NodeId, PublishedLibrary, Style, StyleKind, TextStyle, VariableType, trim_num}; +use figcraft_doc::{ + Document, GridKind, ListStyle, Node, NodeId, ParagraphStyle, PublishedLibrary, Style, StyleKind, TextStyle, VariableType, trim_num, +}; use figcraft_engine::library; use serde_json::{Value, json}; @@ -354,7 +356,7 @@ fn by_folder<'a>(styles: impl Iterator) -> Vec<(&'a str, Vec<& /// A text style's definition, if `s` is one. fn text_def(s: &Style) -> Option<&TextStyle> { match &s.kind { - StyleKind::Text { style } => Some(style), + StyleKind::Text { style, .. } => Some(style), _ => None, } } @@ -974,6 +976,39 @@ fn text_properties(ui: &mut Ui, doc: &Document, style: &Style, def: &TextStyle, if let Some(sr) = style_resp { font_style_menu(id, def, &sr, out); } + if let StyleKind::Text { paragraph, .. } = &style.kind { + paragraph_rows(ui, paragraph); + } +} + +/// What a text style sets at the paragraph level (#1829), when it sets anything: the spacing, +/// indent, list style and OpenType features (as `+tnum -liga`). A layer's Type settings edit +/// them; Update from selection takes them into the style. +fn paragraph_rows(ui: &mut Ui, ps: &ParagraphStyle) { + let mut rows: Vec = Vec::new(); + if ps.paragraph_spacing != 0.0 { + let label = tr("Paragraph spacing"); + rows.push(format!("{label}: {}", trim_num(ps.paragraph_spacing))); + } + if ps.paragraph_indent != 0.0 { + let label = tr("Paragraph indent"); + rows.push(format!("{label}: {}", trim_num(ps.paragraph_indent))); + } + match ps.list { + ListStyle::None => {} + ListStyle::Bulleted => rows.push(tr("Bulleted list").into()), + ListStyle::Numbered => rows.push(tr("Numbered list").into()), + } + if !ps.features.is_empty() { + rows.push(ps.features.iter().map(|(tag, on)| format!("{}{tag}", if *on { '+' } else { '-' })).collect::>().join(" ")); + } + if rows.is_empty() { + return; + } + ui.add_space(4.0); + for row in rows { + caption(ui, &row); + } } /// Editing one style: name, description, its values (paints open the colour picker; text styles @@ -1038,7 +1073,7 @@ fn editor(ui: &mut Ui, doc: &Document, p: &mut Picker, out: &mut Frame) { binding_cell(ui, doc, &style, &format!("layoutGrids/{i}/size"), figcraft_doc::VariableType::Number, out); } } - StyleKind::Text { style: def } => text_properties(ui, doc, &style, def, out), + StyleKind::Text { style: def, .. } => text_properties(ui, doc, &style, def, out), } }); ui.add_space(8.0); diff --git a/crates/ui-egui/src/widgets/style_picker/tests.rs b/crates/ui-egui/src/widgets/style_picker/tests.rs index fa996374c..0f3392e48 100644 --- a/crates/ui-egui/src/widgets/style_picker/tests.rs +++ b/crates/ui-egui/src/widgets/style_picker/tests.rs @@ -29,7 +29,7 @@ fn names_split_into_folders() { for s in [StyleSlot::Fill, StyleSlot::Stroke, StyleSlot::Effect, StyleSlot::Grid, StyleSlot::Text] { assert_eq!(StyleSlot::parse(s.key()), Some(s)); } - assert!(StyleSlot::Text.holds(&StyleKind::Text { style: Default::default() }) && StyleSlot::Text.has_grid()); + assert!(StyleSlot::Text.holds(&StyleKind::Text { style: Default::default(), paragraph: Default::default() }) && StyleSlot::Text.has_grid()); } fn frame(ctx: &egui::Context, app: &mut FigApp, t: &mut f64) { @@ -255,7 +255,7 @@ fn commit_text_field(def: &TextStyle, field: &str, typed: &str) -> Option = texts.iter().filter(|(_, p)| p.x > left && p.x < left + W).cloned().collect(); @@ -434,7 +434,7 @@ fn text_style_editor_binds_variables_from_its_fields() { assert_eq!(bound_to(&u, field).as_deref(), Some(name)); } let doc = u.app.session.doc().unwrap(); - let Some(StyleKind::Text { style: def }) = doc.style("Body").map(|s| &s.kind) else { panic!("a text style") }; + let Some(StyleKind::Text { style: def, .. }) = doc.style("Body").map(|s| &s.kind) else { panic!("a text style") }; assert_eq!((def.font_size, def.font_style.as_str()), (18.0, "Bold"), "the style takes the variables' values"); assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); } diff --git a/docs/components-parity.md b/docs/components-parity.md index 0e3248248..7fce63d14 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -1,6 +1,6 @@ # Components, variants, styles and variables parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) Design systems are why teams adopt Figma. **Components: breadth ~96%, ready ~72%. Styles and variables: breadth ~95%, ready ~76% (estimated).** QA'd with a synthetic design system of ~300 @@ -59,7 +59,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Feature | Status | Notes | |---|---|---| -| Paint, text, effect, grid styles; style picker; text styles on character ranges | done | behaviour suite: `styles_behaviour_tests.rs` | +| Paint, text, effect, grid styles; style picker; text styles on character ranges | done | behaviour suite: `styles_behaviour_tests.rs`; a text style carries paragraph spacing and indent, the list style and the OpenType features beside the character properties (`paragraph` next to `style` in `style.list`): applied with it, moved by `style.update`, unlinking when edited, kept by `.fig` files (#1829) | | Editing a style updates its layers; detach and delete keep values; editing a styled property unlinks that style | done | an edited fill/stroke/effect/grid list or text chars unlink; applying a style replaces variables bound to what it sets; text styles on text layers only | | Organising styles: folders by `/` names, order, duplicate, rename folder, Local styles list | done | `style.move` (into a folder renames), `style.duplicate` (right below), `style.renameFolder`; the page's Local styles list by type and folder (drag to reorder, right-click) | | Variables inside styles (paint, effect, grid and text styles; each user resolves them in its own modes) | done | `style.bind`, `style_vars_tests`; the editor binds paint colours, shadow colours, blur radii, grid sizes and a text style's font, font style, size, line height and letter spacing, the rest through the command | @@ -78,6 +78,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | M3, #1829: text styles carry paragraph spacing and indent, the list style and the OpenType features ("Supported in text styles": "Paragraph spacing and indentation", "Lists", "OpenType features", Create and apply text styles) beside the character properties: `style.create` takes them from the layer (or the selected paragraphs' list) or from a `value` (`paragraphSpacing`, `paragraphIndent`, `listStyle`, `features`), `style.apply` sets them (on a range, the list goes to the paragraphs touched; the rest is the layer's, as in Figma), `style.update` moves them on every linked layer, editing one on a styled text unlinks it as editing its font does, the style editor lists them, and a `.fig` file keeps them with the style (its sample layer). Grade unchanged. | | 2026-11-01 | patch | M3: Delete on a layer inside an instance hides it (an override) instead of being refused ("You can't delete a layer or object from an instance. If you try, Figma will only toggle the layer's visibility instead of removing it", Guide to auto layout); `edit.delete` reports those ids under `hidden`, the structure and the main component stay as they were, one undo step; deleting the instance itself still removes it. Found by a documentation audit of the auto layout page. Test: `components_behaviour_tests::deleting_a_layer_inside_an_instance_hides_it_instead` (the refusal row for it is gone from `what_instances_cannot_override_is_refused`). Numbers unchanged | | 2026-10-31 | minor | M3, gap 10: library analytics cover styles and variables. A file reports how many of its layers use each of a library's styles and variables, and Show usage (`library.usage`) lists them beside the components, by a Type choice, with their layers and files. Layers inside instances count for their component. Insertions, detachments and modes aren't counted for them yet. Numbers unchanged. Tests: `library_assets_tests`. | | 2026-10-31 | minor | M6: as the help center describes code syntax, Dev Mode's SwiftUI and Compose code now writes a bound variable's iOS or Android code syntax in place of its value, as CSS already wrote the Web one: fills, strokes and their weight, sizes, corner radius, gaps, padding, opacity, the font family and size and the characters. A variable with no code syntax for the platform keeps the value, since a name made up here wouldn't exist in the code it lands in. ArkUI and Flutter have no code syntax platform and are unchanged. Test: `variables_behaviour_tests::swiftui_and_compose_name_variables_by_their_code_syntax`. Numbers unchanged. Grade unchanged | diff --git a/docs/mcp.md b/docs/mcp.md index b5e49e749..8344f4972 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -312,10 +312,16 @@ Or in a project's `.mcp.json`: `style.detach {which: "text", start?, end?}` unlinks them (values stay). A layer's `styles.text` is the style all its chars share (none when they differ); `get_node` lists the linked chars as `textStyleRanges` (`[start, end, style id]`). + A text style also carries paragraph spacing and indent, the list style and the OpenType features + (`paragraph` beside `style` in `style.list`): applying it sets them (on a range, the list goes to + the paragraphs touched; the rest is the layer's), `style.update` moves them too, and a `.fig` + file keeps them with the style. Changing what a text style sets (font, size, line height, letter spacing, decoration, case, axis - values) on linked chars unlinks them; `style.update` moves every linked char. `style.create - {type: "text", name}` takes the selected chars while editing; a `value` may use the `node.set` - spellings (`{"fontSize": 32, "lineHeight": "120%", "letterSpacing": "2%"}`). + values; at the paragraph level the spacing, indent, list and features) on linked chars unlinks + them; `style.update` moves every linked char. `style.create {type: "text", name}` takes the + selected chars while editing; a `value` may use the `node.set` spellings (`{"fontSize": 32, + "lineHeight": "120%", "letterSpacing": "2%", "paragraphSpacing": 12, "listStyle": "bulleted", + "features": {"liga": false}}`). - **Styles stay true to their layers**: editing a styled fill, stroke, effect or layout grid list (`node.set`, `fill.set`, `fill.add`, a bound variable…) unlinks that style (`styles.fill` etc. go `null`), so a later `style.update` doesn't overwrite the edit; `style.apply` replaces variables From e5a3fcf02820d4e6cdcb4925e73cb3b0f167eb29 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 07:01:04 -0500 Subject: [PATCH 023/102] Merge fix: text_link_tests is a test module The merge's union of two mod lines left upstream's text_link_tests without its cfg(test), so the library build pulled a test module in. Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 20e5847b0..b1daf85ec 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -242,6 +242,7 @@ mod style_props_tests; mod table_paste_tests; #[cfg(test)] mod text_enter_tests; +#[cfg(test)] mod text_link_tests; #[cfg(test)] mod text_mixed_fill_tests; From 90bec33322d3a33e004a5f632b3dde8d914d684e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 07:23:33 -0500 Subject: [PATCH 024/102] Crosshair: the board Shapes tool places on it, and the view pans to keep it in sight draws_shape includes BoardShape (tool.place lets the tool centre its own shape); a nudge past an edge of the view pans by the overshoot. Tests; docs. Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/canvas/tools.rs | 1 + crates/engine/src/canvas/tools/keys.rs | 3 +- crates/engine/src/cmd/view.rs | 10 ++++-- crates/engine/src/place_crosshair_tests.rs | 40 ++++++++++++++++++++++ docs/ui-parity.md | 2 +- 5 files changed, 52 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index 9bc4bef2a..788e5eb8e 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -201,6 +201,7 @@ impl ToolId { | ToolId::Star | ToolId::Line | ToolId::Arrow + | ToolId::BoardShape ) } } diff --git a/crates/engine/src/canvas/tools/keys.rs b/crates/engine/src/canvas/tools/keys.rs index 07a91557b..2b56aecd3 100644 --- a/crates/engine/src/canvas/tools/keys.rs +++ b/crates/engine/src/canvas/tools/keys.rs @@ -90,7 +90,8 @@ impl Session { self.tool.place_at = None; let v = &self.ds()?.view; let (c, zoom) = (at.or(crosshair).unwrap_or(Point::new(v.cx, v.cy)), v.zoom); - let (w, h) = tool.click_size(); + // The board Shapes tool centres its own shape on the press; the others get half a click's size. + let (w, h) = if matches!(tool, ToolId::BoardShape) { (0.0, 0.0) } else { tool.click_size() }; let ev = |kind| PointerEvent::at(kind, c.x - w / 2.0, c.y - h / 2.0, zoom); let r = self.pointer(&ev(PointerKind::Down)).and_then(|()| self.pointer(&ev(PointerKind::Up))); if r.is_err() { diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 583d46ba6..305db5399 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -541,9 +541,10 @@ pub fn specs() -> Vec { let step = if boolean(p, "big").unwrap_or(false) { s.prefs.nudge_big } else { s.prefs.nudge_small }; let dir = |k| num(p, k).filter(|v| v.is_finite()).unwrap_or(0.0).clamp(-100.0, 100.0) * step; let (dx, dy) = (dir("dx"), dir("dy")); - let (uid, page, centre) = { + let (uid, page, centre, half) = { let ds = s.ds()?; - (ds.uid, ds.page, figcraft_geom::Point::new(ds.view.cx, ds.view.cy)) + let z = ds.view.zoom.max(1e-6); + (ds.uid, ds.page, figcraft_geom::Point::new(ds.view.cx, ds.view.cy), (ds.view.vw / z / 2.0, ds.view.vh / z / 2.0)) }; // "It will appear in the middle of the viewport": the first arrow shows it there (a // crosshair left on another page or document starts over). @@ -554,6 +555,11 @@ pub fn specs() -> Vec { s.tool.place_at = Some(at); s.tool.place_on = Some((uid, page)); if let Ok(ds) = s.ds_mut() { + // "Move the crosshair around the canvas": nudged past an edge of the view, the + // view pans by the overshoot to keep it in sight. + let v = &mut ds.view; + v.cx += (at.x - (v.cx + half.0)).max(0.0) + (at.x - (v.cx - half.0)).min(0.0); + v.cy += (at.y - (v.cy + half.1)).max(0.0) + (at.y - (v.cy - half.1)).min(0.0); ds.revision += 1; } Ok(json!({"x": at.x, "y": at.y})) diff --git a/crates/engine/src/place_crosshair_tests.rs b/crates/engine/src/place_crosshair_tests.rs index 9bd89dc90..6b5f7b732 100644 --- a/crates/engine/src/place_crosshair_tests.rs +++ b/crates/engine/src/place_crosshair_tests.rs @@ -80,3 +80,43 @@ fn the_crosshair_keeps_its_page_and_goes_with_a_pointer_placement_but_not_the_sa let v = &s.ds().unwrap().view; assert_eq!((r["x"].as_f64(), r["y"].as_f64()), (Some(v.cx), Some(v.cy)), "shown afresh in the middle of this page's view"); } + +#[test] +fn the_view_pans_to_keep_the_crosshair_in_sight() { + // "Use the arrow keys to move the crosshair around the canvas or board": nudged past an edge + // of the view, the view follows it by the overshoot; inside it, the view stays put. + let mut s = Session::new(); + s.execute("view.set", &json!({"zoom": 10.0, "cx": 300, "cy": 200})).unwrap(); + s.execute("tool.rectangle", &json!({})).unwrap(); + s.execute("tool.crosshair", &json!({})).unwrap(); + for _ in 0..6 { + s.execute("tool.crosshair", &json!({"dx": 1, "big": true})).unwrap(); + } + let v = s.ds().unwrap().view.clone(); + assert_eq!((s.tool.place_at.map(|p| p.x), v.cx, v.cy), (Some(360.0), 300.0, 200.0), "at the edge of the 120 px wide view: no pan yet"); + s.execute("tool.crosshair", &json!({"dx": 1, "big": true})).unwrap(); + let v = s.ds().unwrap().view.clone(); + assert_eq!((v.cx, v.cy), (310.0, 200.0), "ten past the edge: the view moved ten"); + for _ in 0..5 { + s.execute("tool.crosshair", &json!({"dy": -1, "big": true})).unwrap(); + } + let v = s.ds().unwrap().view.clone(); + assert_eq!((v.cx, v.cy), (310.0, 190.0), "the view is 80 px tall: 40 up is its edge, 50 moves it ten"); +} + +#[test] +fn the_board_shapes_tool_places_on_the_crosshair_too() { + // "...move the crosshair around the canvas or board, then press Return/Enter to place the + // object": the board Shapes tool takes the crosshair like the shape tools, its shape centred + // on it (the tool centres its own 160 px shape on a press). + let mut s = crate::board_tests::board(); + s.execute("view.set", &json!({"zoom": 1.0, "cx": 300, "cy": 200})).unwrap(); + s.execute("tool.set", &json!({"tool": "shape"})).unwrap(); + s.execute("tool.crosshair", &json!({})).unwrap(); + s.execute("tool.crosshair", &json!({"dx": 2})).unwrap(); + let placed = s.execute("tool.place", &json!({})).unwrap(); + let id = crate::params::id_of(&placed["ids"][0]).unwrap(); + let b = s.doc().unwrap().world_bounds(id).unwrap(); + assert_eq!((b.center().x, b.center().y, b.width(), b.height()), (302.0, 200.0, 160.0, 160.0)); + assert_eq!(s.tool.place_at, None); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 0fde4bcd2..a7185146b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -177,7 +177,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| -| 2026-11-02 | patch | M6, #1839: with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it by the nudge amounts (`tool.crosshair`), Enter places the object there (`tool.place`), Escape or a tool change takes it away; the canvas draws the crosshair and `ui.inspect` reports it (`tool.crosshair`), the Keyboard shortcuts panel lists the gesture ("Use the arrow keys to activate the crosshair cursor...", Accessibility at Figma). Tests: `place_crosshair_tests`, `shortcut_keys_tests::arrows_show_and_move_the_placement_crosshair_with_a_shape_tool`. | +| 2026-11-02 | patch | M6, #1839: with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it by the nudge amounts (`tool.crosshair`), Enter places the object there (`tool.place`), Escape or a tool change takes it away; the canvas draws the crosshair and `ui.inspect` reports it (`tool.crosshair`), the Keyboard shortcuts panel lists the gesture ("Use the arrow keys to activate the crosshair cursor...", Accessibility at Figma). The board Shapes tool places on it too (its 160 px shape centred, as the tool centres a press), and the view pans by the overshoot when the crosshair is nudged past its edge. Tests: `place_crosshair_tests`, `shortcut_keys_tests::arrows_show_and_move_the_placement_crosshair_with_a_shape_tool`. | | 2026-11-02 | patch | M4: Backspace or Delete at the start of a list item takes its marker and keeps its level ("Use Backspace or Delete at the beginning of a list item to delete the counter, but keep the same level of indentation", Create bulleted and numbered lists): a plain paragraph may now carry a list level, and the text layout starts it where that level's item text starts (the gutters stay even when no list is left). Backspace used to drop the level too, and Delete at an item's start deleted the next character. Tab on such a paragraph types a tab, as outside a list. Tests: `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests::a_plain_paragraph_at_a_list_level_starts_where_the_items_text_does` | | 2026-11-02 | patch | M4: max lines on an auto-width text keep it auto width: the box hugs up to that many lines and still grows with its longest line ("Max lines is available only if truncate text is enabled, and: Text resizing is set to auto height or auto width", Explore text properties). `text.maxLines` turned such a text into a fixed truncating box with a stale height, so later typing no longer widened it; fixed-size text still becomes a truncating box, auto-height text hugs as before. Test: `text_behaviour_tests::max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines` | | 2026-11-02 | patch | M4, #1828: superscript and subscript synthesised where the font has no `sups` / `subs` glyphs (the standard glyph shrunk and shifted by the OS/2 metrics, the usual 0.65 em and 0.35 / 0.14 em offsets without them), and a run mixing available and unavailable glyphs synthesised whole, as Explore text properties says. Tests: `text::tests::superscript_native_or_synthesised_and_never_mixed`, `text_behaviour_tests::superscript_and_subscript_are_synthesised_without_glyphs_for_them`. | From 6365e4339b4d4cf5754111715e2ea4e4eee74b9d Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:32:37 +0100 Subject: [PATCH 025/102] M4: Increase and decrease font weight step through the styles the family has (#1831) text.weightUp/weightDown stepped the CSS weight by 100 and stored a canonical name ("Medium", "Semi Bold", ...) whether the family had that face or not, so the first press on Arial Regular changed nothing visible and the stored style named a face no font provides. They now move to the nearest heavier or lighter style of the family with the same slant and width (Narrow stays Narrow), and stay put at either end. A family that isn't installed keeps the old 100 steps. --- crates/engine/src/cmd/text.rs | 65 ++++++++++++++++- crates/engine/src/lib.rs | 2 + crates/engine/src/text_weight_step_tests.rs | 81 +++++++++++++++++++++ 3 files changed, 145 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/text_weight_step_tests.rs diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index f72f215ee..c2b9043c3 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -122,11 +122,70 @@ fn toggle_italic(s: &mut Session, p: &Value) -> Result { }) } +/// What a style name says besides its weight and slant ("Narrow Bold Italic" → "narrow"). +fn style_rest(style: &str) -> String { + const WORDS: [&str; 25] = [ + "thin", + "hairline", + "extralight", + "ultralight", + "light", + "regular", + "normal", + "roman", + "book", + "medium", + "semibold", + "demibold", + "bold", + "extrabold", + "ultrabold", + "black", + "heavy", + "semi", + "demi", + "extra", + "ultra", + "italic", + "oblique", + "plain", + "standard", + ]; + let s = style.to_ascii_lowercase().replace('-', " "); + let words = s.split_whitespace().filter(|w| !WORDS.contains(w) && !w.chars().all(|c| c.is_ascii_digit())); + words.collect::>().join(" ") +} + +fn slanted(style: &str) -> bool { + let s = style.to_ascii_lowercase(); + s.contains("italic") || s.contains("oblique") +} + +/// The next heavier (`up`) or lighter style of `styles` (a family's) after the chars' style: the +/// nearest weight with the same slant and width, as the style menu lists them. None when the family +/// has nothing further that way. +pub(crate) fn next_style(styles: &[String], st: &TextStyle, up: bool) -> Option { + let (w, italic, rest) = (i32::from(st.weight()), st.italic(), style_rest(&st.font_style)); + styles + .iter() + .filter(|x| slanted(x) == italic && style_rest(x) == rest) + .map(|x| (i32::from(figcraft_doc::style_weight(x)) - w, x)) + .filter(|(d, _)| if up { *d > 0 } else { *d < 0 }) + .min_by_key(|(d, _)| d.abs()) + .map(|(_, x)| x.clone()) +} + fn step_weight(s: &mut Session, p: &Value, up: bool) -> Result { style(s, p, |st| { - let w = (i32::from(st.weight()) + if up { 100 } else { -100 }).clamp(100, 900) as u16; - let italic = st.italic(); - st.set_font_style(styled_name(weight_name(w), italic)); + let styles = figcraft_text::family_styles(&st.font_family); + if styles.is_empty() { + // A family that isn't installed: step the weight by 100 under its canonical name. + let w = (i32::from(st.weight()) + if up { 100 } else { -100 }).clamp(100, 900) as u16; + let italic = st.italic(); + st.set_font_style(styled_name(weight_name(w), italic)); + } else if let Some(next) = next_style(&styles, st, up) { + st.set_font_style(next); + } }) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e919444e2..621fdd8cb 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -575,6 +575,8 @@ mod text_style_picker_tests; #[cfg(test)] mod text_tail_tests; #[cfg(test)] +mod text_weight_step_tests; +#[cfg(test)] mod textfit_tests; #[cfg(test)] mod theme_pages_tests; diff --git a/crates/engine/src/text_weight_step_tests.rs b/crates/engine/src/text_weight_step_tests.rs new file mode 100644 index 000000000..f3f7fa587 --- /dev/null +++ b/crates/engine/src/text_weight_step_tests.rs @@ -0,0 +1,81 @@ +//! Increase and decrease font weight step through the styles the family has, by weight with the +//! same slant and width (#1831), not by 100 to a canonical name no face provides. + +use figcraft_doc::{NodeId, TextStyle}; +use serde_json::json; + +use crate::Session; +use crate::cmd::text::next_style; + +fn styles(names: &[&str]) -> Vec { + names.iter().map(|s| (*s).to_string()).collect() +} + +fn at(style: &str) -> TextStyle { + let mut st = TextStyle::default(); + st.set_font_style(style); + st +} + +/// Walk `from` heavier (`up`) or lighter until the family has nothing further. +fn walk(family: &[String], from: &str, up: bool) -> Vec { + let mut st = at(from); + let mut out = Vec::new(); + while let Some(next) = next_style(family, &st, up) { + st.set_font_style(next.clone()); + out.push(next); + } + out +} + +#[test] +fn the_steps_follow_the_family_with_the_same_slant_and_width() { + let arial = styles(&["Narrow", "Regular", "Italic", "Narrow Italic", "Bold", "Narrow Bold", "Bold Italic", "Narrow Bold Italic", "Black"]); + assert_eq!(walk(&arial, "Regular", true), ["Bold", "Black"]); + assert_eq!(walk(&arial, "Black", false), ["Bold", "Regular"]); + assert_eq!(walk(&arial, "Italic", true), ["Bold Italic"]); + assert_eq!(walk(&arial, "Narrow", true), ["Narrow Bold"]); + assert_eq!(walk(&arial, "Narrow Bold Italic", false), ["Narrow Italic"]); + let segoe = styles(&["Light", "Semilight", "Regular", "Italic", "Semibold", "Bold", "Black", "Bold Italic"]); + assert_eq!(walk(&segoe, "Regular", true), ["Semibold", "Bold", "Black"]); + assert_eq!(walk(&segoe, "Regular", false), ["Light"]); + // A style the family doesn't have (as the old steps stored) moves to the next real one. + assert_eq!(next_style(&segoe, &at("Medium"), true).as_deref(), Some("Semibold")); +} + +#[test] +fn a_custom_weight_axis_value_steps_from_where_it_is() { + let family = styles(&["Light", "Regular", "Medium", "Bold"]); + let mut st = at("Regular"); + st.variations.insert("wght".into(), 550.0); + assert_eq!(next_style(&family, &st, true).as_deref(), Some("Bold")); + assert_eq!(next_style(&family, &st, false).as_deref(), Some("Medium")); +} + +fn font_style(s: &Session, t: NodeId) -> String { + s.doc().unwrap().node(t).unwrap().kind.text().unwrap().spans()[0].2.font_style.clone() +} + +#[test] +fn the_commands_land_on_styles_the_family_has() { + figcraft_text::scan_system_fonts(); + // Any installed family with a regular face and a heavier upright one (CI machines differ). + let upright = |x: &String| !x.to_lowercase().contains("italic") && !x.to_lowercase().contains("oblique"); + let pick = figcraft_text::family_names().into_iter().find_map(|f| { + let st = figcraft_text::family_styles(&f); + (st.iter().any(|x| x == "Regular") && st.iter().any(|x| upright(x) && figcraft_doc::style_weight(x) > 400)).then_some((f, st)) + }); + let Some((family, styles)) = pick else { return }; + let mut s = Session::new(); + let r = s.execute("node.create", &json!({"type": "text", "text": "Hi", "props": {"fontFamily": family, "fontStyle": "Regular"}})).unwrap(); + let t = crate::params::id_of(&r["id"]).unwrap(); + s.execute("text.weightUp", &json!({"ids": [t]})).unwrap(); + let up = font_style(&s, t); + assert!(styles.contains(&up) && figcraft_doc::style_weight(&up) > 400, "{family}: {up} of {styles:?}"); + s.execute("text.weightDown", &json!({"ids": [t]})).unwrap(); + assert_eq!(font_style(&s, t), "Regular", "{family}: {styles:?}"); + // A family that isn't installed still steps by 100 under the canonical names. + s.execute("node.set", &json!({"ids": [t], "props": {"fontFamily": "No Such Family 7f3a", "fontStyle": "Regular"}})).unwrap(); + s.execute("text.weightUp", &json!({"ids": [t]})).unwrap(); + assert_eq!(font_style(&s, t), "Medium"); +} From dc82e6cac9b3ab2055dd294fa015fb9072d8f26e Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:49:00 +0100 Subject: [PATCH 026/102] M4: weight steps follow the family's order and keep widths and oblique slants (#1831) Review follow-up. The step now finds the chars' style in the family's list (the style menu's order, lightest first) and takes its neighbour, so a style whose name gives no distinct weight (Semilight) is reachable; a style the family lacks or a custom wght value still goes by weight, ties going to the nearer one in that order. "Extra", "Ultra", "Semi" and "Demi" are weight words only before a weight ("Extra Bold"), so "Extra Condensed" keeps its width; Oblique names count as slanted for the current style too; W3-style names are weights; and style_weight reads Hairline as 100, not 400. The installed-font test picks a family the step actually moves. --- crates/doc/src/tests.rs | 1 + crates/doc/src/text.rs | 3 +- crates/engine/src/cmd/text.rs | 65 ++++++++++++++++----- crates/engine/src/text_weight_step_tests.rs | 40 +++++++++++-- 4 files changed, 86 insertions(+), 23 deletions(-) diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index a0e3e17b0..0964f2e46 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -223,6 +223,7 @@ fn text_case() { assert_eq!(style_weight("Semi Bold Italic"), 600); assert_eq!(style_weight("Black"), 900); assert_eq!(style_weight("Regular"), 400); + assert_eq!(style_weight("Hairline"), 100); } #[test] diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 0c41d3c9a..a0850ec83 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -389,8 +389,9 @@ pub fn style_weight(style: &str) -> u16 { { return n; } - let table: [(&str, u16); 10] = [ + let table: [(&str, u16); 11] = [ ("thin", 100), + ("hairline", 100), ("extralight", 200), ("ultralight", 200), ("light", 300), diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index c2b9043c3..31008533a 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -122,14 +122,23 @@ fn toggle_italic(s: &mut Session, p: &Value) -> Result { }) } -/// What a style name says besides its weight and slant ("Narrow Bold Italic" → "narrow"). +/// Hiragino's weight names: "W3" is 300. +fn w_number(word: &str) -> Option { + let n = word.strip_prefix('w')?.parse::().ok()?; + (1..=9).contains(&n).then_some(n * 100) +} + +/// What a style name says besides its weight and slant ("Narrow Bold Italic" → "narrow", +/// "Extra Condensed Bold" → "extra condensed"). fn style_rest(style: &str) -> String { - const WORDS: [&str; 25] = [ + const WEIGHTS: [&str; 25] = [ "thin", "hairline", "extralight", "ultralight", "light", + "semilight", + "demilight", "regular", "normal", "roman", @@ -141,40 +150,64 @@ fn style_rest(style: &str) -> String { "extrabold", "ultrabold", "black", + "extrablack", + "ultrablack", "heavy", - "semi", - "demi", - "extra", - "ultra", "italic", "oblique", "plain", "standard", ]; + // Words that grade the weight word after them ("Extra Bold") but a width otherwise ("Extra Condensed"). + const GRADES: [&str; 4] = ["extra", "ultra", "semi", "demi"]; let s = style.to_ascii_lowercase().replace('-', " "); - let words = s.split_whitespace().filter(|w| !WORDS.contains(w) && !w.chars().all(|c| c.is_ascii_digit())); - words.collect::>().join(" ") + let words: Vec<&str> = s.split_whitespace().collect(); + let weight = |w: &str| WEIGHTS.contains(&w) || w_number(w).is_some() || w.chars().all(|c| c.is_ascii_digit()); + let rest = words.iter().enumerate().filter(|(i, w)| { + let graded = GRADES.contains(w) && words.get(i + 1).is_some_and(|next| weight(next) && !matches!(*next, "italic" | "oblique")); + !weight(w) && !graded + }); + rest.map(|(_, w)| *w).collect::>().join(" ") } +/// A style name that slants: italic, or oblique as some families name it. fn slanted(style: &str) -> bool { let s = style.to_ascii_lowercase(); s.contains("italic") || s.contains("oblique") } -/// The next heavier (`up`) or lighter style of `styles` (a family's) after the chars' style: the -/// nearest weight with the same slant and width, as the style menu lists them. None when the family -/// has nothing further that way. +/// The weight a style name says ("W3" too). +fn name_weight(style: &str) -> u16 { + w_number(&style.to_ascii_lowercase()).unwrap_or_else(|| figcraft_doc::style_weight(style)) +} + +/// The next heavier (`up`) or lighter style of `styles` (a family's, lightest first, as the style +/// menu lists them) after the chars' style, with the same slant and width. The chars' style is +/// found in the list by name and its neighbour taken; a style the family doesn't have, or a custom +/// weight axis value, goes to the nearest weight that way. None when the family has nothing further. pub(crate) fn next_style(styles: &[String], st: &TextStyle, up: bool) -> Option { - let (w, italic, rest) = (i32::from(st.weight()), st.italic(), style_rest(&st.font_style)); - styles - .iter() - .filter(|x| slanted(x) == italic && style_rest(x) == rest) - .map(|x| (i32::from(figcraft_doc::style_weight(x)) - w, x)) + let italic = st.italic() || slanted(&st.font_style); + let rest = style_rest(&st.font_style); + let mut same: Vec<&String> = styles.iter().filter(|x| slanted(x) == italic && style_rest(x) == rest).collect(); + let norm = |s: &str| s.to_lowercase().replace([' ', '-', '_'], ""); + let here = same.iter().position(|x| norm(x) == norm(&st.font_style)); + if let Some(i) = here.filter(|_| !st.variations.contains_key("wght")) { + let next = if up { i.checked_add(1) } else { i.checked_sub(1) }; + return next.and_then(|n| same.get(n)).map(|x| (*x).clone()); + } + let w = i32::from(st.weight()); + // Of equal weights, the one nearest in the family's order: the first going up, the last going down. + if !up { + same.reverse(); + } + same.into_iter() + .map(|x| (i32::from(name_weight(x)) - w, x)) .filter(|(d, _)| if up { *d > 0 } else { *d < 0 }) .min_by_key(|(d, _)| d.abs()) .map(|(_, x)| x.clone()) } +/// `text.weightUp` / `text.weightDown`: each targeted run moves to the next style of its family. fn step_weight(s: &mut Session, p: &Value, up: bool) -> Result { style(s, p, |st| { let styles = figcraft_text::family_styles(&st.font_family); diff --git a/crates/engine/src/text_weight_step_tests.rs b/crates/engine/src/text_weight_step_tests.rs index f3f7fa587..f3647d77d 100644 --- a/crates/engine/src/text_weight_step_tests.rs +++ b/crates/engine/src/text_weight_step_tests.rs @@ -38,11 +38,39 @@ fn the_steps_follow_the_family_with_the_same_slant_and_width() { assert_eq!(walk(&arial, "Narrow Bold Italic", false), ["Narrow Italic"]); let segoe = styles(&["Light", "Semilight", "Regular", "Italic", "Semibold", "Bold", "Black", "Bold Italic"]); assert_eq!(walk(&segoe, "Regular", true), ["Semibold", "Bold", "Black"]); - assert_eq!(walk(&segoe, "Regular", false), ["Light"]); + assert_eq!(walk(&segoe, "Regular", false), ["Semilight", "Light"]); // A style the family doesn't have (as the old steps stored) moves to the next real one. assert_eq!(next_style(&segoe, &at("Medium"), true).as_deref(), Some("Semibold")); } +#[test] +fn extra_and_semi_before_a_width_keep_the_width() { + let family = styles(&["Extra Condensed Regular", "Condensed Regular", "Condensed Bold", "Extra Condensed Bold", "Semi Condensed Extra Bold"]); + assert_eq!(walk(&family, "Extra Condensed Regular", true), ["Extra Condensed Bold"]); + assert_eq!(walk(&family, "Condensed Bold", false), ["Condensed Regular"]); + assert_eq!(walk(&family, "Semi Condensed Extra Bold", false), Vec::::new()); +} + +#[test] +fn oblique_names_step_to_oblique_faces() { + let dejavu = styles(&["Book", "Oblique", "Bold", "Bold Oblique"]); + assert_eq!(walk(&dejavu, "Oblique", true), ["Bold Oblique"]); + assert_eq!(walk(&dejavu, "Bold Oblique", false), ["Oblique"]); + assert_eq!(walk(&dejavu, "Book", true), ["Bold"]); +} + +#[test] +fn hairline_and_w_numbers_are_weights() { + let family = styles(&["Hairline", "Thin", "Regular", "Bold"]); + assert_eq!(walk(&family, "Regular", false), ["Thin", "Hairline"]); + // Off the list (a stored style the family lacks): by weight, the nearer of two equal ones. + assert_eq!(next_style(&family, &at("Extra Light"), false).as_deref(), Some("Thin")); + assert_eq!(next_style(&family, &at("Extra Light"), true).as_deref(), Some("Regular")); + let hiragino = styles(&["W3", "W6"]); + assert_eq!(walk(&hiragino, "W3", true), ["W6"]); + assert_eq!(next_style(&hiragino, &at("Bold"), false).as_deref(), Some("W6")); +} + #[test] fn a_custom_weight_axis_value_steps_from_where_it_is() { let family = styles(&["Light", "Regular", "Medium", "Bold"]); @@ -59,19 +87,19 @@ fn font_style(s: &Session, t: NodeId) -> String { #[test] fn the_commands_land_on_styles_the_family_has() { figcraft_text::scan_system_fonts(); - // Any installed family with a regular face and a heavier upright one (CI machines differ). - let upright = |x: &String| !x.to_lowercase().contains("italic") && !x.to_lowercase().contains("oblique"); + // Any installed family with a Regular face and a style the step takes it to (CI machines differ). let pick = figcraft_text::family_names().into_iter().find_map(|f| { let st = figcraft_text::family_styles(&f); - (st.iter().any(|x| x == "Regular") && st.iter().any(|x| upright(x) && figcraft_doc::style_weight(x) > 400)).then_some((f, st)) + let up = next_style(&st, &at("Regular"), true).filter(|_| st.iter().any(|x| x == "Regular"))?; + Some((f, st, up)) }); - let Some((family, styles)) = pick else { return }; + let Some((family, styles, heavier)) = pick else { return }; let mut s = Session::new(); let r = s.execute("node.create", &json!({"type": "text", "text": "Hi", "props": {"fontFamily": family, "fontStyle": "Regular"}})).unwrap(); let t = crate::params::id_of(&r["id"]).unwrap(); s.execute("text.weightUp", &json!({"ids": [t]})).unwrap(); let up = font_style(&s, t); - assert!(styles.contains(&up) && figcraft_doc::style_weight(&up) > 400, "{family}: {up} of {styles:?}"); + assert_eq!(up, heavier, "{family}: {styles:?}"); s.execute("text.weightDown", &json!({"ids": [t]})).unwrap(); assert_eq!(font_style(&s, t), "Regular", "{family}: {styles:?}"); // A family that isn't installed still steps by 100 under the canonical names. From 2c9226c0215acf23772cd6c062790019fe9629d7 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 3 Nov 2026 03:44:58 +0100 Subject: [PATCH 027/102] M4: weight steps from an off-list weight compare the faces' own weights (#1831) next_style compared a custom wght value or a style the family lacks with the weights the style names say, so Segoe UI Variable's Semilight (350) counted as 300 and a wght of 325 stepped up to Regular. The family's styles now come with the weights the style menu sorts them by (figcraft_text::family_style_weights), and "W7 Italic" reads as 700. --- crates/engine/src/cmd/text.rs | 33 +++++++++------- crates/engine/src/text_weight_step_tests.rs | 43 ++++++++++++++++++--- crates/text/src/fontdb.rs | 13 ++++++- crates/text/src/lib.rs | 4 +- 4 files changed, 69 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 31008533a..a25d19733 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -176,32 +176,35 @@ fn slanted(style: &str) -> bool { s.contains("italic") || s.contains("oblique") } -/// The weight a style name says ("W3" too). -fn name_weight(style: &str) -> u16 { - w_number(&style.to_ascii_lowercase()).unwrap_or_else(|| figcraft_doc::style_weight(style)) +/// The weight a style name says ("W3" and "W6 Italic" too). +pub(crate) fn name_weight(style: &str) -> u16 { + let first = style.to_ascii_lowercase().replace('-', " "); + first.split_whitespace().next().and_then(w_number).unwrap_or_else(|| figcraft_doc::style_weight(style)) } -/// The next heavier (`up`) or lighter style of `styles` (a family's, lightest first, as the style -/// menu lists them) after the chars' style, with the same slant and width. The chars' style is -/// found in the list by name and its neighbour taken; a style the family doesn't have, or a custom -/// weight axis value, goes to the nearest weight that way. None when the family has nothing further. -pub(crate) fn next_style(styles: &[String], st: &TextStyle, up: bool) -> Option { +/// The next heavier (`up`) or lighter style of `styles` (a family's with the weight each is listed +/// by, lightest first, as the style menu lists them) after the chars' style, with the same slant +/// and width. The chars' style is found in the list by name and its neighbour taken; a style the +/// family doesn't have, or a custom weight axis value, goes to the listed style of nearest weight +/// that way. None when the family has nothing further. +pub(crate) fn next_style(styles: &[(String, u16)], st: &TextStyle, up: bool) -> Option { let italic = st.italic() || slanted(&st.font_style); let rest = style_rest(&st.font_style); - let mut same: Vec<&String> = styles.iter().filter(|x| slanted(x) == italic && style_rest(x) == rest).collect(); + let mut same: Vec<&(String, u16)> = styles.iter().filter(|(x, _)| slanted(x) == italic && style_rest(x) == rest).collect(); let norm = |s: &str| s.to_lowercase().replace([' ', '-', '_'], ""); - let here = same.iter().position(|x| norm(x) == norm(&st.font_style)); - if let Some(i) = here.filter(|_| !st.variations.contains_key("wght")) { + let here = same.iter().position(|(x, _)| norm(x) == norm(&st.font_style)); + let axis = st.variations.contains_key("wght"); + if let Some(i) = here.filter(|_| !axis) { let next = if up { i.checked_add(1) } else { i.checked_sub(1) }; - return next.and_then(|n| same.get(n)).map(|x| (*x).clone()); + return next.and_then(|n| same.get(n)).map(|(x, _)| x.clone()); } - let w = i32::from(st.weight()); + let w = i32::from(if axis { st.weight() } else { name_weight(&st.font_style) }); // Of equal weights, the one nearest in the family's order: the first going up, the last going down. if !up { same.reverse(); } same.into_iter() - .map(|x| (i32::from(name_weight(x)) - w, x)) + .map(|(x, xw)| (i32::from(*xw) - w, x)) .filter(|(d, _)| if up { *d > 0 } else { *d < 0 }) .min_by_key(|(d, _)| d.abs()) .map(|(_, x)| x.clone()) @@ -210,7 +213,7 @@ pub(crate) fn next_style(styles: &[String], st: &TextStyle, up: bool) -> Option< /// `text.weightUp` / `text.weightDown`: each targeted run moves to the next style of its family. fn step_weight(s: &mut Session, p: &Value, up: bool) -> Result { style(s, p, |st| { - let styles = figcraft_text::family_styles(&st.font_family); + let styles = figcraft_text::family_style_weights(&st.font_family); if styles.is_empty() { // A family that isn't installed: step the weight by 100 under its canonical name. let w = (i32::from(st.weight()) + if up { 100 } else { -100 }).clamp(100, 900) as u16; diff --git a/crates/engine/src/text_weight_step_tests.rs b/crates/engine/src/text_weight_step_tests.rs index f3647d77d..96562bf7e 100644 --- a/crates/engine/src/text_weight_step_tests.rs +++ b/crates/engine/src/text_weight_step_tests.rs @@ -5,10 +5,16 @@ use figcraft_doc::{NodeId, TextStyle}; use serde_json::json; use crate::Session; -use crate::cmd::text::next_style; +use crate::cmd::text::{name_weight, next_style}; -fn styles(names: &[&str]) -> Vec { - names.iter().map(|s| (*s).to_string()).collect() +/// A family's styles listed by the weights their names say, as for faces not read yet. +fn styles(names: &[&str]) -> Vec<(String, u16)> { + names.iter().map(|s| ((*s).to_string(), name_weight(s))).collect() +} + +/// A family's styles with the faces' own weights. +fn weighed(faces: &[(&str, u16)]) -> Vec<(String, u16)> { + faces.iter().map(|(s, w)| ((*s).to_string(), *w)).collect() } fn at(style: &str) -> TextStyle { @@ -18,7 +24,7 @@ fn at(style: &str) -> TextStyle { } /// Walk `from` heavier (`up`) or lighter until the family has nothing further. -fn walk(family: &[String], from: &str, up: bool) -> Vec { +fn walk(family: &[(String, u16)], from: &str, up: bool) -> Vec { let mut st = at(from); let mut out = Vec::new(); while let Some(next) = next_style(family, &st, up) { @@ -80,6 +86,31 @@ fn a_custom_weight_axis_value_steps_from_where_it_is() { assert_eq!(next_style(&family, &st, false).as_deref(), Some("Medium")); } +#[test] +fn off_the_list_the_faces_own_weights_decide() { + // From 500 between 400 and 700 faces: the neighbours, under their own names (the axis value goes). + let family = weighed(&[("Light", 300), ("Regular", 400), ("Bold", 700)]); + let mut st = at("Regular"); + st.variations.insert("wght".into(), 500.0); + assert_eq!(next_style(&family, &st, true).as_deref(), Some("Bold")); + assert_eq!(next_style(&family, &st, false).as_deref(), Some("Regular")); + st.set_font_style("Bold"); + assert_eq!((st.weight(), st.variations.get("wght")), (700, None)); + // Segoe UI Variable's Semilight is 350, not the 300 its name says: from a `wght` of 325 it is + // the next heavier style, and from 375 the next lighter. + let segoe = weighed(&[("Light", 300), ("Semilight", 350), ("Regular", 400), ("Semibold", 600), ("Bold", 700)]); + st.variations.insert("wght".into(), 325.0); + assert_eq!(next_style(&segoe, &st, true).as_deref(), Some("Semilight")); + assert_eq!(next_style(&segoe, &st, false).as_deref(), Some("Light")); + st.variations.insert("wght".into(), 375.0); + assert_eq!(next_style(&segoe, &st, false).as_deref(), Some("Semilight")); + assert_eq!(next_style(&segoe, &st, true).as_deref(), Some("Regular")); + // A W-numbered name with a slant after it is still that weight ("W7 Italic" is 700). + let hiragino = weighed(&[("W3 Italic", 300), ("W6 Italic", 600), ("W8 Italic", 800)]); + assert_eq!(next_style(&hiragino, &at("W7 Italic"), false).as_deref(), Some("W6 Italic")); + assert_eq!(next_style(&hiragino, &at("W7 Italic"), true).as_deref(), Some("W8 Italic")); +} + fn font_style(s: &Session, t: NodeId) -> String { s.doc().unwrap().node(t).unwrap().kind.text().unwrap().spans()[0].2.font_style.clone() } @@ -89,8 +120,8 @@ fn the_commands_land_on_styles_the_family_has() { figcraft_text::scan_system_fonts(); // Any installed family with a Regular face and a style the step takes it to (CI machines differ). let pick = figcraft_text::family_names().into_iter().find_map(|f| { - let st = figcraft_text::family_styles(&f); - let up = next_style(&st, &at("Regular"), true).filter(|_| st.iter().any(|x| x == "Regular"))?; + let st = figcraft_text::family_style_weights(&f); + let up = next_style(&st, &at("Regular"), true).filter(|_| st.iter().any(|(x, _)| x == "Regular"))?; Some((f, st, up)) }); let Some((family, styles, heavier)) = pick else { return }; diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index d0004fcd9..c3c2f43a6 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -743,6 +743,12 @@ impl FontDb { /// Style names of a family, by weight then italic. pub fn styles(&mut self, family: &str) -> Vec { + self.style_weights(family).into_iter().map(|(name, _)| name).collect() + } + + /// [`styles`](Self::styles) with the weight each is listed by: the face's own (Segoe UI + /// Semilight is 350), a named instance's `wght`, or for a face not read yet its name's. + pub fn style_weights(&mut self, family: &str) -> Vec<(String, u16)> { self.load_family(family, None); let key = self.key(family); // (weight, italic, order in the font, name): named instances keep the font's order. @@ -768,7 +774,7 @@ impl FontDb { v.sort(); let mut seen = std::collections::HashSet::new(); v.retain(|x| seen.insert(norm_style(&x.3))); - v.into_iter().map(|x| x.3).collect() + v.into_iter().map(|x| (x.3, x.0)).collect() } /// The key `family` is known under: itself in any case; for a name designs use for Apple's @@ -1502,6 +1508,11 @@ pub fn family_styles(family: &str) -> Vec { db().write().unwrap_or_else(std::sync::PoisonError::into_inner).styles(family) } +/// [`family_styles`] with the weight each is listed by (see [`FontDb::style_weights`]). +pub fn family_style_weights(family: &str) -> Vec<(String, u16)> { + db().write().unwrap_or_else(std::sync::PoisonError::into_inner).style_weights(family) +} + /// Scan system fonts into the global db (desktop; a no-op on the web, or with /// `FIGCRAFT_NO_SYSTEM_FONTS` set). Runs once per process: a concurrent caller waits for that scan. /// The directory walk runs without holding the database lock; results are merged in one short write. diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index cad3e1326..b6d87d669 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -17,8 +17,8 @@ pub use breaks::{backspace_step, grapheme_step}; pub use color::{ColorBitmap, ColorInk, ColorLayer}; pub use fontdb::{ Axis, CRAFT_FONTS, Coords, Face, FontDb, LocalFont, NamedInstance, Rescan, add_local_fonts, axis_label, db, face_with_char, family_names, - family_styles, find_face, has_family, installed_fonts_known, load_font_bytes, load_local_font, local_only, no_coords, opt_out_of_system_fonts, - rescan_system_fonts, scan_system_fonts, scan_system_fonts_on_demand, system_fonts_scanned, take_wanted_local_fonts, + family_style_weights, family_styles, find_face, has_family, installed_fonts_known, load_font_bytes, load_local_font, local_only, no_coords, + opt_out_of_system_fonts, rescan_system_fonts, scan_system_fonts, scan_system_fonts_on_demand, system_fonts_scanned, take_wanted_local_fonts, }; pub use layout::{Decoration, Glyph, Line, TextLayout, layout}; pub use onpath::OnPath; From 45c89c5a737e493c9e2e3de12d0e40d02ee2edbc Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 3 Nov 2026 04:38:16 +0100 Subject: [PATCH 028/102] M4: weight steps reach a weight family's italics and read W weights after a width (#1831) A family installed as one family per weight ("Foo Bold" with Regular and Italic faces) now lists Bold and Bold Italic, the names resolve draws them by, with the faces' own weights when they are read. A W-numbered weight counts after other words too ("Condensed W7 Italic" is 700). --- crates/engine/src/cmd/text.rs | 6 +-- crates/engine/src/text_weight_step_tests.rs | 4 ++ crates/text/src/fontdb.rs | 21 ++++++++-- crates/text/src/fontdb_names_tests.rs | 43 ++++++++++++++++++++- 4 files changed, 67 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index a25d19733..9024e1229 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -176,10 +176,10 @@ fn slanted(style: &str) -> bool { s.contains("italic") || s.contains("oblique") } -/// The weight a style name says ("W3" and "W6 Italic" too). +/// The weight a style name says ("W3", "W6 Italic" and "Condensed W7" too). pub(crate) fn name_weight(style: &str) -> u16 { - let first = style.to_ascii_lowercase().replace('-', " "); - first.split_whitespace().next().and_then(w_number).unwrap_or_else(|| figcraft_doc::style_weight(style)) + let words = style.to_ascii_lowercase().replace('-', " "); + words.split_whitespace().find_map(w_number).unwrap_or_else(|| figcraft_doc::style_weight(style)) } /// The next heavier (`up`) or lighter style of `styles` (a family's with the weight each is listed diff --git a/crates/engine/src/text_weight_step_tests.rs b/crates/engine/src/text_weight_step_tests.rs index 96562bf7e..e8bf65a7b 100644 --- a/crates/engine/src/text_weight_step_tests.rs +++ b/crates/engine/src/text_weight_step_tests.rs @@ -109,6 +109,10 @@ fn off_the_list_the_faces_own_weights_decide() { let hiragino = weighed(&[("W3 Italic", 300), ("W6 Italic", 600), ("W8 Italic", 800)]); assert_eq!(next_style(&hiragino, &at("W7 Italic"), false).as_deref(), Some("W6 Italic")); assert_eq!(next_style(&hiragino, &at("W7 Italic"), true).as_deref(), Some("W8 Italic")); + // And after a width ("Condensed W7 Italic" is 700 too). + let condensed = weighed(&[("Condensed W3 Italic", 300), ("Condensed W6 Italic", 600), ("Condensed W8 Italic", 800)]); + assert_eq!(next_style(&condensed, &at("Condensed W7 Italic"), true).as_deref(), Some("Condensed W8 Italic")); + assert_eq!(next_style(&condensed, &at("Condensed W7 Italic"), false).as_deref(), Some("Condensed W6 Italic")); } fn font_style(s: &Session, t: NodeId) -> String { diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index c3c2f43a6..a856aa1fe 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -767,9 +767,24 @@ impl FontDb { v.push((w, f.italic || italic_name(&inst.name), k, inst.name.clone())); } } - // A family installed as one family per weight offers those weights too. - for (_, style) in self.split_families(&key) { - v.push((pending_weight(&style).clamp(1, 1000) as u16, italic_name(&style), 0, style)); + // A family installed as one family per weight offers those weights too, upright and italic + // as that family's faces are ("Foo Bold" with Regular and Italic faces: Bold and Bold + // Italic, the names `resolve` finds them by). A face read gives its own weight, one not + // read the name's; the families aren't read for this. + for (k, style) in self.split_families(&key) { + let named = pending_weight(&style).clamp(1, 1000) as u16; + let italic = italic_name(&style); + let read = self.families.get(&k).map(|(_, idx)| idx.as_slice()).unwrap_or_default().iter().filter_map(|i| self.faces.get(*i)); + let unread = self.pending.get(&k).into_iter().flat_map(|(_, entries)| entries).map(|e| (named, italic_name(&e.style))); + let faces: Vec<(u16, bool)> = read.map(|f| (f.weight, f.italic)).chain(unread).collect(); + if faces.is_empty() { + v.push((named, italic, 0, style)); + continue; + } + for (w, slanted) in faces { + let name = if slanted && !italic { format!("{style} Italic") } else { style.clone() }; + v.push((w, slanted || italic, 0, name)); + } } v.sort(); let mut seen = std::collections::HashSet::new(); diff --git a/crates/text/src/fontdb_names_tests.rs b/crates/text/src/fontdb_names_tests.rs index 0d31b7c56..62bd27be3 100644 --- a/crates/text/src/fontdb_names_tests.rs +++ b/crates/text/src/fontdb_names_tests.rs @@ -5,9 +5,10 @@ //! case; the picker lists what is installed. Synthetic family names only, over pending entries //! (no files) and the embedded faces when the build has them. +use std::collections::BTreeMap; use std::sync::Arc; -use super::{CRAFT_FONTS, Face, FontBytes, FontDb, Pending, style_words}; +use super::{CRAFT_FONTS, Face, FontBytes, FontDb, LocalFont, Pending, scan_dir, style_words, system_font_dirs}; fn entry(style: &str) -> Pending { Pending { path: format!("no-such-dir/{style}.ttf").into(), index: 0, style: style.into(), postscript: None, local: None } @@ -104,3 +105,43 @@ fn faces_are_found_and_listed_under_either_name() { assert!(Arc::ptr_eq(&db.find("Synthetic Text SemiBold", "Regular").unwrap(), &semibold)); assert!(Arc::ptr_eq(&db.find("synthetictext", "Semibold").unwrap(), &semibold)); } + +#[test] +fn a_family_per_weight_offers_its_italics_too() { + // Listed by name before anything is read: Synthetic Slab Bold's Italic face is Bold Italic. + let local = |id: usize, family: &str, style: &str| LocalFont { id, family: family.into(), style: style.into(), postscript: String::new() }; + let mut db = FontDb::default(); + db.add_local(vec![ + local(0, "Synthetic Slab", "Regular"), + local(1, "Synthetic Slab", "Italic"), + local(2, "Synthetic Slab Bold", "Regular"), + local(3, "Synthetic Slab Bold", "Italic"), + ]); + let listed = |db: &mut FontDb| db.style_weights("Synthetic Slab"); + let want = |v: &[(&str, u16)]| v.iter().map(|(s, w)| ((*s).to_string(), *w)).collect::>(); + assert_eq!(listed(&mut db), want(&[("Regular", 400), ("Italic", 400), ("Bold", 700), ("Bold Italic", 700)])); + assert_eq!(resolved(&db, "Synthetic Slab", "Bold Italic"), pair("synthetic slab bold", "Italic"), "the style drawn by that face"); + // Faces read give their own weights: Synthetic Slab Semi Light's are 350, not the name's 300. + let stand_in = CRAFT_FONTS.first().map(|f| f.bytes.to_vec()).or_else(|| { + let mut installed = BTreeMap::new(); + for dir in system_font_dirs() { + scan_dir(&dir, 0, &mut installed); + } + installed.values().flat_map(|(_, v)| v).find_map(|p| std::fs::read(&p.path).ok()) + }); + let Some(bytes) = stand_in.map(Arc::new) else { + eprintln!("skipping the read faces: no font to stand in"); + return; + }; + let face = |family: &str, style: &str, weight: u16, italic: bool| { + let mut f = Face::from_bytes(FontBytes::Shared(bytes.clone()), 0, Some(family), Some(style)).unwrap(); + f.instances.clear(); + (f.weight, f.italic) = (weight, italic); + f + }; + let mut db = FontDb::default(); + db.add(face("Synthetic Slab", "Regular", 400, false)); + db.add(face("Synthetic Slab Semi Light", "Regular", 350, false)); + db.add(face("Synthetic Slab Semi Light", "Italic", 350, true)); + assert_eq!(listed(&mut db), want(&[("Semi Light", 350), ("Semi Light Italic", 350), ("Regular", 400)])); +} From 8864068cd592f517d4dd4b0ce6c4270957d9d0c6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:21:45 +0000 Subject: [PATCH 029/102] fix(engine): compare online servers' paths with their case same_server lowercased the whole address, so files on /Team/ and /team/ (which a proxy can route to different servers) counted as one server and the online refresh sent both files' owner tokens to whichever answered. The scheme and host still compare without case; the path keeps its. --- crates/engine/src/online_tests.rs | 3 +++ crates/engine/src/sharing/online.rs | 13 ++++++++----- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/online_tests.rs b/crates/engine/src/online_tests.rs index af13db8e7..c6feca29c 100644 --- a/crates/engine/src/online_tests.rs +++ b/crates/engine/src/online_tests.rs @@ -590,4 +590,7 @@ fn same_server_ignores_the_default_port_before_a_path() { assert!(same_server("wss://share.example:443/figcraft/", "wss://share.example/figcraft/")); assert!(same_server("ws://host:80/x", "ws://host/x")); assert!(!same_server("wss://share.example:8443/figcraft/", "wss://share.example/figcraft/")); + // The path is a route: owner tokens for /Team/ must never be sent to /team/. + assert!(same_server("WSS://Share.Example/team/", "wss://share.example/team")); + assert!(!same_server("wss://share.example/Team/", "wss://share.example/team/")); } diff --git a/crates/engine/src/sharing/online.rs b/crates/engine/src/sharing/online.rs index d68b20f82..89eb8a266 100644 --- a/crates/engine/src/sharing/online.rs +++ b/crates/engine/src/sharing/online.rs @@ -117,14 +117,17 @@ pub(crate) fn plain_server(server: &str) -> String { /// Two addresses name the same server (case, a closing slash and the scheme's own port aside). pub fn same_server(a: &str, b: &str) -> bool { let norm = |s: &str| { - let s = plain_server(s).to_ascii_lowercase(); + let s = plain_server(s); let s = s.trim_end_matches('/'); - let port = if s.starts_with("wss://") { ":443" } else { ":80" }; let start = s.find("://").map_or(0, |i| i + 3); let end = s[start..].find('/').map_or(s.len(), |i| start + i); - match s[start..end].strip_suffix(port) { - Some(host) => format!("{}{}{}", &s[..start], host, &s[end..]), - None => s.to_string(), + // The scheme and host compare without case; the path routes (a proxy may send + // `/Team/` and `/team/` to different servers), so it keeps its case. + let head = s[..end].to_ascii_lowercase(); + let port = if head.starts_with("wss://") { ":443" } else { ":80" }; + match head[start..].strip_suffix(port) { + Some(host) => format!("{}{}{}", &head[..start], host, &s[end..]), + None => format!("{head}{}", &s[end..]), } }; norm(a) == norm(b) From 4e7d8319f1c04428672e7c84e80d63b9eb11f966 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:22:15 +0000 Subject: [PATCH 030/102] fix(collab-net): hold a health check's header read to the handshake deadline The request line was read within the hello timeout, but the header loop after it only timed out per read, so a peer dripping header bytes kept the worker thread and its connection slot for as long as it liked. Each header read now gets what is left of the one deadline. --- crates/collab-net/src/hub/conn.rs | 34 +++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/collab-net/src/hub/conn.rs b/crates/collab-net/src/hub/conn.rs index 1f365cbab..345f94117 100644 --- a/crates/collab-net/src/hub/conn.rs +++ b/crates/collab-net/src/hub/conn.rs @@ -51,6 +51,12 @@ fn health_check(stream: &mut TcpStream, until: Instant) -> bool { let mut req = Vec::new(); let mut chunk = [0u8; 1024]; while !req.windows(4).any(|w| w == b"\r\n\r\n") && req.len() < 16 << 10 { + // The same deadline as the request line: a peer dripping header bytes would otherwise + // hold this thread and its connection slot for as long as it liked. + let left = until.saturating_duration_since(Instant::now()); + if left.is_zero() || stream.set_read_timeout(Some(left)).is_err() { + break; + } match stream.read(&mut chunk) { Ok(0) | Err(_) => break, Ok(n) => req.extend_from_slice(chunk.get(..n).unwrap_or_default()), @@ -407,3 +413,31 @@ fn linger(ws: &mut WebSocket) { } } } + +#[cfg(test)] +mod health_check_tests { + use super::*; + + #[test] + fn a_health_check_dripping_headers_ends_at_the_deadline() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let client = std::thread::spawn(move || { + let mut c = TcpStream::connect(addr).unwrap(); + c.write_all(b"GET /healthz HTTP/1.1\r\n").unwrap(); + // One header byte every 20 ms, far past the deadline, until the server hangs up. + for _ in 0..200 { + if c.write_all(b"X").is_err() { + break; + } + std::thread::sleep(Duration::from_millis(20)); + } + }); + let (mut stream, _) = listener.accept().unwrap(); + let start = Instant::now(); + assert!(health_check(&mut stream, start + Duration::from_millis(300))); + assert!(start.elapsed() < Duration::from_secs(2), "{:?}", start.elapsed()); + drop(stream); + client.join().unwrap(); + } +} From 970a3e6745d27f7a1fab9e27e82553a7545aef66 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:22:36 +0000 Subject: [PATCH 031/102] fix(engine): check the opened file, not the looked-up path, before reading it read_capped checked the path's metadata (type and size) and then opened the path again, so an entry swapped between the two steps was read without those checks. The opened handle's metadata is checked as well; the path check stays, so a pipe is still refused before it is opened. --- crates/engine/src/automation/file_access.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/engine/src/automation/file_access.rs b/crates/engine/src/automation/file_access.rs index b40a92f79..26f15700b 100644 --- a/crates/engine/src/automation/file_access.rs +++ b/crates/engine/src/automation/file_access.rs @@ -277,6 +277,14 @@ pub fn read_capped(path: impl AsRef, max: u64) -> Result> { return Err(refuse(format!("is {}, more than the {} allowed here", size(meta.len()), size(max)))); } let f = std::fs::File::open(p).map_err(io(path))?; + // What was opened, not what was looked at: the path could have been swapped in between. + let meta = f.metadata().map_err(io(path))?; + if !meta.is_file() { + return Err(refuse("isn't a regular file (a device or a pipe?), so it isn't read".into())); + } + if meta.len() > max { + return Err(refuse(format!("is {}, more than the {} allowed here", size(meta.len()), size(max)))); + } let mut bytes = Vec::with_capacity(usize::try_from(meta.len()).unwrap_or(0)); f.take(max.saturating_add(1)).read_to_end(&mut bytes).map_err(io(path))?; // It grew after it was looked at. From 5bbab0fa181329d01973c489bc6fb01b4f863ab4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:23:05 +0000 Subject: [PATCH 032/102] fix(pdf): drop an oversized hyperlink before it is copied once per line Every linked line copied the destination string, and its length was only checked when the annotation was written, so one multi-megabyte link on text wrapping onto many lines was copied that many times first. The length is checked where the link areas are collected. --- crates/pdf/src/export_tests.rs | 17 +++++++++++++++++ crates/pdf/src/text.rs | 4 +++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/pdf/src/export_tests.rs b/crates/pdf/src/export_tests.rs index 259e58327..d41f11379 100644 --- a/crates/pdf/src/export_tests.rs +++ b/crates/pdf/src/export_tests.rs @@ -284,3 +284,20 @@ fn depth_samples() { std::fs::write(format!("{stem}-{name}.png"), figcraft_render::encode_png(&pix).unwrap()).unwrap(); } } + +#[test] +fn an_oversized_link_is_dropped_before_it_is_copied_per_line() { + // One link far past MAX_URL on text that wraps onto many lines: no annotation, and the + // destination is never copied once per line on the way to being refused. + let mut d = Document::new("long link"); + let p = d.first_page().unwrap_or(NodeId(0)); + let f = d.create(p, NodeKind::Frame, "F", 0.0, 0.0, 300.0, 4000.0).unwrap(); + let words = "word ".repeat(2_000); + let mut td = TextData::new(words.trim_end()); + td.style.font_size = 20.0; + td.style.link = Some("https://example.com/".to_string() + &"a".repeat(1 << 20)); + let t = d.create(f, NodeKind::Text(td), "T", 10.0, 10.0, 280.0, 3980.0).unwrap(); + d.get_mut(t).unwrap().fills = vec![Paint::solid(Color::BLACK)]; + let pdf = export_pdf(&d, &[f], &PdfOptions::default()).unwrap(); + assert_eq!(text(&pdf).matches("/Subtype/Link").count(), 0); +} diff --git a/crates/pdf/src/text.rs b/crates/pdf/src/text.rs index abbb65b34..3b3917689 100644 --- a/crates/pdf/src/text.rs +++ b/crates/pdf/src/text.rs @@ -111,7 +111,9 @@ fn record_links(ex: &mut Exporter, layout: &TextLayout, gxf: Affine) { let glyphs = layout.glyphs.get(line.glyph_start..line.glyph_end).unwrap_or(&[]); for g in glyphs.iter().map(Some).chain([None]) { let link = g.and_then(|g| { - let url = layout.styles.get(g.style)?.link.as_deref().filter(|u| !u.trim().is_empty())?; + // Checked here, not when the annotation is written: every linked line copies + // the destination, so one oversized link must not be copied at all. + let url = layout.styles.get(g.style)?.link.as_deref().map(str::trim).filter(|u| !u.is_empty() && u.len() <= crate::MAX_URL)?; let (a, b) = (g.x, g.x + g.advance); (a.is_finite() && b.is_finite()).then(|| (url, a.min(b), a.max(b))) }); From a9e66d2de9cc628a09f98898b69ec8a5bb2404fc Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:24:32 +0000 Subject: [PATCH 033/102] perf(vectordrawable): keep warning names in a set Each affected layer name was checked against every name already kept for the warning, quadratic in the number of distinct names although only three are ever shown. A set holds the distinct names; the first three stay in order. --- crates/vectordrawable/src/warnings.rs | 38 ++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/crates/vectordrawable/src/warnings.rs b/crates/vectordrawable/src/warnings.rs index 445198d5b..6f7f152ef 100644 --- a/crates/vectordrawable/src/warnings.rs +++ b/crates/vectordrawable/src/warnings.rs @@ -63,27 +63,53 @@ const NAMED: usize = 3; #[derive(Default)] pub(crate) struct Warnings { - seen: std::collections::BTreeMap>, + /// Per warning: the distinct names so far (a set, so a document with many distinct names + /// doesn't make each check a scan of all before it), and the first few in order. + seen: std::collections::BTreeMap, Vec)>, } impl Warnings { pub fn add(&mut self, w: Warn, layer: &str) { - let names = self.seen.entry(w).or_default(); - if !names.iter().any(|n| n == layer) { - names.push(layer.to_string()); + let (distinct, first) = self.seen.entry(w).or_default(); + if distinct.insert(layer.to_string()) && first.len() < NAMED { + first.push(layer.to_string()); } } pub fn finish(self) -> Vec { self.seen .into_iter() - .map(|(w, names)| { + .map(|(w, (distinct, names))| { let shown: Vec = names.iter().take(NAMED).map(|n| if n.is_empty() { "unnamed layer".to_string() } else { n.clone() }).collect(); - let more = names.len().saturating_sub(NAMED); + let more = distinct.len().saturating_sub(NAMED); let more = if more > 0 { format!(", {more} more") } else { String::new() }; format!("{} ({}{more})", w.message(), shown.join(", ")) }) .collect() } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_are_counted_once_each_and_the_first_three_shown() { + let mut w = Warnings::default(); + for name in ["a", "b", "a", "c", "d", "b", "e"] { + w.add(Warn::NothingDrawn, name); + } + let lines = w.finish(); + assert_eq!(lines.len(), 1); + assert!(lines[0].ends_with("(a, b, c, 2 more)"), "{}", lines[0]); + // Many distinct names: each is one set insertion, not a scan of all before it. + let mut w = Warnings::default(); + let start = std::time::Instant::now(); + for i in 0..200_000 { + w.add(Warn::TooLarge, &format!("layer {i}")); + } + assert!(w.finish()[0].ends_with("199997 more)")); + assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed()); + } +} From 1ff0da1841bd4c2b45ef13e3e8ffec26b65cd94f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:26:03 +0000 Subject: [PATCH 034/102] fix(figcraft): write the recovery copy's online note owner-only The .online note beside a recovery copy holds the secret the client resumes its identity with, but it was written with the default mode while the copy itself was created 0600. Both now go through one owner-only writer, which also narrows a note that already existed. --- apps/figcraft/src/recovery.rs | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/apps/figcraft/src/recovery.rs b/apps/figcraft/src/recovery.rs index 750786d1c..92884e528 100644 --- a/apps/figcraft/src/recovery.rs +++ b/apps/figcraft/src/recovery.rs @@ -217,7 +217,8 @@ impl Recovery { return false; } let _ = match online { - Some(text) => std::fs::write(¬e, text), + // The note holds the secret the client resumes with: owner-only, as the copy. + Some(text) => write_private(¬e, text.as_bytes()), None => std::fs::remove_file(¬e), }; true @@ -326,24 +327,29 @@ fn rejoin_online(file: &Path, s: &mut Session) -> Option { fn write_atomic(path: &Path, doc: &figcraft_engine::doc::Document, versions: &[Version], branches: &[Branch]) -> bool { let Ok(bytes) = figcraft_format::save_bytes_with_history(doc, None, versions, branches) else { return false }; let tmp = path.with_extension("tmp"); + if write_private(&tmp, &bytes).is_err() { + let _ = std::fs::remove_file(&tmp); + return false; + } + std::fs::rename(&tmp, path).is_ok() +} + +/// Write `bytes` to `path`, created (or cut back) readable by its owner only on Unix. +fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> { #[cfg(unix)] { - use std::os::unix::fs::OpenOptionsExt; + use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; let mut opts = std::fs::OpenOptions::new(); opts.write(true).create(true).truncate(true).mode(0o600); - let Ok(mut f) = opts.open(&tmp) else { return false }; - if std::io::Write::write_all(&mut f, &bytes).is_err() { - let _ = std::fs::remove_file(&tmp); - return false; - } + let mut f = opts.open(path)?; + // `mode` applies to a new file only: one that was there keeps its mode unless set. + f.set_permissions(std::fs::Permissions::from_mode(0o600))?; + std::io::Write::write_all(&mut f, bytes) } #[cfg(not(unix))] { - if std::fs::write(&tmp, bytes).is_err() { - return false; - } + std::fs::write(path, bytes) } - std::fs::rename(&tmp, path).is_ok() } /// [`recover_all`], for a start that keeps nothing waiting: how many documents came back as From dd03165d79362b2d25b3c21de7128a0c24d31544 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 3 Nov 2026 05:27:23 +0100 Subject: [PATCH 035/102] M4: weight steps read number weights after a width too (#1831) An off-list "Condensed 600" read as 400, since a number word counted as a weight only at the start of the name: weightUp took Condensed 500 and weightDown found nothing. A number from 100 to 1000 now counts in any position, as W numbers do. Smaller numbers (a width grade, an optical size: "Condensed 2", "Caption 12") are part of the width rather than a weight, so optical sizes no longer step into each other. --- crates/engine/src/cmd/text.rs | 13 ++++++++++--- crates/engine/src/text_weight_step_tests.rs | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 9024e1229..392fd4636 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -128,6 +128,13 @@ fn w_number(word: &str) -> Option { (1..=9).contains(&n).then_some(n * 100) } +/// A weight number as some families name styles ("Condensed 600"). Below 100 it is something else +/// (a width grade, an optical size: "Condensed 2", "Caption 12"). +fn number_weight(word: &str) -> Option { + let n = word.parse::().ok().filter(|_| word.bytes().all(|b| b.is_ascii_digit()))?; + (100..=1000).contains(&n).then_some(n) +} + /// What a style name says besides its weight and slant ("Narrow Bold Italic" → "narrow", /// "Extra Condensed Bold" → "extra condensed"). fn style_rest(style: &str) -> String { @@ -162,7 +169,7 @@ fn style_rest(style: &str) -> String { const GRADES: [&str; 4] = ["extra", "ultra", "semi", "demi"]; let s = style.to_ascii_lowercase().replace('-', " "); let words: Vec<&str> = s.split_whitespace().collect(); - let weight = |w: &str| WEIGHTS.contains(&w) || w_number(w).is_some() || w.chars().all(|c| c.is_ascii_digit()); + let weight = |w: &str| WEIGHTS.contains(&w) || w_number(w).or_else(|| number_weight(w)).is_some(); let rest = words.iter().enumerate().filter(|(i, w)| { let graded = GRADES.contains(w) && words.get(i + 1).is_some_and(|next| weight(next) && !matches!(*next, "italic" | "oblique")); !weight(w) && !graded @@ -176,10 +183,10 @@ fn slanted(style: &str) -> bool { s.contains("italic") || s.contains("oblique") } -/// The weight a style name says ("W3", "W6 Italic" and "Condensed W7" too). +/// The weight a style name says ("W3", "W6 Italic", "Condensed W7" and "Condensed 600" too). pub(crate) fn name_weight(style: &str) -> u16 { let words = style.to_ascii_lowercase().replace('-', " "); - words.split_whitespace().find_map(w_number).unwrap_or_else(|| figcraft_doc::style_weight(style)) + words.split_whitespace().find_map(|w| w_number(w).or_else(|| number_weight(w))).unwrap_or_else(|| figcraft_doc::style_weight(style)) } /// The next heavier (`up`) or lighter style of `styles` (a family's with the weight each is listed diff --git a/crates/engine/src/text_weight_step_tests.rs b/crates/engine/src/text_weight_step_tests.rs index e8bf65a7b..057a0a4e5 100644 --- a/crates/engine/src/text_weight_step_tests.rs +++ b/crates/engine/src/text_weight_step_tests.rs @@ -77,6 +77,20 @@ fn hairline_and_w_numbers_are_weights() { assert_eq!(next_style(&hiragino, &at("Bold"), false).as_deref(), Some("W6")); } +#[test] +fn number_weights_count_after_a_width_but_other_numbers_dont() { + // An off-list "Condensed 600" is 600, as "600" alone is: between Condensed 500 and 700. + let condensed = weighed(&[("Condensed 300", 300), ("Condensed 500", 500), ("Condensed 700", 700)]); + assert_eq!(next_style(&condensed, &at("Condensed 600"), true).as_deref(), Some("Condensed 700")); + assert_eq!(next_style(&condensed, &at("Condensed 600"), false).as_deref(), Some("Condensed 500")); + assert_eq!((name_weight("Condensed 600"), name_weight("600 Italic"), name_weight("Condensed 1000")), (600, 600, 1000)); + // A number that isn't a weight (a width grade, an optical size) is part of the width. + assert_eq!((name_weight("Condensed 2"), name_weight("Caption 12 Bold"), name_weight("Condensed +600")), (400, 700, 400)); + let optical = styles(&["Caption 12 Regular", "Caption 24 Regular", "Caption 12 Bold", "Caption 24 Bold"]); + assert_eq!(walk(&optical, "Caption 12 Regular", true), ["Caption 12 Bold"]); + assert_eq!(walk(&optical, "Caption 24 Bold", false), ["Caption 24 Regular"]); +} + #[test] fn a_custom_weight_axis_value_steps_from_where_it_is() { let family = styles(&["Light", "Regular", "Medium", "Bold"]); From bd28a9c19e39f24058e4ffb0ae4ca1905b45f71f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:29:07 +0000 Subject: [PATCH 036/102] fix(text): load at most 64 faces from a font collection given as bytes A collection header names its faces in four bytes each, so a small upload could declare any number of faces over the same tables; every one was parsed and kept its own character map under the font database's lock. The largest real collections hold a few dozen faces; 64 are loaded. --- crates/text/src/fontdb.rs | 8 +++++++- crates/text/src/fontdb_tests.rs | 12 ++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index d0004fcd9..0643cb026 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -640,6 +640,9 @@ struct FallbackLists { /// The most styles whose fallback faces are kept (a file naming more starts the list again). const MAX_FALLBACK_STYLES: usize = 64; +/// Most faces loaded from one font collection given as bytes (the largest real collections, +/// the CJK ones, hold a few dozen). +const MAX_COLLECTION_FACES: u32 = 64; /// [`FontDb::key`]'s and [`FontDb::resolve`]'s answers for the families known in one generation. #[derive(Default)] @@ -711,7 +714,10 @@ impl FontDb { pub fn add_bytes(&mut self, bytes: Vec) -> Vec> { let shared = Arc::new(bytes); let count = match FileRef::new(shared.as_slice()) { - Ok(FileRef::Collection(c)) => c.len(), + // A collection's header may name any number of faces, each a few bytes pointing at + // the same tables, and every face keeps its own character map: at most + // [`MAX_COLLECTION_FACES`] of them are loaded. + Ok(FileRef::Collection(c)) => c.len().min(MAX_COLLECTION_FACES), Ok(FileRef::Font(_)) => 1, Err(_) => 0, }; diff --git a/crates/text/src/fontdb_tests.rs b/crates/text/src/fontdb_tests.rs index 5f0fa522b..112041050 100644 --- a/crates/text/src/fontdb_tests.rs +++ b/crates/text/src/fontdb_tests.rs @@ -595,3 +595,15 @@ fn system_font_dirs_are_walked_once_each() { let unique: std::collections::HashSet<_> = dirs.iter().collect(); assert_eq!(unique.len(), dirs.len(), "{dirs:?}"); } + +#[test] +fn a_collection_header_naming_billions_of_faces_loads_a_bounded_few() { + // Four bytes per face offset: a header can name far more faces than the data holds, and each + // one would be parsed (and keep a character map) in turn. + let mut bytes = synthetic_font_collection(32); + bytes[8..12].copy_from_slice(&u32::MAX.to_be_bytes()); + let start = std::time::Instant::now(); + let faces = FontDb::default().add_bytes(bytes); + assert!(faces.len() <= 64, "{}", faces.len()); + assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed()); +} From 72ec49f92f097393dac8d165093127dfd1a9a7d1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:31:08 +0000 Subject: [PATCH 037/102] fix(engine): bound the keys an effect object is probed for Unknown effect keys are found by reparsing the whole object once per key, so an effect with many unknown keys cost their number squared in cloning and parsing before it was refused. More than 32 keys is refused outright. --- crates/engine/src/cmd/props.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 01f83bc85..3025c5c4a 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -85,10 +85,18 @@ pub fn effect_from(cmd: &str, p: &Value, key: &str) -> Result> { Ok(Some(effect)) } +/// Most keys an effect object may carry (the widest effect takes about a dozen). +const MAX_EFFECT_KEYS: usize = 32; + /// Refuse the keys of effect `given` that `parse` ignores, naming the keys the effect takes. Set to /// null, a key it reads fails to parse or changes the effect; a key it ignores changes nothing. fn refuse_ignored_effect_keys(cmd: &str, at: &str, given: &Value, parse: impl Fn(&Value) -> Option) -> Result<()> { let Some(fields) = given.as_object() else { return Ok(()) }; + // Each key is probed by reparsing the whole object without it: bounded, or a long list of + // unknown keys costs its length squared before it is refused. + if fields.len() > MAX_EFFECT_KEYS { + return Err(bad(cmd, format!("{at}: more than {MAX_EFFECT_KEYS} properties"))); + } let parsed = parse(given); let ignored: Vec<&str> = fields .iter() From 31a60ed3606c18d8329a04e55faba6e16537419b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:35:27 +0000 Subject: [PATCH 038/102] fix(collab-net): give a management request one deadline for its answer reply read until the server answered, and every ping, pong or control frame renewed the per-read timeout, so a library endpoint could hold a background refresh (and the shared refresh permit) open indefinitely. The whole exchange now ends at one absolute deadline, the idle timeout from when the request went out. --- crates/collab-net/src/manage.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/collab-net/src/manage.rs b/crates/collab-net/src/manage.rs index 04c718c5d..eecbca964 100644 --- a/crates/collab-net/src/manage.rs +++ b/crates/collab-net/src/manage.rs @@ -206,7 +206,15 @@ fn send(ws: &mut Ws, msg: &ClientMsg) -> Result<(), String> { /// The next answer `pick` takes, or why there is none. fn reply(ws: &mut Ws, limits: &NetLimits, pick: impl Fn(ServerMsg) -> Option) -> Result { + // One deadline for the whole answer: pings, pongs and a message trickling in each renew the + // read timeout, so without it a server could keep a request (and the refresh permit the + // caller holds) waiting for as long as it liked. + let until = std::time::Instant::now() + limits.idle_timeout; + ws.get_mut().read_until(Some(until)); loop { + if std::time::Instant::now() >= until { + return Err("no answer from the server (it took too long)".into()); + } return match ws.read() { Ok(Message::Binary(b)) => match message::decode::(&b, limits.max_server_message) { Ok(ServerMsg::Refused { reason }) => Err(format!("{REFUSED}{reason}")), From 84a0693076a9cd6cf94691e8af324f8036a16ebc Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 3 Nov 2026 00:45:53 -0500 Subject: [PATCH 039/102] Fill section: the canvas crop and gradient handles follow the characters' shared fill The handles read the paint list the Fill section and the colour picker show (character_fills), so with the characters' image already in Crop mode the crop handles show and edit it, not the layer's own fill at that index; writes still go through fill.set, which moves the characters' list to the layer first. No undo step on entering crop mode. Test canvas::handles::character_fill_tests. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/handles.rs | 22 +++++++--- .../canvas/handles/character_fill_tests.rs | 40 +++++++++++++++++++ docs/ui-parity.md | 2 +- 3 files changed, 58 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/canvas/handles/character_fill_tests.rs diff --git a/crates/ui-egui/src/canvas/handles.rs b/crates/ui-egui/src/canvas/handles.rs index 137e2c92b..b9711dfa8 100644 --- a/crates/ui-egui/src/canvas/handles.rs +++ b/crates/ui-egui/src/canvas/handles.rs @@ -40,6 +40,15 @@ enum Drag { /// The Crop-mode image being edited: (node, fills, index, paint, image rect in the unit box). type UnitRect = (f64, f64, f64, f64); +/// The paint list a picker paint at an index belongs to on layer `n`, as the Fill section and the +/// colour picker list it: for fills, a text's characters' shared fills (`character_fills`: the +/// layer's own when the characters have none), else the layer's strokes. None when a text's +/// characters have different fills. Writes go through `fill.set`, which moves the characters' +/// list to the layer first, so the handles read and write the same paint (#1856). +fn edited_list(n: &figcraft_doc::Node, fills: bool) -> Option> { + if fills { figcraft_engine::cmd::lists::character_fills(n) } else { Some(n.strokes.clone()) } +} + /// The paint open in the colour picker, else the image fill in crop mode (while its layer is the /// selection). fn crop_target(app: &FigApp) -> Option<(NodeId, bool, usize, ImagePaint, UnitRect)> { @@ -53,7 +62,7 @@ fn crop_target(app: &FigApp) -> Option<(NodeId, bool, usize, ImagePaint, UnitRec }; let doc = app.session.doc().ok()?; let n = doc.node(id)?; - let list = if fills { &n.fills } else { &n.strokes }; + let list = edited_list(n, fills)?; let PaintKind::Image(img) = &list.get(index)?.kind else { return None }; if img.scale_mode != ImageScaleMode::Crop { return None; @@ -193,7 +202,7 @@ fn gradient_target(app: &FigApp) -> Option<(NodeId, bool, usize, figcraft_color: return None; } let n = app.session.doc().ok()?.node(id)?; - let list = if *fills { &n.fills } else { &n.strokes }; + let list = edited_list(n, *fills)?; match &list.get(*index)?.kind { PaintKind::Gradient(g) => Some((id, *fills, *index, g.clone())), _ => None, @@ -233,7 +242,7 @@ fn line_param(a: Pos2, b: Pos2, p: Pos2) -> Option<(f64, f32)> { fn set_gradient(app: &mut FigApp, id: NodeId, fills: bool, index: usize, g: figcraft_color::Gradient) { let Some(n) = app.session.doc().ok().and_then(|d| d.node(id)).cloned() else { return }; - let list = if fills { &n.fills } else { &n.strokes }; + let Some(list) = edited_list(&n, fills) else { return }; let Some(mut paint) = list.get(index).cloned() else { return }; paint.kind = PaintKind::Gradient(g); let cmd = if fills { "fill.set" } else { "stroke.set" }; @@ -652,7 +661,7 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) { Drag::Gradient { id, fills, index, which } => { let Some(u) = screen_to_unit(app, *id, pos) else { return }; let Some(n) = app.session.doc().ok().and_then(|d| d.node(*id)).cloned() else { return }; - let list = if *fills { &n.fills } else { &n.strokes }; + let Some(list) = edited_list(&n, *fills) else { return }; let Some(mut paint) = list.get(*index).cloned() else { return }; if let PaintKind::Gradient(g) = &mut paint.kind { match which { @@ -727,7 +736,7 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) { (ax.min(ax + nw), ay.min(ay + nh), ax.max(ax + nw), ay.max(ay + nh)) }; let Some(n) = app.session.doc().ok().and_then(|d| d.node(*id)).cloned() else { return }; - let list = if *fills { &n.fills } else { &n.strokes }; + let Some(list) = edited_list(&n, *fills) else { return }; let Some(mut paint) = list.get(*index).cloned() else { return }; if let PaintKind::Image(img) = &mut paint.kind { img.crop = Some(ImagePaint::crop_from_rect(r.0, r.1, r.2, r.3)); @@ -749,3 +758,6 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) { } } } + +#[cfg(test)] +mod character_fill_tests; diff --git a/crates/ui-egui/src/canvas/handles/character_fill_tests.rs b/crates/ui-egui/src/canvas/handles/character_fill_tests.rs new file mode 100644 index 000000000..59488cd3b --- /dev/null +++ b/crates/ui-egui/src/canvas/handles/character_fill_tests.rs @@ -0,0 +1,40 @@ +//! The canvas crop handles on a text whose characters share an image fill the layer doesn't have +//! (#1856): they show and edit the characters' image, the one the Fill section and the colour +//! picker show, not the layer's own fill at that index. + +use base64::Engine as _; +use figcraft_color::{Color, ImageScaleMode, Paint, PaintKind}; +use figcraft_engine::Session; +use serde_json::json; + +use super::crop_target; +use crate::colorpicker::PickerTarget; +use crate::layers_drag_tests::Ui; +use crate::present_tests::id; + +#[test] +fn the_crop_handles_follow_the_characters_shared_image_in_crop_mode() { + let mut s = Session::new(); + let t = id(&s.execute("text.create", &json!({"text": "Hello", "x": 0, "y": 0})).unwrap()); + s.execute("fill.set", &json!({"ids": [t.0], "color": "#00FF00"})).unwrap(); + let image = image::RgbaImage::from_pixel(40, 20, image::Rgba([200, 30, 30, 255])); + let mut png = std::io::Cursor::new(Vec::new()); + image.write_to(&mut png, image::ImageFormat::Png).unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(png.into_inner()); + s.execute("image.place", &json!({"data": data, "target": t.0, "mode": "fill"})).unwrap(); + s.execute("image.crop", &json!({"ids": [t.0], "index": 1})).unwrap(); + // The cropped image goes to the characters; the layer keeps only its green. + let cropped = s.doc().unwrap().node(t).unwrap().fills[1].clone(); + s.execute("text.style", &json!({"id": t.0, "start": 0, "end": 5, "textFills": [cropped]})).unwrap(); + s.doc_mut().unwrap().get_mut(t).unwrap().fills = vec![Paint::solid(Color::from_hex("#00FF00").unwrap())]; + let mut u = Ui::new(s); + // The picker on the Fill section's row: the characters' image, already in Crop mode. + u.app.ui.picker = Some(PickerTarget::Paint { fills: true, index: 0, ids: vec![t] }); + let (at, fills, index, img, _) = crop_target(&u.app).expect("the handles show the characters' image"); + assert_eq!((at, fills, index), (t, true, 0)); + assert_eq!(img.scale_mode, ImageScaleMode::Crop); + assert!( + matches!(u.app.session.doc().unwrap().node(t).unwrap().fills[0].kind, PaintKind::Solid { .. }), + "the layer's own fill is not what they show" + ); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 0bdb62441..0bc09a912 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -33,7 +33,7 @@ interaction feel not yet compared. | Colour picker placement and dismissal | done | Opens 8 pt beside the sidebar at the opening control, lifted to fit the screen; outside presses (including the sidebar), Escape and X close it. Reopening resets a dragged position; eyedropper sampling keeps it open. | | Colour picker image well | partial | the Image tab shows a checkered placeholder and Upload from computer until there is a file (no dialog at once); an image paint shows its asset preview; a file dropped on the open picker replaces the image, keeping the fill mode, crop, position and adjustments (`image.replace`). Layers' fills and strokes only (text ranges, styles and selection colours keep Upload). The Fill and Stroke swatches take no drop: a dragged file's position isn't known, so a drop with none goes to the open picker | | Colour picker on a new fill or stroke | done | + opens the picker on the new paint when the selection shares one paint list; on a mixed selection + adds a paint to each layer and no picker opens (#404) | -| Fill section on a text with coloured characters | done | a text's Fill section shows what its characters show: characters coloured differently while editing are mixed content ("Click + to replace mixed content", as a mixed selection; the developer documentation's `fills`: "Text nodes can have multiple sets of fills if some characters are colored differently than others"), and characters that all share fills the layer doesn't have show those. Any layer-level fill edit (a row, its picker, +, reordering, `fill.*`, `node.set`) reaches every character, starting from the list they showed; the characters' own fills go in the same undo step (`text_mixed_fill_tests`, engine `text_fill_tests`; #1856). A range selected while editing keeps its own Fill row | +| Fill section on a text with coloured characters | done | a text's Fill section shows what its characters show: characters coloured differently while editing are mixed content ("Click + to replace mixed content", as a mixed selection; the developer documentation's `fills`: "Text nodes can have multiple sets of fills if some characters are colored differently than others"), and characters that all share fills the layer doesn't have show those. Any layer-level fill edit (a row, its picker, +, reordering, `fill.*`, `node.set`) reaches every character, starting from the list they showed; the characters' own fills go in the same undo step; the canvas gradient and crop handles show and edit the paint the row shows, the characters' own, also when their image is already in Crop mode (`text_mixed_fill_tests`, `canvas::handles::character_fill_tests`, engine `text_fill_tests`; #1856). A range selected while editing keeps its own Fill row | | Blend mode menus: the layer's (Design panel) and each paint's (colour picker) | done | Pass through and Normal are distinct (Normal isolates a group's or frame's children); paints have no pass-through; plus darker drawn exactly on the canvas | ## Layers and Assets panels From ee6ca15ccfacd5cef78cc41c5ef9671dd4316a79 Mon Sep 17 00:00:00 2001 From: Carbocode Date: Fri, 30 Oct 2026 11:12:57 +0100 Subject: [PATCH 040/102] M8: join and round layer hierarchy highlights --- crates/ui-egui/src/layers_behaviour_tests.rs | 109 +++++++++++++++++++ crates/ui-egui/src/panels/layers.rs | 32 +++++- crates/ui-egui/src/theme.rs | 2 +- docs/ui-parity.md | 5 +- 4 files changed, 140 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/layers_behaviour_tests.rs b/crates/ui-egui/src/layers_behaviour_tests.rs index 7cf0bf235..0c28ede87 100644 --- a/crates/ui-egui/src/layers_behaviour_tests.rs +++ b/crates/ui-egui/src/layers_behaviour_tests.rs @@ -51,6 +51,115 @@ fn sorted(mut v: Vec) -> Vec { v } +#[test] +fn selected_hierarchies_have_continuous_rounded_backgrounds() { + let mut s = Session::new(); + let frame = id(s.execute("frame.create", &json!({"name": "Selected frame"})).unwrap()); + let child = rect(&mut s, "child", 0.0, Some(frame)); + let group = id(s.execute("object.group", &json!({"ids": [child]})).unwrap()); + rect(&mut s, "sibling", 30.0, Some(frame)); + let other = id(s.execute("frame.create", &json!({"name": "Other frame"})).unwrap()); + rect(&mut s, "other child", 0.0, Some(other)); + s.execute("select.set", &json!({"ids": [frame, group, other]})).unwrap(); + let mut u = Ui::new(s); + u.app.ui.expanded.extend([frame, group, other]); + let selected_rows = [frame, group, other].map(|id| u.row_at(id)); + let out = u.frame_output(vec![Event::PointerGone]); + let t = crate::theme::Tokens::get(&u.ctx); + for pos in selected_rows { + let rect_at = |fill| { + out.shapes.iter().enumerate().find_map(|(i, s)| match &s.shape { + egui::Shape::Rect(r) if r.fill == fill && r.rect.contains(pos) => Some(i), + _ => None, + }) + }; + let background = rect_at(t.selected_row_child).expect("the selected row belongs to the hierarchy background"); + let highlight = rect_at(t.selected_row).expect("each selected frame or group has its own highlight"); + assert!(highlight > background, "the selected highlight is painted above the hierarchy background"); + } + let backgrounds: Vec<_> = out + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Rect(r) if r.fill == t.selected_row_child => Some(r), + _ => None, + }) + .collect(); + // Other frame + child, then selected frame + sibling + selected group + child. + assert_eq!(backgrounds.len(), 6); + for band in [&backgrounds[..2], &backgrounds[2..]] { + assert_eq!(band.first().unwrap().corner_radius.nw, 5); + assert_eq!(band.last().unwrap().corner_radius.sw, 5); + for pair in band.windows(2) { + assert_eq!(pair[0].rect.bottom(), pair[1].rect.top(), "the highlight fills the inter-row spacing"); + assert_eq!(pair[0].corner_radius.sw, 0, "no rounded seams inside the hierarchy"); + assert_eq!(pair[1].corner_radius.nw, 0, "a selected nested group stays in the same block"); + } + } + assert!(backgrounds[1].rect.bottom() < backgrounds[2].rect.top(), "separate selected hierarchies stay separate"); + // A collapsed frame and a filtered leaf each have all four corners rounded. + u.app.ui.expanded.clear(); + let out = u.frame_output(vec![]); + let collapsed: Vec<_> = out + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Rect(r) if r.fill == t.selected_row_child => Some(r), + _ => None, + }) + .collect(); + assert_eq!(collapsed.len(), 2); + assert!(collapsed.iter().all(|r| r.corner_radius == egui::CornerRadius::same(5))); + u.app.ui.layer_filter = "child".into(); + let out = u.frame_output(vec![]); + assert!(out.shapes.iter().any(|s| matches!(&s.shape, + egui::Shape::Rect(r) if r.fill == t.selected_row_child && r.corner_radius.sw == 5 + ))); +} + +#[test] +fn selected_hierarchy_keeps_square_seams_when_scrolled() { + let mut s = Session::new(); + let frame = id(s.execute("frame.create", &json!({"name": "Long hierarchy"})).unwrap()); + for i in 0..70 { + rect(&mut s, &format!("Child {i}"), 0.0, Some(frame)); + } + s.execute("select.set", &json!({"ids": [frame]})).unwrap(); + let mut u = Ui::new(s); + u.app.ui.expanded.insert(frame); + let fill = crate::theme::Tokens::get(&u.ctx).selected_row_child; + let corners = |out: &egui::FullOutput| { + out.shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Rect(r) if r.fill == fill && r.rect.intersects(s.clip_rect) => Some(r.corner_radius), + _ => None, + }) + .collect::>() + }; + let wheel = |y| Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, y), + modifiers: Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + }; + u.frame(vec![Event::PointerMoved(egui::pos2(150.0, 500.0)), wheel(-700.0)]); + for _ in 0..30 { + u.frame(vec![]); + } + let middle = corners(&u.frame_output(vec![])); + assert!(!middle.is_empty()); + assert!(middle.iter().all(|c| *c == egui::CornerRadius::ZERO), "viewport edges inside a subtree are square seams"); + u.frame(vec![wheel(-10000.0)]); + for _ in 0..30 { + u.frame(vec![]); + } + let end = corners(&u.frame_output(vec![])); + assert_eq!(end.first().unwrap().nw, 0, "the hierarchy starts above the viewport"); + assert_eq!(end.last().unwrap().sw, 5, "the hierarchy's real end stays rounded"); +} + #[test] fn clicking_rows_selects_by_the_documented_rules() { let (mut u, [a, b, c, d]) = four(); diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 164ec7e4a..244f95805 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -956,15 +956,33 @@ fn reveal_selection(app: &mut FigApp, doc: &Document, page: NodeId, sel: &[NodeI reveal } +/// The outermost selected layer owning a row's continuous hierarchy highlight. +fn selection_root(doc: &Document, sel: &[NodeId], id: NodeId) -> Option { + doc.ancestors(id).into_iter().rev().find(|a| sel.contains(a)).or_else(|| sel.contains(&id).then_some(id)) +} + +fn hierarchy_bg(doc: &Document, sel: &[NodeId], rows: &[Row], i: usize, mut rr: Rect, gap: f32) -> Option<(Rect, CornerRadius)> { + let root = selection_root(doc, sel, rows.get(i)?.id)?; + // Look beyond the viewport too: scrolling must not round an edge in the + // middle of a selected subtree. Separate selected subtrees keep their corners. + let joins = |neighbor: &Row| selection_root(doc, sel, neighbor.id) == Some(root); + let above = i.checked_sub(1).and_then(|j| rows.get(j)).is_some_and(joins); + let below = rows.get(i + 1).is_some_and(joins); + if below { + rr.max.y += gap; + } + let top = if above { 0 } else { 5 }; + let bottom = if below { 0 } else { 5 }; + Some((rr, CornerRadius { nw: top, ne: top, sw: bottom, se: bottom })) +} + /// A row's background: selected, inside a selected layer, or outlined when hovered. /// `state` is [selected, in_selected, component]. fn paint_row_bg(ui: &Ui, t: &Tokens, rr: Rect, state: [bool; 3], hovered: bool) { let [selected, in_selected, is_comp] = state; if selected { ui.painter().rect_filled(rr, CornerRadius::same(5), if is_comp { t.component_row } else { t.selected_row }); - } else if in_selected { - ui.painter().rect_filled(rr, CornerRadius::ZERO, t.selected_row_child); - } else if hovered { + } else if !in_selected && hovered { ui.painter().rect_stroke(rr, CornerRadius::same(5), Stroke::new(1.0, if is_comp { COMPONENT } else { ACCENT }), egui::StrokeKind::Inside); } } @@ -1070,7 +1088,7 @@ fn layers(app: &mut FigApp, ui: &mut Ui) { // Stable widget ids for a row wherever the list is scrolled. band_ui.skip_ahead_auto_ids(first); let ui = &mut band_ui; - for row in rows.iter().take(last).skip(first) { + for (i, row) in rows.iter().enumerate().take(last).skip(first) { let Some(n) = doc.node(row.id) else { continue }; let (r, resp) = ui.allocate_exact_size(vec2(w, ROW), Sense::click_and_drag()); let selected = sel.contains(&row.id); @@ -1087,9 +1105,13 @@ fn layers(app: &mut FigApp, ui: &mut Ui) { locked: n.locked, }; a11y::tree_item(&resp, if n.name.is_empty() { tr(n.kind.label()) } else { &n.name }, &info); - let in_selected = !selected && doc.ancestors(row.id).iter().any(|a| sel.contains(a)); let is_comp = matches!(n.kind, NodeKind::Component { .. } | NodeKind::ComponentSet { .. } | NodeKind::Instance { .. }); let rr = r.shrink2(vec2(8.0, 0.0)); + let bg = hierarchy_bg(&doc, &sel, &rows, i, rr, pitch - ROW); + let in_selected = !selected && bg.is_some(); + if let Some((rect, corners)) = bg { + ui.painter().rect_filled(rect, corners, t.selected_row_child); + } a11y::ring_around(ui, rr, &resp); // Over the row, its eye and padlock included (they sit on top of it). let over = resp.contains_pointer(); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 200dd72bc..cddd89d09 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -493,7 +493,7 @@ mod tests { let theme = if t.dark { "dark" } else { "light" }; // Disabled text (a disabled button's label, placeholders) on panels, fields and // selected rows, still dimmer than secondary text. - for bg in [t.panel, t.field, t.hover, t.selected_row] { + for bg in [t.panel, t.field, t.hover, t.selected_row, t.selected_row_child] { let ratio = c(t.text_tertiary).contrast(c(bg)); assert!(ratio >= 3.0, "{theme}: dim text {:?} on {bg:?} is {ratio:.2}:1", t.text_tertiary); assert!(ratio < c(t.text_secondary).contrast(c(bg)), "{theme}: dim text reads dimmer than secondary text"); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index cc0fc9db8..f30e46409 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (continuous, rounded layer hierarchy selection (M8); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -39,7 +39,7 @@ interaction feel not yet compared. | Item | Status | Notes | |---|---|---| -| Rows: click, Shift-click range, Cmd/Ctrl-click toggle; the selection follows on the canvas and a canvas selection is revealed | done | `layers_behaviour_tests` | +| Rows: click, Shift-click range, Cmd/Ctrl-click toggle; the selection follows on the canvas and a canvas selection is revealed | done | `layers_behaviour_tests`; selected hierarchies share a continuous background with rounded outer corners, including nested selections | | Expand and collapse: Alt-click opens or closes everything inside; Collapse layers (Alt+L) keeps the way to the selection open | done | Alt-click pinned (the documentation is silent) | | Drag to reorder and into frames, groups and auto layout: insertion line, spring-loaded open, several layers together, Escape cancels | done | several layers dropped together land together (they split apart before); instances and a layer's own children refuse drops | | Eye and padlock: click, or drag across rows to set several in one step; layers in a locked frame show a faint padlock | done | the toggles no longer vanish under the pointer (clicks on them could miss) | @@ -178,6 +178,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | M8: selected layer hierarchies have a continuous background across row spacing, with rounded outer corners; nested selections stay in the same block and separate selected trees keep their own corners. Regressions cover continuous fills, the selected-row highlight above them, scrolling and the original palette's dim-text contrast. Numbers unchanged. | | 2026-11-02 | patch | M8, #1875: a click with the Bend tool on a sharp point between two segments gives it handles along the line between its neighbours, a third of the way to each ("Click on a point or path where you want to add a curve", Edit vector layers); a click on a curved point still makes it sharp, a drag still sets the handles by hand, an endpoint is left alone. Between a handle's end and a point both within reach of the pointer, the nearer one on the page is hit (the handle on a tie), so a short path's point (its handles a few pixels long) can be clicked again. Before, only a drag curved a point, and a short one left two tiny handles in its direction. Tests: `vectoredit::tests::short_handles_leave_their_point_clickable`, `vectoredit::tests::a_bend_click_curves_a_sharp_point_between_its_neighbours`, `bend_tool_smooths_and_sharpens_points`. Numbers unchanged. | | 2026-11-02 | minor | M4, #1827: wrap style on a text layer (`WrapStyle`: Auto, Balance, Pretty): Balance re-breaks each paragraph at the narrowest width that keeps its line count (bisection over the greedy breaker, as browsers balance), Pretty narrows one of the last four lines just enough so the last line isn't one word; `text.wrapStyle`, `node.set wrapStyle` (`textWrap` too), inspect `wrapStyle`, Dev Mode CSS `text-wrap` (Tailwind `text-balance` / `text-pretty`), the Type settings control under Vertical trim. Per-paragraph settings, text-style support and the `.fig` import/export mapping stay open. Test: `text_behaviour_tests::balance_and_pretty_wrap_styles_break_lines_as_documented`. | | 2026-11-02 | patch | M4: Backspace or Delete at the start of a list item takes its marker and keeps its level ("Use Backspace or Delete at the beginning of a list item to delete the counter, but keep the same level of indentation", Create bulleted and numbered lists): a plain paragraph may now carry a list level, and the text layout starts it where that level's item text starts (the gutters stay even when no list is left). Backspace used to drop the level too, and Delete at an item's start deleted the next character. Tab on such a paragraph types a tab, as outside a list. Tests: `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests::a_plain_paragraph_at_a_list_level_starts_where_the_items_text_does` | From 901bc6d4fc6a2297289a04d600be22bc05bbc2d5 Mon Sep 17 00:00:00 2001 From: Carbocode Date: Mon, 2 Nov 2026 10:52:52 +0100 Subject: [PATCH 041/102] M8: compute layer selection roots once per visible row --- crates/ui-egui/src/panels/layers.rs | 26 ++++++++++++++++---------- docs/ui-parity.md | 3 ++- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 244f95805..1fc89d1d9 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -957,17 +957,18 @@ fn reveal_selection(app: &mut FigApp, doc: &Document, page: NodeId, sel: &[NodeI } /// The outermost selected layer owning a row's continuous hierarchy highlight. -fn selection_root(doc: &Document, sel: &[NodeId], id: NodeId) -> Option { +fn selection_root(doc: &Document, sel: &BTreeSet, id: NodeId) -> Option { + if sel.is_empty() { + return None; + } doc.ancestors(id).into_iter().rev().find(|a| sel.contains(a)).or_else(|| sel.contains(&id).then_some(id)) } -fn hierarchy_bg(doc: &Document, sel: &[NodeId], rows: &[Row], i: usize, mut rr: Rect, gap: f32) -> Option<(Rect, CornerRadius)> { - let root = selection_root(doc, sel, rows.get(i)?.id)?; - // Look beyond the viewport too: scrolling must not round an edge in the - // middle of a selected subtree. Separate selected subtrees keep their corners. - let joins = |neighbor: &Row| selection_root(doc, sel, neighbor.id) == Some(root); - let above = i.checked_sub(1).and_then(|j| rows.get(j)).is_some_and(joins); - let below = rows.get(i + 1).is_some_and(joins); +fn hierarchy_bg(roots: &[Option], i: usize, mut rr: Rect, gap: f32) -> Option<(Rect, CornerRadius)> { + let root = roots.get(i).copied().flatten()?; + let joins = |neighbor: &Option| *neighbor == Some(root); + let above = i.checked_sub(1).and_then(|j| roots.get(j)).is_some_and(joins); + let below = roots.get(i + 1).is_some_and(joins); if below { rr.max.y += gap; } @@ -1083,6 +1084,11 @@ fn layers(app: &mut FigApp, ui: &mut Ui) { drag_autoscroll(ui, dragging.is_some()); let first = ((viewport.min.y / pitch).floor().max(0.0) as usize).min(rows.len()); let last = ((viewport.max.y / pitch).ceil().max(0.0) as usize).saturating_add(1).min(rows.len()); + // Compute each visible row's root once, plus one neighbor outside each end + // so scrolling never rounds a seam in the middle of a selected subtree. + let selected_ids: BTreeSet<_> = sel.iter().copied().collect(); + let roots_start = first.saturating_sub(1); + let roots: Vec<_> = rows.iter().take(last.saturating_add(1)).skip(roots_start).map(|r| selection_root(&doc, &selected_ids, r.id)).collect(); let band = Rect::from_x_y_ranges(ui.max_rect().x_range(), (top + first as f32 * pitch)..=(top + last as f32 * pitch)); let mut band_ui = ui.new_child(egui::UiBuilder::new().max_rect(band)); // Stable widget ids for a row wherever the list is scrolled. @@ -1091,7 +1097,7 @@ fn layers(app: &mut FigApp, ui: &mut Ui) { for (i, row) in rows.iter().enumerate().take(last).skip(first) { let Some(n) = doc.node(row.id) else { continue }; let (r, resp) = ui.allocate_exact_size(vec2(w, ROW), Sense::click_and_drag()); - let selected = sel.contains(&row.id); + let selected = selected_ids.contains(&row.id); a11y::layer_row(&mut app.ui.nav, &resp); if sel.last() == Some(&row.id) { a11y::prefer(&mut app.ui.nav, Region::Layers, resp.id); @@ -1107,7 +1113,7 @@ fn layers(app: &mut FigApp, ui: &mut Ui) { a11y::tree_item(&resp, if n.name.is_empty() { tr(n.kind.label()) } else { &n.name }, &info); let is_comp = matches!(n.kind, NodeKind::Component { .. } | NodeKind::ComponentSet { .. } | NodeKind::Instance { .. }); let rr = r.shrink2(vec2(8.0, 0.0)); - let bg = hierarchy_bg(&doc, &sel, &rows, i, rr, pitch - ROW); + let bg = hierarchy_bg(&roots, i - roots_start, rr, pitch - ROW); let in_selected = !selected && bg.is_some(); if let Some((rect, corners)) = bg { ui.painter().rect_filled(rect, corners, t.selected_row_child); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f30e46409..57c0c4993 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (continuous, rounded layer hierarchy selection (M8); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (reuse visible layer selection roots (M8); continuous, rounded layer hierarchy selection (M8); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -178,6 +178,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | M8: layer hierarchy backgrounds compute each visible row's selection root once, plus its immediate offscreen neighbors, rather than walking ancestors three times per row. Selection membership uses a set instead of a linear search. The scrolling regression keeps the internal seams square at viewport boundaries. Numbers unchanged. | | 2026-11-02 | minor | M8: selected layer hierarchies have a continuous background across row spacing, with rounded outer corners; nested selections stay in the same block and separate selected trees keep their own corners. Regressions cover continuous fills, the selected-row highlight above them, scrolling and the original palette's dim-text contrast. Numbers unchanged. | | 2026-11-02 | patch | M8, #1875: a click with the Bend tool on a sharp point between two segments gives it handles along the line between its neighbours, a third of the way to each ("Click on a point or path where you want to add a curve", Edit vector layers); a click on a curved point still makes it sharp, a drag still sets the handles by hand, an endpoint is left alone. Between a handle's end and a point both within reach of the pointer, the nearer one on the page is hit (the handle on a tie), so a short path's point (its handles a few pixels long) can be clicked again. Before, only a drag curved a point, and a short one left two tiny handles in its direction. Tests: `vectoredit::tests::short_handles_leave_their_point_clickable`, `vectoredit::tests::a_bend_click_curves_a_sharp_point_between_its_neighbours`, `bend_tool_smooths_and_sharpens_points`. Numbers unchanged. | | 2026-11-02 | minor | M4, #1827: wrap style on a text layer (`WrapStyle`: Auto, Balance, Pretty): Balance re-breaks each paragraph at the narrowest width that keeps its line count (bisection over the greedy breaker, as browsers balance), Pretty narrows one of the last four lines just enough so the last line isn't one word; `text.wrapStyle`, `node.set wrapStyle` (`textWrap` too), inspect `wrapStyle`, Dev Mode CSS `text-wrap` (Tailwind `text-balance` / `text-pretty`), the Type settings control under Vertical trim. Per-paragraph settings, text-style support and the `.fig` import/export mapping stay open. Test: `text_behaviour_tests::balance_and_pretty_wrap_styles_break_lines_as_documented`. | From 692c4545ba2dcf31a405fd7c28cdaac9d13e813d Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:41:15 +0100 Subject: [PATCH 042/102] M4: weight steps read Univers numbers (45 Light, 57 Condensed) by weight within their width (#1831) --- crates/engine/src/cmd/text.rs | 95 +++++++++++++-------- crates/engine/src/text_weight_step_tests.rs | 32 +++++++ 2 files changed, 92 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 392fd4636..2ef66c519 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -135,46 +135,65 @@ fn number_weight(word: &str) -> Option { (100..=1000).contains(&n).then_some(n) } +/// Style-name words that give a weight or a slant. +const WEIGHT_WORDS: [&str; 25] = [ + "thin", + "hairline", + "extralight", + "ultralight", + "light", + "semilight", + "demilight", + "regular", + "normal", + "roman", + "book", + "medium", + "semibold", + "demibold", + "bold", + "extrabold", + "ultrabold", + "black", + "extrablack", + "ultrablack", + "heavy", + "italic", + "oblique", + "plain", + "standard", +]; + +/// Words that grade the weight word after them ("Extra Bold") but a width otherwise ("Extra Condensed"). +const GRADES: [&str; 4] = ["extra", "ultra", "semi", "demi"]; + +/// The width a Univers number leading a style name gives, as Univers, Frutiger and Helvetica Neue +/// LT name styles ("45 Light", "55 Roman", "57 Condensed", "67 Bold Condensed"): the first digit +/// grades the weight, the second the width (3 or 4 extended, 5 or 6 normal, 7 or 8 condensed, 9 +/// ultra condensed; even is italic, which the name says too). Only before weight, slant and width +/// words, so another leading number ("12 Regular", "55 Rounded") stays part of the width. +fn univers_width(words: &[&str]) -> Option { + const WIDTHS: [&str; 6] = ["condensed", "compressed", "narrow", "extended", "expanded", "wide"]; + let (code, rest) = words.split_first()?; + let &[b'1'..=b'9', d @ b'3'..=b'9'] = code.as_bytes() else { return None }; + let known = |w: &&str| WEIGHT_WORDS.contains(w) || GRADES.contains(w) || WIDTHS.contains(w); + (!rest.is_empty() && rest.iter().all(known)).then_some((d - b'1') / 2) +} + /// What a style name says besides its weight and slant ("Narrow Bold Italic" → "narrow", -/// "Extra Condensed Bold" → "extra condensed"). +/// "Extra Condensed Bold" → "extra condensed", "67 Bold Condensed" → its Univers width and "condensed"). fn style_rest(style: &str) -> String { - const WEIGHTS: [&str; 25] = [ - "thin", - "hairline", - "extralight", - "ultralight", - "light", - "semilight", - "demilight", - "regular", - "normal", - "roman", - "book", - "medium", - "semibold", - "demibold", - "bold", - "extrabold", - "ultrabold", - "black", - "extrablack", - "ultrablack", - "heavy", - "italic", - "oblique", - "plain", - "standard", - ]; - // Words that grade the weight word after them ("Extra Bold") but a width otherwise ("Extra Condensed"). - const GRADES: [&str; 4] = ["extra", "ultra", "semi", "demi"]; let s = style.to_ascii_lowercase().replace('-', " "); let words: Vec<&str> = s.split_whitespace().collect(); - let weight = |w: &str| WEIGHTS.contains(&w) || w_number(w).or_else(|| number_weight(w)).is_some(); + let weight = |w: &str| WEIGHT_WORDS.contains(&w) || w_number(w).or_else(|| number_weight(w)).is_some(); let rest = words.iter().enumerate().filter(|(i, w)| { let graded = GRADES.contains(w) && words.get(i + 1).is_some_and(|next| weight(next) && !matches!(*next, "italic" | "oblique")); !weight(w) && !graded }); - rest.map(|(_, w)| *w).collect::>().join(" ") + let univers = univers_width(&words).map(|d| format!("univers width {d}")); + // The Univers number (the first word kept) gives way to its width. + let rest = rest.map(|(_, w)| *w).skip(usize::from(univers.is_some())); + univers.as_deref().into_iter().chain(rest).collect::>().join(" ") } /// A style name that slants: italic, or oblique as some families name it. @@ -183,10 +202,16 @@ fn slanted(style: &str) -> bool { s.contains("italic") || s.contains("oblique") } -/// The weight a style name says ("W3", "W6 Italic", "Condensed W7" and "Condensed 600" too). +/// The weight a style name says ("W3", "W6 Italic", "Condensed W7", "Condensed 600" and "45 Light" too). pub(crate) fn name_weight(style: &str) -> u16 { - let words = style.to_ascii_lowercase().replace('-', " "); - words.split_whitespace().find_map(|w| w_number(w).or_else(|| number_weight(w))).unwrap_or_else(|| figcraft_doc::style_weight(style)) + let s = style.to_ascii_lowercase().replace('-', " "); + let words: Vec<&str> = s.split_whitespace().collect(); + // A Univers number's weight digit has no fixed CSS weight ("65" is Medium in Helvetica Neue, + // Bold in Univers): the words after it say it. + if let Some((_, rest)) = words.split_first().filter(|_| univers_width(&words).is_some()) { + return figcraft_doc::style_weight(&rest.join(" ")); + } + words.iter().find_map(|w| w_number(w).or_else(|| number_weight(w))).unwrap_or_else(|| figcraft_doc::style_weight(style)) } /// The next heavier (`up`) or lighter style of `styles` (a family's with the weight each is listed diff --git a/crates/engine/src/text_weight_step_tests.rs b/crates/engine/src/text_weight_step_tests.rs index 057a0a4e5..a6c465789 100644 --- a/crates/engine/src/text_weight_step_tests.rs +++ b/crates/engine/src/text_weight_step_tests.rs @@ -91,6 +91,38 @@ fn number_weights_count_after_a_width_but_other_numbers_dont() { assert_eq!(walk(&optical, "Caption 24 Bold", false), ["Caption 24 Regular"]); } +#[test] +fn univers_numbers_step_by_weight_within_their_width() { + // Helvetica Neue LT, Univers, Frutiger: the first digit grades the weight, the second the width. + let hn = weighed(&[ + ("45 Light", 300), + ("46 Light Italic", 300), + ("55 Roman", 400), + ("56 Italic", 400), + ("57 Condensed", 400), + ("65 Medium", 500), + ("67 Medium Condensed", 500), + ("75 Bold", 700), + ("76 Bold Italic", 700), + ("77 Bold Condensed", 700), + ]); + assert_eq!(walk(&hn, "55 Roman", true), ["65 Medium", "75 Bold"]); + assert_eq!(walk(&hn, "65 Medium", false), ["55 Roman", "45 Light"]); + assert_eq!(walk(&hn, "57 Condensed", true), ["67 Medium Condensed", "77 Bold Condensed"]); + assert_eq!(walk(&hn, "67 Medium Condensed", false), ["57 Condensed"]); + assert_eq!(walk(&hn, "46 Light Italic", true), ["56 Italic", "76 Bold Italic"]); + // Faces not read yet: the words after the number give the weight. + let univers = styles(&["45 Light", "55 Roman", "65 Bold", "75 Black", "57 Condensed", "67 Bold Condensed"]); + assert_eq!(walk(&univers, "45 Light", true), ["55 Roman", "65 Bold", "75 Black"]); + assert_eq!(walk(&univers, "67 Bold Condensed", false), ["57 Condensed"]); + assert_eq!((name_weight("45 Light"), name_weight("75 Black"), name_weight("57 Condensed")), (300, 900, 400)); + // Other leading numbers stay part of the width: before another word, or not a width digit. + let other = styles(&["12 Regular", "12 Bold", "55 Rounded", "55 Rounded Bold", "Regular", "Bold"]); + assert_eq!(walk(&other, "12 Regular", true), ["12 Bold"]); + assert_eq!(walk(&other, "55 Rounded", true), ["55 Rounded Bold"]); + assert_eq!(walk(&other, "Regular", true), ["Bold"]); +} + #[test] fn a_custom_weight_axis_value_steps_from_where_it_is() { let family = styles(&["Light", "Regular", "Medium", "Bold"]); From bb7d568d4962574e4705450321f6b9a9f2613ba5 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 3 Nov 2026 09:13:19 -0500 Subject: [PATCH 043/102] M2: baseline alignment puts a layer without text on the line with its bottom (#1825) In the baseline branch of the flow layout only an item with a text baseline got one; any other layer stayed at the top of the line. A layer without a text baseline now uses its bottom edge, as the help center's figure shows ("the bottoms of the icon and the word home are aligned on the red line"): an icon next to a text sits on the text's baseline, a layer reaching below it moves the text down, and a line with no text lines the layers' bottoms up (CSS does the same). Tests: alignment_rules (three cases), baseline_alignment_horizontal, engine baseline_alignment_puts_an_icons_bottom_on_the_text_baseline. Docs: auto-layout-parity row, status line and revision history. Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/cmd/layout.rs | 24 ++++++++++++++++++++++++ crates/layout/src/behaviour_tests.rs | 26 +++++++++++++++++++++++--- crates/layout/src/lib.rs | 8 ++++++-- crates/layout/src/tests.rs | 5 +++-- docs/auto-layout-parity.md | 5 +++-- 5 files changed, 59 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 6972a6780..fc40cee88 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -215,6 +215,30 @@ mod tests { assert_eq!(x(&s, small).0, x(&s, big).0); } + /// "for baseline alignment, the bottoms of the icon and the word home are aligned on the red + /// line" (Use the horizontal and vertical flows in auto layout, the figure's caption; #1825): a + /// layer without text sits on the text's baseline with its bottom edge, not at the top. + #[test] + fn baseline_alignment_puts_an_icons_bottom_on_the_text_baseline() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 100, "props": {"layout": "horizontal", "gap": 8}}))); + let icon = id(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 16, "height": 16, "parent": f}))); + let home = id(&ex(&mut s, "text.create", json!({"text": "Home", "x": 0, "y": 0, "parent": f, "props": {"fontSize": 48}}))); + ex(&mut s, "node.set", json!({"id": f, "props": {"crossAlign": "baseline"}})); + let base = figcraft_text::layout_node(&node(&s, home)).and_then(|(l, dy)| l.lines.first().map(|line| line.baseline + dy)); + // Only meaningful when the text was measured (fonts available) and its baseline is below + // the icon's height. + if let Some(b) = base + && b > 16.0 + { + let bottom = x(&s, icon).1 + 16.0; + assert!((bottom - (x(&s, home).1 + b)).abs() < 1e-6, "icon bottom {bottom}, text baseline {}", x(&s, home).1 + b); + } + // Top alignment puts it back at the top. + ex(&mut s, "node.set", json!({"id": f, "props": {"crossAlign": "min"}})); + assert_eq!(x(&s, icon).1, x(&s, home).1); + } + #[test] fn grid_tracks_cells_and_undo() { let mut s = Session::new(); diff --git a/crates/layout/src/behaviour_tests.rs b/crates/layout/src/behaviour_tests.rs index bba20c532..50dcc79ad 100644 --- a/crates/layout/src/behaviour_tests.rs +++ b/crates/layout/src/behaviour_tests.rs @@ -535,12 +535,32 @@ fn alignment_rules() { rects: &[(0.0, 10.0, 30.0, 14.0), (35.0, 0.0, 60.0, 28.0)], }, Case { - // Docs silent on layers without text: they keep to the top of the line. - rule: "baseline alignment: a layer without text sits at the top", + // "for baseline alignment, the bottoms of the icon and the word home are aligned on + // the red line" (the figure's caption): a layer without text sits on the baseline with + // its bottom edge. Baseline 20, icon 10 high: the icon moves down 10 (#1825). + rule: "baseline alignment: a layer without text puts its bottom on the baseline", frame: Frame { sizing: (Hug, Hug), cross: CrossAlign::Baseline, ..FRAME }, kids: &[kid(10.0, 10.0), Kid { text: Some((60.0, 28.0, 20.0)), sizing: (Hug, Hug), ..KID }], want: (70.0, 28.0), - rects: &[(0.0, 0.0, 10.0, 10.0), (10.0, 0.0, 60.0, 28.0)], + rects: &[(0.0, 10.0, 10.0, 10.0), (10.0, 0.0, 60.0, 28.0)], + }, + Case { + // The icon (30 high) reaches below the text's baseline (20): the line's baseline is the + // icon's bottom, so the text moves down 10 and the frame hugs 10 + 28. + rule: "baseline alignment: a layer taller than the baseline moves the text down", + frame: Frame { sizing: (Hug, Hug), cross: CrossAlign::Baseline, ..FRAME }, + kids: &[kid(10.0, 30.0), Kid { text: Some((60.0, 28.0, 20.0)), sizing: (Hug, Hug), ..KID }], + want: (70.0, 38.0), + rects: &[(0.0, 0.0, 10.0, 30.0), (10.0, 10.0, 60.0, 28.0)], + }, + Case { + // Docs silent on a line with no text at all: every layer's baseline is its bottom + // edge (as the icon's), so the bottoms line up, as they do under CSS baseline alignment. + rule: "baseline alignment without text: the layers' bottoms line up", + frame: Frame { sizing: (Hug, Hug), cross: CrossAlign::Baseline, ..FRAME }, + kids: &[kid(10.0, 10.0), kid(10.0, 30.0)], + want: (20.0, 30.0), + rects: &[(0.0, 20.0, 10.0, 10.0), (10.0, 0.0, 10.0, 30.0)], }, ]); } diff --git a/crates/layout/src/lib.rs b/crates/layout/src/lib.rs index 19de84afb..65049eb01 100644 --- a/crates/layout/src/lib.rs +++ b/crates/layout/src/lib.rs @@ -332,7 +332,8 @@ struct Item { /// inside stroke): fill children share the free space by their content area, border-box /// fashion, so these come on top of each one's share. inset_main: f64, - /// Baseline alignment: distance from the item's top to its first baseline. + /// Baseline alignment: distance from the item's top to its first text baseline, or to its + /// bottom edge when it has no text (an icon next to a text sits on the line with its bottom). baseline: Option, /// Baseline alignment: offset from the line's top (computed per line). base_off: f64, @@ -555,8 +556,11 @@ pub fn layout_frame(doc: &mut Document, frame: NodeId, m: &dyn Measure) { it.cross = if horizontal { h } else { w }; } if baseline { + // A layer without a text baseline (an icon, a shape, a frame holding no text) sits on the + // line with its bottom edge: "the bottoms of the icon and the word home are aligned on the + // red line" (Use the horizontal and vertical flows in auto layout; #1825). for it in items.iter_mut().filter(|it| !it.fill_cross) { - it.baseline = item_baseline(doc, it.id, m, 0); + it.baseline = item_baseline(doc, it.id, m, 0).or(Some(it.cross)); } } diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 0af9861b8..fa215b799 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -302,10 +302,11 @@ fn baseline_alignment_horizontal() { let rect = d.create(f, NodeKind::Rectangle, "R", 0.0, 0.0, 10.0, 20.0).unwrap(); let m = FakeMeasure([(small, (30.0, 14.0, 10.0)), (big, (60.0, 40.0, 30.0))].into_iter().collect()); layout_frame(&mut d, f, &m); - // Baselines line up at 5 + 30; the rectangle (no baseline) sits at the top. + // Baselines line up at 5 + 30; the rectangle (no text baseline) sits on it with its bottom + // edge: 35 - 20 (#1825). assert_eq!(pos(&d, small).1, 25.0); assert_eq!(pos(&d, big).1, 5.0); - assert_eq!(pos(&d, rect).1, 5.0); + assert_eq!(pos(&d, rect).1, 15.0); // Hug height covers the shifted small text: max(20 + 14, 40) + padding. assert_eq!(d.node(f).unwrap().height, 50.0); // Nested auto layout frames align on their first child's baseline. diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index 3b5466b2c..3f49f3008 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -1,6 +1,6 @@ # Auto layout and constraints parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-02 · **Change:** patch (fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-03 · **Change:** patch (baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) Auto layout is the most used layout feature in Figma and the one where small differences (a hugging frame one pixel off, text wrapping at another width) break real files. **Breadth ~98%, @@ -60,7 +60,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | An auto gap stops at 0 when children don't fit (no overlap) | **fixed** | went negative before | | Alignment 3×3; with an auto gap only the cross alignment; a hugging frame shows no difference | pass | `alignment_rules` | | Text baseline alignment, texts of different sizes | pass | `alignment_rules` | -| Baseline alignment of a layer without text (an icon next to text) | silent | it keeps to the top of the line | +| Baseline alignment of a layer without text (an icon next to text) | **fixed** | its bottom sits on the baseline, as the figure's caption says ("the bottoms of the icon and the word home are aligned on the red line"); it kept to the top of the line (#1825) | | Horizontal wrap: a new row when the width runs out; gap between rows | pass | `wrap_rules` | | Vertical wrap: a new column when the height runs out; not masonry; gap between columns | **added** | layout, Design panel wrap toggle, column gap field, on-canvas gap handles, drag reorder and arrow keys by column | | Wrapped rows/columns as a block: packed at the start, centre or end the cross alignment names; stretched when every child fills across the flow; or the free space between them (one line or no free space: like packed) | **added** | `content_align_tests` (13 cases), `al_content_align_tests`; `contentAlign`, the Row/Column gap mode in the Design panel, REST and `.fig` both ways, `align-content` in CSS | @@ -100,6 +100,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Date | Change | Summary | |---|---|---| +| 2026-11-03 | patch | M2, #1825: baseline alignment of a layer without text (an icon next to a text) puts its bottom on the line's baseline, as the help center's figure shows ("the bottoms of the icon and the word home are aligned on the red line"); it kept to the top of the line. A layer reaching below the text's baseline moves the text down, and a line with no text lines the layers' bottoms up (the documentation is silent; CSS baseline alignment does the same). Tests: `alignment_rules` (three cases), engine `baseline_alignment_puts_an_icons_bottom_on_the_text_baseline`. Numbers unchanged. | | 2026-11-02 | patch | M2, #1824: fill container children share the free space by their content area: each one's own insets (padding and an included inside stroke, from the same `insets` the frame uses) come off the free space before the equal split and go back on its share, so a child with more padding or a thicker inside stroke takes a little more and the content areas match ("Figma distributes space amongst fill container children by the children's content area instead of by their size, matching the CSS border-box model", Use auto layout with CSS Flexbox in mind). Min and max still clamp the outer sizes and the frozen-share loop is as it was; children without insets split as before. Test: `nested_tests::fill_children_share_by_content_area` | | 2026-11-02 | patch | M2, #1838: a double-click on an edge of an auto layout frame's bounding box sets Hug contents on that axis, Alt+double-click on an edge of a child's Fill container ("Double-click the vertical or horizontal edge of an auto layout object's bounding box to set it to Hug contents", "Hold ⌥ Option or Alt and double-click ... to set it to Fill container", Guide to auto layout); a vertical edge sizes the width, a horizontal one the height; the Keyboard shortcuts panel lists both gestures. Test: `double_click_tests::a_double_click_on_an_auto_layout_edge_hugs_and_with_alt_fills`. Numbers unchanged. | | 2026-11-02 | patch | M2: a child of an auto layout frame resized to the full space available to it on an axis (the frame's size less its padding: across the flow for any child, along the flow for a lone child) becomes Fill container on that axis, whether by `transform.resize`, the W/H fields or a canvas handle ("Child objects of an auto layout frame will also be set to Fill container if they are manually resized to the full available space of the parent frame", Guide to auto layout). Any other size keeps the axis Fixed as before; beside siblings along the flow, in a hugging or wrapping frame, in a grid and for a layer that ignores the layout nothing changes. Test: `al_behaviour_tests::a_child_resized_to_the_full_available_space_becomes_fill` | From 1354c6bb6f4d70ca3c0ebe0d4479bb3d0df95f34 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 3 Nov 2026 09:23:44 -0500 Subject: [PATCH 044/102] M10: FIGCRAFT_EMBED_SCRIPTS embeds other scripts' craft-fonts faces in a web build (#1902) The browser has no system fonts and the text crate's build script keeps the web catalog to Inter, Noto Sans Georgian, the wordmark and (with FIGCRAFT_EMBED_CJK) Noto Sans CJK, so craft-fonts' Noto Sans Arabic never reached a web build and Persian or Arabic text drew as missing-glyph boxes. FIGCRAFT_EMBED_SCRIPTS names script tags as the manifest lists them (Arab, Hebr, ...); a web build keeps the faces of those scripts as well. The default build is unchanged. Test: web_embeds_other_scripts_faces_only_when_asked (build script). Docs: localization-parity (web fonts paragraph, Arabic row, status line, revision history), translating.md. Co-Authored-By: Claude Fable 5.1 --- crates/text/build.rs | 85 ++++++++++++++++++++++++++++--------- docs/localization-parity.md | 10 +++-- docs/translating.md | 4 +- 3 files changed, 74 insertions(+), 25 deletions(-) diff --git a/crates/text/build.rs b/crates/text/build.rs index ba087983c..c2a1bf4d2 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -3,22 +3,28 @@ //! `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). +//! The other scripts' faces (Noto Sans Arabic, Hebrew, Thai, Devanagari…) stay out of web builds unless +//! `FIGCRAFT_EMBED_SCRIPTS` names their script tags (`Arab,Hebr`, as the manifest's scripts column +//! lists them; #1902). 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_EMBED_SCRIPTS` 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_EMBED_SCRIPTS"); 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 embed_scripts = scripts_from(std::env::var("FIGCRAFT_EMBED_SCRIPTS").ok().as_deref()); + match input_fonts(dir.as_deref(), wasm, required, embed_cjk, &embed_scripts) { Ok(entries) => src.push_str(&entries), Err(e) => println!("cargo::error={e}"), } @@ -29,8 +35,15 @@ fn main() { } } +/// The script tags `FIGCRAFT_EMBED_SCRIPTS` names (comma- or space-separated), trimmed; none when +/// it is unset. +fn scripts_from(var: Option<&str>) -> Vec { + var.unwrap_or_default().split([',', ' ']).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).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 { +/// `embed_scripts`: script tags whose faces a web build keeps as well. +fn input_fonts(dir: Option<&std::path::Path>, wasm: bool, required: bool, embed_cjk: bool, embed_scripts: &[String]) -> Result { let Some(dir) = dir else { return if required { Err("CRAFT_FONTS_REQUIRED is set but CRAFT_FONTS_DIR is missing".into()) } else { Ok(String::new()) }; }; @@ -42,7 +55,7 @@ fn input_fonts(dir: Option<&std::path::Path>, wasm: bool, required: bool, embed_ watch(&path); continue; } - match craft_fonts(dir, manifest, wasm, embed_cjk) { + match craft_fonts(dir, manifest, wasm, embed_cjk, embed_scripts) { Ok(catalog) => { out.push_str(&catalog.entries); faces.extend(catalog.faces); @@ -82,9 +95,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 { +/// to its budgeted families (plus the faces of the scripts in `embed_scripts`), 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, embed_scripts: &[String]) -> Result { 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 +118,12 @@ 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 faces + // of the scripts `FIGCRAFT_EMBED_SCRIPTS` names (an Arabic or Persian document needs Noto Sans + // Arabic, +0.8 MB; the browser has no system fonts to fall back on, #1902). let wordmark = *family == "Archivo" && *style == "SemiBold"; - if wasm && !matches!(*family, "Inter" | "Noto Sans Georgian") && !wordmark && !cjk { + let asked = scripts.split(',').map(str::trim).any(|s| embed_scripts.iter().any(|e| e.eq_ignore_ascii_case(s))); + if wasm && !matches!(*family, "Inter" | "Noto Sans Georgian") && !wordmark && !cjk && !asked { continue; } let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; @@ -161,9 +177,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 +187,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 +205,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 +218,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 +231,33 @@ 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")); + } + + /// #1902: a web build leaves the other scripts' faces out (an Arabic or Persian document shows + /// missing-glyph boxes) unless `FIGCRAFT_EMBED_SCRIPTS` names their script tags; native builds + /// keep every face, as before. + #[test] + fn web_embeds_other_scripts_faces_only_when_asked() { + let f = Fixture::new(); + std::fs::write( + f.0.join("fonts/manifest.txt"), + "Noto Sans Georgian | Regular | fonts/face.ttf | Geor\nNoto Sans Arabic | Regular | fonts/face.ttf | Arab\nNoto Sans Hebrew | Regular | fonts/face.ttf | Hebr\nNoto Sans Symbols | Regular | fonts/face.ttf | Zsym,Latn\n", + ) + .unwrap(); + let families = |c: &Catalog| c.faces.iter().map(|(f, _)| f.clone()).collect::>(); + let web = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &[]).unwrap(); + assert_eq!(families(&web), ["Noto Sans Georgian"], "the web budget: Georgian only"); + let arabic = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &["Arab".to_string()]).unwrap(); + assert_eq!(families(&arabic), ["Noto Sans Georgian", "Noto Sans Arabic"]); + // Several tags, any case, spaces, and a tag among a face's several scripts. + let more = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &scripts_from(Some(" hebr, LATN "))).unwrap(); + assert_eq!(families(&more), ["Noto Sans Georgian", "Noto Sans Hebrew", "Noto Sans Symbols"]); + // Native builds keep every face whatever the variable says. + assert_eq!(craft_fonts(&f.0, "fonts/manifest.txt", false, false, &[]).unwrap().faces.len(), 4); + // The variable reaches the catalog through `input_fonts`. + assert!(input_fonts(Some(&f.0), true, false, false, &["Arab".into()]).unwrap().contains("Noto Sans Arabic")); + assert!(!input_fonts(Some(&f.0), true, false, false, &[]).unwrap().contains("Noto Sans Arabic")); + assert!(scripts_from(None).is_empty()); } } diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 541e7ab90..d26dfbbdc 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (`FIGCRAFT_EMBED_SCRIPTS` embeds other scripts' craft-fonts faces in a web build, so Arabic and Persian documents draw there (#1902); Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7) FigCraft's interface has a localization layer with an English catalog, a Russian catalog reviewed by a native speaker, and Spanish (with a Latin American overlay), French, German, Brazilian @@ -81,7 +81,10 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v nothing (startup and memory measured unchanged); no CJK font installed means tofu, never a crash. The web build has no system fonts: built with craft-fonts and `FIGCRAFT_EMBED_CJK=1` it embeds Noto Sans CJK SC (+16 MB) and offers Japanese, Korean and Simplified Chinese; otherwise the language picker and - System leave them out. No font file is in this repo. + System leave them out. `FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr` (script tags as the craft-fonts manifest + lists them) embeds those scripts' faces as well, so an Arabic or Persian document draws in Noto Sans + Arabic (+0.8 MB) instead of missing-glyph boxes (#1902); the picker's languages don't change. No + font file is in this repo. ## Languages @@ -91,7 +94,7 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v | Simplified Chinese (Mandarin) | zh-Hans | 2,216 / 2,352 (94.2%, draft) | yes | CJK text and IME in documents; UI text in an installed Chinese face, ahead of Japanese ones (web: the `FIGCRAFT_EMBED_CJK` build); no Traditional Chinese catalog (zh-TW, zh-HK read English) | no | draft | 1–2 (after native review) | | Spanish | es, es-419 | 2,352 / 2,352 (100%, draft); es-419 overlays 104 Latin American wordings (draft) | yes | Latin | no | draft | 0–1 (after native review) | | Hindi | hi | 0 (0%) | no | Devanagari shaping works in documents; UI font fallback to check | no | none | 4–7 | -| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web not offered (font budget excludes Arabic); panels do not mirror | no | draft | review + panel mirroring (not re-estimated) | +| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web: documents draw in Noto Sans Arabic only in a build with `FIGCRAFT_EMBED_SCRIPTS=Arab` (the font budget leaves it out otherwise, #1902), the UI language not offered; panels do not mirror | no | draft | review + panel mirroring (not re-estimated) | | French | fr | 2,328 / 2,352 (99.0%, draft) | yes | Latin | no | draft | 1–2 (after native review) | | Portuguese | pt-BR | 2,331 / 2,352 (99.1%, draft) | yes | Latin | no | draft | 1–2 (after native review) | | Indonesian | id | 2,292 / 2,352 (97.4%, draft) | yes | Latin | no | draft | 1–2 (after native review) | @@ -125,6 +128,7 @@ Hindi and Arabic. Traditional Chinese is not planned (no catalog; its users see | Date | Change | Summary | |---|---|---| +| 2026-11-03 | patch | M10, #1902: the web build drew Persian and Arabic text as missing-glyph boxes. The browser has no system fonts, and `crates/text/build.rs` keeps the web catalog to Inter, Noto Sans Georgian, the wordmark and (with `FIGCRAFT_EMBED_CJK`) Noto Sans CJK, so craft-fonts' Noto Sans Arabic never reached it. `FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr,…` (script tags as the manifest's scripts column lists them) now embeds those scripts' faces in a web build; the default build, its size and the UI languages on offer are unchanged. Test: `web_embeds_other_scripts_faces_only_when_asked` in the build script. | | 2026-10-30 | minor | Bosnian (`bs`, Bosanski) draft catalog: every UI string (1,906), command label (629) and menu wording (31), machine-drafted in Latin script with ijekavian forms and marked as a draft awaiting native review. Bosnian plurals: one for 1, 21, 31… (not 11), few for 2–4, 22–24… (not 12–14), other for the rest. Grade and hours unchanged (Bosnian is not one of the twelve key languages) | | 2026-10-29 | minor | German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft. Nine existing translations corrected; keys, placeholders, coverage, grade and estimates unchanged | | 2026-10-28 | minor | Arabic draft: 1,857 UI entries, 620 command labels and 31 menu wordings, with count-neutral plurals. AI-assisted, native review pending. Desktop uses the existing Arabic fallback and bidi; web requires an embedded Arabic face. No panel mirroring or parity-grade increase claimed | diff --git a/docs/translating.md b/docs/translating.md index 9c8aea04d..e3599a08a 100644 --- a/docs/translating.md +++ b/docs/translating.md @@ -78,7 +78,9 @@ CJK and Thai text need their own fonts, which egui and Inter lack: the desktop a one when something on screen needs it, so layer and page names in those scripts show whatever the UI language (see `crates/ui-egui/src/cjk.rs`). The web build has no system fonts, so Japanese, Korean and Chinese appear there only in a build with craft-fonts and -`FIGCRAFT_EMBED_CJK=1` (Noto Sans CJK SC, +16 MB); otherwise they are left out of the picker. A +`FIGCRAFT_EMBED_CJK=1` (Noto Sans CJK SC, +16 MB); otherwise they are left out of the picker. The other +scripts' faces (Noto Sans Arabic, Hebrew, Thai, Devanagari) join a web build only with +`FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr` (the manifest's script tags), for documents in those scripts (#1902). A Chinese UI puts its Chinese face first so Han takes Simplified Chinese shapes. Georgian is drawn in craft-fonts' Noto Sans Georgian, one of the built-in faces in `theme::install_fonts`, or else in an installed font on the desktop. Web builds keep it only when the craft-fonts they're built with has From be04efc4fbb8d90934683026d22e8de6116b157a Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 3 Nov 2026 09:41:15 -0500 Subject: [PATCH 045/102] M10: embeddable script faces as document fallbacks; the Arabic UI with Arab embedded (#1902) Review: Noto Sans Hebrew, Devanagari and Georgian join Arabic and Thai in FALLBACK_FAMILIES, so a web build that embeds one draws that script in an Inter document; with Arab embedded the picker offers the Arabic UI catalog, as cjk::can_show intends (the docs said otherwise); the docs example lists one tag per script. Test: every_embeddable_script_face_is_a_document_fallback. Co-Authored-By: Claude Fable 5.1 --- crates/text/build.rs | 4 ++-- crates/text/src/fontdb.rs | 14 ++++++++++---- crates/text/src/fontdb_tests.rs | 25 +++++++++++++++++++++++++ docs/localization-parity.md | 12 ++++++------ docs/translating.md | 3 ++- 5 files changed, 45 insertions(+), 13 deletions(-) diff --git a/crates/text/build.rs b/crates/text/build.rs index c2a1bf4d2..e23dff936 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -4,8 +4,8 @@ //! 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). //! The other scripts' faces (Noto Sans Arabic, Hebrew, Thai, Devanagari…) stay out of web builds unless -//! `FIGCRAFT_EMBED_SCRIPTS` names their script tags (`Arab,Hebr`, as the manifest's scripts column -//! lists them; #1902). +//! `FIGCRAFT_EMBED_SCRIPTS` names their script tags (`Arab,Hebr,Thai,Deva`: one tag per script wanted, +//! as the manifest's scripts column lists them; #1902). use std::fmt::Write as _; use std::path::PathBuf; diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index d0004fcd9..4b4bf4350 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -544,10 +544,13 @@ fn names(f: &skrifa::FontRef) -> (Option, Option) { (family, style) } -/// Families tried, in order, for characters a text's own font lacks. The symbol fonts come last: -/// Apple Symbols (macOS), Segoe UI Symbol (Windows) and the Noto symbol and math fonts (Linux), for -/// signs such as ⌖ and ⤒ that no text face has. -const FALLBACK_FAMILIES: [&str; 29] = [ +/// Families tried, in order, for characters a text's own font lacks. Every script face craft-fonts +/// can embed (Noto Sans Arabic, Thai, Hebrew, Devanagari, Georgian) is here after the Latin faces, +/// so a web build that embeds one (`FIGCRAFT_EMBED_SCRIPTS`, #1902) draws that script in an Inter +/// document: the browser has no other fonts. The symbol fonts come last: Apple Symbols (macOS), +/// Segoe UI Symbol (Windows) and the Noto symbol and math fonts (Linux), for signs such as ⌖ and ⤒ +/// that no text face has. +const FALLBACK_FAMILIES: [&str; 32] = [ "Inter", "Helvetica Neue", "Arial", @@ -571,6 +574,9 @@ const FALLBACK_FAMILIES: [&str; 29] = [ "Leelawadee UI", "Thonburi", "Tahoma", + "Noto Sans Hebrew", + "Noto Sans Devanagari", + "Noto Sans Georgian", "Apple Symbols", "Segoe UI Symbol", "Noto Sans Symbols", diff --git a/crates/text/src/fontdb_tests.rs b/crates/text/src/fontdb_tests.rs index 5f0fa522b..2df34cf73 100644 --- a/crates/text/src/fontdb_tests.rs +++ b/crates/text/src/fontdb_tests.rs @@ -538,6 +538,31 @@ fn every_platform_has_a_thai_font_in_the_fallbacks() { } } +/// #1902: a web build has no system fonts, so a document's missing characters can only come from +/// the embedded faces. Every script face craft-fonts can embed (`FIGCRAFT_EMBED_SCRIPTS`) is a +/// document fallback after the Latin faces; else Hebrew or Devanagari typed into an Inter layer +/// would stay missing glyphs with its face embedded. +#[test] +fn every_embeddable_script_face_is_a_document_fallback() { + let at = |family: &str| FALLBACK_FAMILIES.iter().position(|f| *f == family); + let latin = at("Segoe UI").unwrap(); + for face in [ + "Noto Sans Arabic", + "Noto Sans Thai", + "Noto Sans Hebrew", + "Noto Sans Devanagari", + "Noto Sans Georgian", + "Noto Sans Symbols", + "Noto Sans Symbols 2", + ] { + assert!(at(face).is_some_and(|i| i > latin), "{face} is a fallback after the Latin faces"); + } + // And whatever script face this build embeds (CI builds have craft-fonts; CJK by request). + for f in CRAFT_FONTS.iter().filter(|f| f.family.starts_with("Noto Sans") && !f.family.contains("CJK")) { + assert!(FALLBACK_FAMILIES.contains(&f.family), "embedded {} is a document fallback", f.family); + } +} + // The paths are Unix absolute paths (font managers are a macOS thing): on Windows they aren't absolute. #[cfg(unix)] #[test] diff --git a/docs/localization-parity.md b/docs/localization-parity.md index d26dfbbdc..67cfad441 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -81,10 +81,10 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v nothing (startup and memory measured unchanged); no CJK font installed means tofu, never a crash. The web build has no system fonts: built with craft-fonts and `FIGCRAFT_EMBED_CJK=1` it embeds Noto Sans CJK SC (+16 MB) and offers Japanese, Korean and Simplified Chinese; otherwise the language picker and - System leave them out. `FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr` (script tags as the craft-fonts manifest - lists them) embeds those scripts' faces as well, so an Arabic or Persian document draws in Noto Sans - Arabic (+0.8 MB) instead of missing-glyph boxes (#1902); the picker's languages don't change. No - font file is in this repo. + System leave them out. `FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr,Thai,Deva` (one tag per script wanted, as + the craft-fonts manifest lists them) embeds those scripts' faces as well, so an Arabic or Persian + document draws in Noto Sans Arabic (+0.8 MB) instead of missing-glyph boxes (#1902), and with `Arab` + the picker offers the Arabic UI catalog too, as on the desktop. No font file is in this repo. ## Languages @@ -94,7 +94,7 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v | Simplified Chinese (Mandarin) | zh-Hans | 2,216 / 2,352 (94.2%, draft) | yes | CJK text and IME in documents; UI text in an installed Chinese face, ahead of Japanese ones (web: the `FIGCRAFT_EMBED_CJK` build); no Traditional Chinese catalog (zh-TW, zh-HK read English) | no | draft | 1–2 (after native review) | | Spanish | es, es-419 | 2,352 / 2,352 (100%, draft); es-419 overlays 104 Latin American wordings (draft) | yes | Latin | no | draft | 0–1 (after native review) | | Hindi | hi | 0 (0%) | no | Devanagari shaping works in documents; UI font fallback to check | no | none | 4–7 | -| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web: documents draw in Noto Sans Arabic only in a build with `FIGCRAFT_EMBED_SCRIPTS=Arab` (the font budget leaves it out otherwise, #1902), the UI language not offered; panels do not mirror | no | draft | review + panel mirroring (not re-estimated) | +| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web: only a build with `FIGCRAFT_EMBED_SCRIPTS=Arab` embeds Noto Sans Arabic (the font budget leaves it out otherwise, #1902); documents draw in it and the picker offers the Arabic UI then; panels do not mirror | no | draft | review + panel mirroring (not re-estimated) | | French | fr | 2,328 / 2,352 (99.0%, draft) | yes | Latin | no | draft | 1–2 (after native review) | | Portuguese | pt-BR | 2,331 / 2,352 (99.1%, draft) | yes | Latin | no | draft | 1–2 (after native review) | | Indonesian | id | 2,292 / 2,352 (97.4%, draft) | yes | Latin | no | draft | 1–2 (after native review) | @@ -128,7 +128,7 @@ Hindi and Arabic. Traditional Chinese is not planned (no catalog; its users see | Date | Change | Summary | |---|---|---| -| 2026-11-03 | patch | M10, #1902: the web build drew Persian and Arabic text as missing-glyph boxes. The browser has no system fonts, and `crates/text/build.rs` keeps the web catalog to Inter, Noto Sans Georgian, the wordmark and (with `FIGCRAFT_EMBED_CJK`) Noto Sans CJK, so craft-fonts' Noto Sans Arabic never reached it. `FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr,…` (script tags as the manifest's scripts column lists them) now embeds those scripts' faces in a web build; the default build, its size and the UI languages on offer are unchanged. Test: `web_embeds_other_scripts_faces_only_when_asked` in the build script. | +| 2026-11-03 | patch | M10, #1902: the web build drew Persian and Arabic text as missing-glyph boxes. The browser has no system fonts, and `crates/text/build.rs` keeps the web catalog to Inter, Noto Sans Georgian, the wordmark and (with `FIGCRAFT_EMBED_CJK`) Noto Sans CJK, so craft-fonts' Noto Sans Arabic never reached it. `FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr,…` (script tags as the manifest's scripts column lists them) now embeds those scripts' faces in a web build; the default build and its size are unchanged, and with `Arab` embedded the picker offers the Arabic UI as well (`cjk::can_show`, as on the desktop). Noto Sans Hebrew, Devanagari and Georgian join Arabic and Thai among the document fallbacks, so an embedded face draws its script in an Inter document. Tests: `web_embeds_other_scripts_faces_only_when_asked` in the build script, `every_embeddable_script_face_is_a_document_fallback`. | | 2026-10-30 | minor | Bosnian (`bs`, Bosanski) draft catalog: every UI string (1,906), command label (629) and menu wording (31), machine-drafted in Latin script with ijekavian forms and marked as a draft awaiting native review. Bosnian plurals: one for 1, 21, 31… (not 11), few for 2–4, 22–24… (not 12–14), other for the rest. Grade and hours unchanged (Bosnian is not one of the twelve key languages) | | 2026-10-29 | minor | German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft. Nine existing translations corrected; keys, placeholders, coverage, grade and estimates unchanged | | 2026-10-28 | minor | Arabic draft: 1,857 UI entries, 620 command labels and 31 menu wordings, with count-neutral plurals. AI-assisted, native review pending. Desktop uses the existing Arabic fallback and bidi; web requires an embedded Arabic face. No panel mirroring or parity-grade increase claimed | diff --git a/docs/translating.md b/docs/translating.md index e3599a08a..b24a4e04b 100644 --- a/docs/translating.md +++ b/docs/translating.md @@ -80,7 +80,8 @@ UI language (see `crates/ui-egui/src/cjk.rs`). The web build has no system fonts so Japanese, Korean and Chinese appear there only in a build with craft-fonts and `FIGCRAFT_EMBED_CJK=1` (Noto Sans CJK SC, +16 MB); otherwise they are left out of the picker. The other scripts' faces (Noto Sans Arabic, Hebrew, Thai, Devanagari) join a web build only with -`FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr` (the manifest's script tags), for documents in those scripts (#1902). A +`FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr,Thai,Deva` (one tag per script wanted, as the manifest lists them), for +documents in those scripts; with `Arab` embedded the picker offers Arabic too (#1902). A Chinese UI puts its Chinese face first so Han takes Simplified Chinese shapes. Georgian is drawn in craft-fonts' Noto Sans Georgian, one of the built-in faces in `theme::install_fonts`, or else in an installed font on the desktop. Web builds keep it only when the craft-fonts they're built with has From 1206c0156e956fd48ca22edf83dcd1419fb15c2e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:28:27 +0000 Subject: [PATCH 046/102] fix(format): charge an archive member's unpacking even when the read fails The shared unpacking total (and Sketch's) was debited only when a member read succeeded, so a snapshot or page member damaged near its end could be named again and again by an index and unpacked each time without ever spending the budget. A failed read is now charged its recorded size; one refused for that size before any unpacking still costs nothing. --- crates/format/src/lib.rs | 13 ++++++++++--- crates/format/src/sketch.rs | 8 +++++--- crates/format/src/unpacked_total_tests.rs | 23 +++++++++++++++++++++++ 3 files changed, 38 insertions(+), 6 deletions(-) diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 3a69ca848..02445da74 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -707,9 +707,16 @@ impl Unpacked { if self.exceeded(z, name) && z.by_name(name).is_ok_and(|f| f.size() <= limit) { return Err(FormatError::Corrupt(format!("{name}: {}", self.passed()))); } - let data = read_member(z, name, limit.min(self.left))?; - self.left = self.left.saturating_sub(data.len() as u64); - Ok(data) + let cap = limit.min(self.left); + let size = z.by_name(name).map_or(0, |f| f.size()); + let data = read_member(z, name, cap); + // A read that failed part way (a bad checksum at the end, say) did its unpacking all the + // same: it is charged in full, so an index naming that member again can't repeat it. One + // refused for its recorded size before any unpacking costs nothing. + if size <= cap { + self.left = self.left.saturating_sub(data.as_ref().map_or(size, |d| d.len() as u64)); + } + data } } diff --git a/crates/format/src/sketch.rs b/crates/format/src/sketch.rs index 8186ce26d..3a2c602df 100644 --- a/crates/format/src/sketch.rs +++ b/crates/format/src/sketch.rs @@ -277,9 +277,11 @@ fn capped_member( if size > allowed { return Err(corrupt(format!("{name} is too large"))); } - let data = crate::read_member(z, name, allowed)?; - *total += data.len() as u64; - Ok(data) + let data = crate::read_member(z, name, allowed); + // A failed read (a bad checksum at the end, say) unpacked all the same: charged in full, so + // a page list naming the member again can't repeat it within the budget. + *total += data.as_ref().map_or(size, |d| d.len() as u64); + data } /// JSON member `name`, read by [`capped_member`] within the file's [`MAX_JSON_TOTAL`]. diff --git a/crates/format/src/unpacked_total_tests.rs b/crates/format/src/unpacked_total_tests.rs index 8ed304ddc..92db654e5 100644 --- a/crates/format/src/unpacked_total_tests.rs +++ b/crates/format/src/unpacked_total_tests.rs @@ -93,3 +93,26 @@ fn the_total_leaves_room_for_the_largest_real_files() { // Below what the per-area caps added up to (about 10 GB). const { assert!(MAX_UNPACKED < 10 * 1024 * 1024 * 1024) }; } + +#[test] +fn a_read_that_fails_part_way_still_spends_the_total() { + // A member whose compressed bytes are damaged near the end unpacks almost all of itself + // before failing: that work is charged, so an index naming it again can't repeat it for free. + let body: Vec = (0..200_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect(); + // Stored, so a byte flipped in the middle is read through and fails only on the checksum. + let mut buf = std::io::Cursor::new(Vec::new()); + let mut w = zip::ZipWriter::new(&mut buf); + w.start_file("snapshots/v1.json", zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored)).unwrap(); + w.write_all(&body).unwrap(); + w.finish().unwrap(); + let mut bytes = buf.into_inner(); + let at = 30 + "snapshots/v1.json".len() + body.len() / 2; + bytes[at] ^= 0xff; + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let size = z.by_name("snapshots/v1.json").unwrap().size(); + assert_eq!(size, body.len() as u64); + let mut total = crate::Unpacked::new(size + size / 2); + assert!(total.read(&mut z, "snapshots/v1.json", 1 << 20).is_err(), "the damaged member fails"); + let again = total.read(&mut z, "snapshots/v1.json", 1 << 20).unwrap_err().to_string(); + assert!(again.contains("together pass"), "the second read is refused for the total, not read again: {again}"); +} From c673996fe792f8ae85e00bb52fd8e1572bf73eb6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:37:12 +0000 Subject: [PATCH 047/102] fix(engine): install a directory plugin only with the permissions that were shown The confirmation showed the directory entry's access and commands, but the downloaded bundle's manifest was registered as is, so a directory could show a read-only plugin and install one that edits the document. A manifest asking for more than the entry showed is refused before it is saved. --- .../engine/src/extensions/plugin_directory.rs | 10 +++++++ crates/engine/src/plugin_directory_tests.rs | 26 +++++++++++++++++++ crates/engine/src/sharing/background/tests.rs | 11 ++++++-- 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/extensions/plugin_directory.rs b/crates/engine/src/extensions/plugin_directory.rs index 2f721feae..2c7e00e8f 100644 --- a/crates/engine/src/extensions/plugin_directory.rs +++ b/crates/engine/src/extensions/plugin_directory.rs @@ -127,6 +127,16 @@ fn install(s: &mut Session, p: &Value) -> Result { if manifest.id != entry.id || manifest.version != entry.version { return Err(fail("its manifest doesn't match the directory's entry")); } + // What was shown and approved is the entry's access and commands: a bundle whose manifest + // asks for more is refused, since the manifest is what the plugin then runs under. + if manifest.permissions.access == figcraft_plugin::manifest::Access::Write && !entry.access.trim().eq_ignore_ascii_case("write") { + return Err(fail("its manifest asks to write the document, but the directory showed it as read-only")); + } + if !entry.commands.is_empty() + && (manifest.permissions.commands.is_empty() || manifest.permissions.commands.iter().any(|c| !entry.commands.contains(c))) + { + return Err(fail("its manifest asks for commands the directory didn't show")); + } let source = address(&server); let path = save(s, &mut manifest, &bundle).map_err(|e| fail(&e))?; let out = json!({ diff --git a/crates/engine/src/plugin_directory_tests.rs b/crates/engine/src/plugin_directory_tests.rs index fa4d3d4cc..358845933 100644 --- a/crates/engine/src/plugin_directory_tests.rs +++ b/crates/engine/src/plugin_directory_tests.rs @@ -252,3 +252,29 @@ fn publishing_sends_a_checked_folder() { assert_eq!(r["id"], ID); let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn a_bundle_asking_for_more_than_the_directory_showed_is_not_installed() { + let (mut s, d) = session(); + // Shown as read-only with one command; the bundle's manifest asks to write, any command. + let text = + json!({"id": ID, "name": "Tiny", "version": "1.0.0", "author": "Ada", "main": "tiny.wasm", "permissions": {"access": "write"}}).to_string(); + let b = Bundle { manifest: text, wasm: wasm(), assets: vec![] }.encode(); + let mut e = entry(ID, "1.0.0", &b); + e.commands = vec!["node.get".into()]; + d.lock().unwrap().plugins.push((e, b)); + s.execute("plugin.directory.list", &json!({"server": "ws://127.0.0.1:9/"})).unwrap(); + let err = s.execute("plugin.directory.install", &json!({"id": ID, "confirm": true})).unwrap_err().to_string(); + assert!(err.contains("write"), "{err}"); + assert!(s.prefs.plugins.is_empty(), "nothing was installed"); + // Read-only as shown, but more commands than shown. + let text = json!({"id": ID, "name": "Tiny", "version": "1.0.1", "author": "Ada", "main": "tiny.wasm", "permissions": {"access": "read", "commands": ["node.get", "node.set"]}}).to_string(); + let b = Bundle { manifest: text, wasm: wasm(), assets: vec![] }.encode(); + let mut e = entry(ID, "1.0.1", &b); + e.commands = vec!["node.get".into()]; + d.lock().unwrap().plugins.clear(); + d.lock().unwrap().plugins.push((e, b)); + s.execute("plugin.directory.list", &json!({"server": "ws://127.0.0.1:9/"})).unwrap(); + let err = s.execute("plugin.directory.install", &json!({"id": ID, "confirm": true})).unwrap_err().to_string(); + assert!(err.contains("commands"), "{err}"); +} diff --git a/crates/engine/src/sharing/background/tests.rs b/crates/engine/src/sharing/background/tests.rs index fa4d00824..6f98841df 100644 --- a/crates/engine/src/sharing/background/tests.rs +++ b/crates/engine/src/sharing/background/tests.rs @@ -73,8 +73,15 @@ fn bundle() -> Vec { fn directory(req: PluginReq) -> PluginReply { let bytes = bundle(); - let entry = - PluginEntry { id: ID.into(), name: "Tiny tool".into(), version: "1.0.0".into(), sha256: sha256_hex(&bytes), ..PluginEntry::default() }; + let entry = PluginEntry { + id: ID.into(), + name: "Tiny tool".into(), + version: "1.0.0".into(), + access: "write".into(), + commands: vec!["shape.rectangle".into()], + sha256: sha256_hex(&bytes), + ..PluginEntry::default() + }; match req { PluginReq::List { .. } => PluginReply::List(vec![entry]), PluginReq::Fetch { .. } => PluginReply::Bundle { entry, bundle: bytes }, From 02db900cc81e0b57c6861beded522c33a156f2a6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:02:53 +0000 Subject: [PATCH 048/102] fix(engine): keep plugins out of branches, saved versions and library links A read-only plugin could archive, merge, create or update a branch: branch state lives beside the document, so neither the command's history flag nor the document Arc check saw the write. Any plugin could read a saved version through dev.compare's version parameter although version.* is denied, and library.list handed plugins each library's path, which for a server library is the share link with its token. --- crates/engine/src/doc_list_paths_tests.rs | 17 +++++++++ crates/engine/src/extensions/plugins.rs | 43 ++++++++++++++++++++--- 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/doc_list_paths_tests.rs b/crates/engine/src/doc_list_paths_tests.rs index 0c62a18dd..f69941919 100644 --- a/crates/engine/src/doc_list_paths_tests.rs +++ b/crates/engine/src/doc_list_paths_tests.rs @@ -46,3 +46,20 @@ fn a_plugin_gets_names_but_no_paths() { assert!(out.contains("Front"), "{out}"); assert!(!out.contains(SECRET) && !out.contains("path"), "{out}"); } + +#[test] +fn a_plugin_gets_library_names_but_not_their_links() { + const LINK: &str = "ws://tracker.example:9/?file=f&token=per-file-secret"; + let mut s = Session::new(); + s.doc_mut().unwrap().libraries_mut().enabled.push(figcraft_doc::LibraryLink { + id: "lib".into(), + name: "Kit".into(), + path: LINK.into(), + version: 3, + }); + let tail = "(call $set_output (i32.const 40000) (call $reply_read (i32.const 40000) (i32.const 20000))) (return (i32.const 0))"; + install(&mut s, manifest("org.test.libs", "read", &[]), &script(&[("library.list", json!({}))], OnRefusal::Fail, tail)); + let out = ex(&mut s, "plugin.run", json!({"id": "org.test.libs"}))["output"].to_string(); + assert!(out.contains("Kit"), "{out}"); + assert!(!out.contains("per-file-secret") && !out.contains("\\\"path\\\""), "{out}"); +} diff --git a/crates/engine/src/extensions/plugins.rs b/crates/engine/src/extensions/plugins.rs index 2b1094306..78044ee71 100644 --- a/crates/engine/src/extensions/plugins.rs +++ b/crates/engine/src/extensions/plugins.rs @@ -170,12 +170,21 @@ fn refusal(m: &Manifest, command: &str, params: &Value) -> Option { if command == "variable.import" && get(params, "variables").and_then(Value::as_str).is_some_and(|t| !t.trim_start().starts_with('{')) { return Some("plugins can't read files: pass the variables JSON itself".into()); } + // A saved version is the file's history, which plugins can't read (`version.` is denied). + if command == "dev.compare" && get(params, "version").is_some_and(|v| !v.is_null()) { + return Some("plugins can't read saved versions: leave out `version`".into()); + } if !m.permissions.allows(command) { return Some(format!("`{command}` isn't in the commands {} asked permission for", m.name)); } if m.permissions.access == Access::Read && find_command(command).is_some_and(|c| c.history) { return Some(format!("`{command}` edits the document, and {} may only read it", m.name)); } + // Branches live beside the document (not in its undo history or its `Arc`), so the write + // checks below don't see them change. + if m.permissions.access == Access::Read && matches!(command, "branch.create" | "branch.updateFromMain" | "branch.merge" | "branch.archive") { + return Some(format!("`{command}` changes the file's branches, and {} may only read it", m.name)); + } None } @@ -253,10 +262,19 @@ impl figcraft_plugin::Host for EngineHost<'_> { Ok(v) }); r.map(|mut v| { - // A plugin gets the open files' names, not where they are on disk (#1117). - if command == "doc.list" { - for e in v.as_array_mut().into_iter().flatten().filter_map(Value::as_object_mut) { - e.remove("path"); + // A plugin gets the open files' and libraries' names, not where they are on disk or + // the share links (with their tokens) that reach them (#1117). + if matches!(command, "doc.list" | "library.list") { + // `doc.list` is a list; `library.list` keeps its list under `libraries`. + let list = if command == "library.list" { v.get_mut("libraries") } else { Some(&mut v) }; + for e in list.and_then(Value::as_array_mut).into_iter().flatten().filter_map(Value::as_object_mut) { + // An error may quote the path too. + if let Some(Value::String(path)) = e.remove("path") + && !path.is_empty() + && let Some(Value::String(err)) = e.get_mut("error") + { + *err = err.replace(&path, "the library"); + } } } v.to_string() @@ -698,6 +716,23 @@ mod refusal_tests { let r = refusal(&m, "library.publishToServer", &json!({})); assert!(r.is_some(), "library.publishToServer uploads the document and must be refused"); } + + #[test] + fn read_only_plugin_cannot_change_branches() { + let m = Manifest::parse(r#"{"id":"x.y","name":"X","main":"plugin.wasm"}"#).unwrap(); + for cmd in ["branch.archive", "branch.updateFromMain", "branch.merge", "branch.create"] { + assert!(refusal(&m, cmd, &json!({})).is_some(), "{cmd} changes persisted branch state"); + } + assert!(refusal(&m, "branch.list", &json!({})).is_none()); + } + + #[test] + fn plugins_cannot_compare_against_a_saved_version() { + let m = Manifest::parse(r#"{"id":"x.y","name":"X","main":"plugin.wasm","permissions":{"access":"write"}}"#).unwrap(); + assert!(refusal(&m, "dev.compare", &json!({"version": "v1"})).is_some()); + assert!(refusal(&m, "dev.compare", &json!({"version": null})).is_none()); + assert!(refusal(&m, "dev.compare", &json!({})).is_none()); + } } #[cfg(test)] From d744379e6050d90ad6920eb3e602fb728a79c400 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:27:00 +0000 Subject: [PATCH 049/102] fix(engine): refuse document URLs with shell syntax or a malformed authority webbrowser on WSL hands an address to cmd.exe /c start, escaping only & and ^, so a document link holding | (or < > " `) ran what followed it with the viewer's authority; and an address its parser can't read is reopened as a file path. Characters never valid in a URL unencoded are now refused, and an http(s) authority must be made of host characters. --- crates/engine/src/automation/doc_urls.rs | 13 ++++++++++++- crates/engine/src/doc_urls_tests.rs | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/automation/doc_urls.rs b/crates/engine/src/automation/doc_urls.rs index 3b8417cd2..8b7d83199 100644 --- a/crates/engine/src/automation/doc_urls.rs +++ b/crates/engine/src/automation/doc_urls.rs @@ -28,6 +28,11 @@ pub fn openable(url: &str) -> bool { if url.is_empty() || url.chars().any(char::is_control) { return false; } + // Never valid in a URL unencoded, and read as syntax by the shells some openers go through + // (webbrowser on WSL hands the address to `cmd.exe /c start`, escaping only `&` and `^`). + if url.chars().any(|c| c.is_whitespace() || matches!(c, '|' | '<' | '>' | '"' | '`' | '\\' | '^')) { + return false; + } let Some((scheme, rest)) = url.split_once(':') else { return false }; // An RFC 3986 scheme, so a stray colon in text cannot look like one. let mut chars = scheme.chars(); @@ -44,5 +49,11 @@ pub fn openable(url: &str) -> bool { // `http` and `https` name a host, so the authority is required: `http:x` is not a web link, // and `http:///p` has no host. let Some(after) = rest.strip_prefix("//") else { return false }; - !after.is_empty() && !after.starts_with('/') + if after.is_empty() || after.starts_with('/') { + return false; + } + // The authority is made of host characters only (an opener that can't parse the address may + // fall back to treating it as a file path). + let authority = after.split(['/', '?', '#']).next().unwrap_or_default(); + authority.chars().all(|c| !c.is_ascii() || c.is_ascii_alphanumeric() || "-._~:@[]%!$&'()*+,;=".contains(c)) } diff --git a/crates/engine/src/doc_urls_tests.rs b/crates/engine/src/doc_urls_tests.rs index d42029a0f..7158eae06 100644 --- a/crates/engine/src/doc_urls_tests.rs +++ b/crates/engine/src/doc_urls_tests.rs @@ -85,3 +85,25 @@ fn a_scheme_is_required_and_control_characters_are_refused() { assert!(!openable(url), "{url:?} must be refused"); } } + +#[test] +fn shell_syntax_and_malformed_authorities_are_refused() { + for url in [ + // Never valid unencoded, and command syntax to the `cmd.exe /c start` an opener may use. + "https://example.com/?a=b|calc", + "https://example.com/", + "https://example.com/\"x\"", + "https://example.com/a b", + "https://example.com/`x`", + "https://example.com/x^y", + "https://example.com\\x", + // An authority an opener can't parse may be reopened as a file path. + "http://exam ple.com/", + "http://a{b}/", + ] { + assert!(!openable(url), "{url:?} must be refused"); + } + for url in ["https://example.com/?a=b&c=d%20e", "https://[::1]:8080/x", "https://bücher.example/", "https://a.b-c_d.example:443/"] { + assert!(openable(url), "{url:?} should open"); + } +} From ff564b1e16a6b325907e850d5e065f3e6657fe1f Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Tue, 3 Nov 2026 19:58:08 +0400 Subject: [PATCH 050/102] i18n(ka): add 6 text-wrap strings Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- crates/ui-egui/locales/ka.toml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/ui-egui/locales/ka.toml b/crates/ui-egui/locales/ka.toml index f634a2e7e..b62936268 100644 --- a/crates/ui-egui/locales/ka.toml +++ b/crates/ui-egui/locales/ka.toml @@ -385,6 +385,12 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv "Decoration style" = "გაფორმების სტილი" "Decoration" = "გაფორმება" "Deep select" = "ღრმა მონიშვნა" +"Wrap style" = "გადატანის სტილი" +"Balance" = "დაბალანსებული" +"Pretty" = "მოწესრიგებული" +"Auto: as many words as fit on each line" = "ავტომატური: თითო სტრიქონში იმდენი სიტყვა, რამდენიც ეტევა" +"Balance: every line close to the same length" = "დაბალანსებული: ყველა სტრიქონი დაახლოებით ერთი სიგრძისაა" +"Pretty: full lines, no one word alone on the last" = "მოწესრიგებული: სავსე სტრიქონები, ბოლო სტრიქონზე ერთი სიტყვა მარტო არ რჩება" "Default" = "ნაგულისხმევი" "Default content" = "ნაგულისხმევი შიგთავსი" "Default value (the top-left variant)" = "ნაგულისხმევი მნიშვნელობა (ზედა მარცხენა ვარიანტი)" From d48aa59ec757ba9b6ebe346aebfbbaed87505d97 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 3 Nov 2026 11:52:41 -0500 Subject: [PATCH 051/102] M12: drag a "+" handle to drop the next shape anywhere or join another object (#1919) The quick-create handles only took a click. As the help says ("drag the preview to any location on your board"), a handle can now be dragged: the preview follows the pointer and, let go on empty board, the next sticky or shape is made there, centred on the pointer, joined by a connector whose ends take the sides facing each other (board.addConnected gains at: [x, y]); let go on another sticky or shape, a connector joins the two instead (board.connector), that object outlined while over it. figcraft_engine::board::object_at exposes the hit test a stamp uses. The click is as before. Tests: board_connect_tests (two), board_connected_tests::the_next_one_goes_where_it_is_dropped. Docs: boards-parity row, status line and revision history. Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/board_connected_tests.rs | 17 +++ crates/engine/src/boards/board.rs | 9 +- crates/engine/src/boards/board/items.rs | 16 +++ crates/ui-egui/src/board_connect_tests.rs | 53 ++++++++ crates/ui-egui/src/canvas/board_connect.rs | 138 +++++++++++++++++++-- docs/boards-parity.md | 5 +- 6 files changed, 225 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/board_connected_tests.rs b/crates/engine/src/board_connected_tests.rs index 2e5f8a344..d6b962449 100644 --- a/crates/engine/src/board_connected_tests.rs +++ b/crates/engine/src/board_connected_tests.rs @@ -104,3 +104,20 @@ fn the_next_sticky_shortcut_joins_the_next_shape_and_leaves_stickies_as_they_wer assert!(r.get("connector").is_none(), "{r}"); assert!(matches!(node(&s, id(&r, "id")).board, Some(BoardItem::Sticky { .. }))); } + +/// `at` (#1919; "drag the preview to any location on your board", Build faster with quick create): +/// the next one is centred on that point, wherever it is, and the connector takes the sides facing +/// each other; `at` must be two finite numbers. +#[test] +fn the_next_one_goes_where_it_is_dropped() { + let mut s = board(); + let a = id(&s.execute("board.shape", &json!({"shape": "diamond", "x": 0, "y": 0, "width": 200, "height": 120})).unwrap(), "id"); + let r = s.execute("board.addConnected", &json!({"id": a, "side": "below", "at": [700, 60]})).unwrap(); + let (b, c) = (id(&r, "id"), id(&r, "connector")); + assert_eq!(at(&s, b), (600.0, 0.0), "centred on the point"); + let k = connector(&s, c); + assert_eq!((k.from, k.to), (End::Node { node: a, side: Side::Auto, at: None }, End::Node { node: b, side: Side::Auto, at: None })); + for wrong in [json!([1]), json!("x"), json!([0, "y"]), json!({"x": 1, "y": 2})] { + assert!(s.execute("board.addConnected", &json!({"id": a, "at": wrong})).is_err(), "{wrong}"); + } +} diff --git a/crates/engine/src/boards/board.rs b/crates/engine/src/boards/board.rs index bf7f8ccf1..d6c5dc255 100644 --- a/crates/engine/src/boards/board.rs +++ b/crates/engine/src/boards/board.rs @@ -33,6 +33,13 @@ pub use connectors::{END_HANDLE_PX, selected_connector_ends}; use connectors::{connector_cmd, reattach}; pub use derived::route; pub(crate) use derived::{settle_routes, settle_stamps, settle_text, stamp_target}; + +/// The sticky, shape or other object at `p` on `page`: the topmost layer of the page whose box +/// holds it (stamps, connectors, their labels and ink aside), other than `except`. What a stamp +/// sticks to, and what a "+" handle dragged onto it joins (#1919). +pub fn object_at(doc: &Document, page: NodeId, p: Point, except: Option) -> Option { + stamp_target(doc, page, p, except) +} pub use edit::label_of; pub(crate) use edit::{copied_items, copy_map, rejoin}; use edit::{label_cmd, set_color, set_style}; @@ -114,7 +121,7 @@ pub fn specs() -> Vec { spec!( "board.addConnected", "Add connected shape", - "{id? (a sticky or shape; default the selected or edited one), side?: right|below|left|above (default right), edit? (start typing in it; default false)} → {id, text, connector} the next one of the same kind, size and colour on that side, joined by a connector", + "{id? (a sticky or shape; default the selected or edited one), side?: right|below|left|above (default right), at? ([x, y] on the page: the next one's centre, anywhere, instead of its place on that side; the connector then takes the sides facing each other), edit? (start typing in it; default false)} → {id, text, connector} the next one of the same kind, size and colour on that side, joined by a connector", true, add_connected ), diff --git a/crates/engine/src/boards/board/items.rs b/crates/engine/src/boards/board/items.rs index 44708d944..981a8399e 100644 --- a/crates/engine/src/boards/board/items.rs +++ b/crates/engine/src/boards/board/items.rs @@ -223,6 +223,12 @@ pub(super) fn add_connected(s: &mut Session, p: &Value) -> Result { let color = color.unwrap_or(s.tool.board.sticky); let (to_at, from_side, to_side) = connected_place((at.x, at.y), (n.width, n.height), next, &side) .ok_or_else(|| bad(cmd, format!("`side` is right, below, left or above, not `{side}`")))?; + // Dropped somewhere by hand ("drag the preview to any location on your board", #1919): the + // next one is centred there, and the connector joins the sides facing each other. + let (to_at, from_side, to_side) = match drop_point(cmd, p)? { + Some((x, y)) => ((x - next.0 / 2.0, y - next.1 / 2.0), Side::Auto, Side::Auto), + None => (to_at, from_side, to_side), + }; let (routing, author, page) = (s.tool.board.routing, author(s), s.page()?); if editing.is_some() { textedit::end(s)?; @@ -246,6 +252,16 @@ pub(super) fn add_connected(s: &mut Session, p: &Value) -> Result { Ok(json!({"id": id, "text": text, "connector": line})) } +/// `at?` of `board.addConnected`: a point on the page, `[x, y]`, or none. +fn drop_point(cmd: &str, p: &Value) -> Result> { + let Some(v) = get(p, "at") else { return Ok(None) }; + let pair = v.as_array().filter(|a| a.len() == 2).and_then(|a| Some((a.first()?.as_f64()?, a.get(1)?.as_f64()?))); + match pair { + Some((x, y)) if x.is_finite() && y.is_finite() => Ok(Some((x, y))), + _ => Err(bad(cmd, "`at` is [x, y] on the page, two finite numbers")), + } +} + /// A shape with text's layers: the frame, its outline and its text. fn make_shape( doc: &mut Document, diff --git a/crates/ui-egui/src/board_connect_tests.rs b/crates/ui-egui/src/board_connect_tests.rs index 5a4712197..f3e4dc612 100644 --- a/crates/ui-egui/src/board_connect_tests.rs +++ b/crates/ui-egui/src/board_connect_tests.rs @@ -140,3 +140,56 @@ fn the_object_a_stamp_will_stick_to_is_highlighted() { u.button(off, false); assert_eq!((target(&u), on(&u)), (None, None), "let go off the shape: on nothing, and no outline"); } + +/// Dragging a "+" carries the preview ("Click to select and create the next shape in that +/// direction, or drag the preview to any location on your board", Build faster with quick create; +/// #1919): let go on empty board and the next shape is made there, centred on the pointer, joined +/// by a connector, with typing started; one undo takes both away. +#[test] +fn dragging_a_handle_drops_the_next_shape_where_it_is_let_go() { + let (mut u, a) = board_with_shape(); + u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap(); + u.frame(vec![]); + u.frame(vec![]); + let before = u.app.session.doc().unwrap().ids().count(); + let from = handle(&u, "below").expect("a handle below").center(); + let to = from + egui::vec2(260.0, 180.0); + u.drag_to(from, to); + u.button(to, false); + u.frame(vec![]); + let doc = u.app.session.doc().unwrap(); + let next = doc.ids().find(|i| *i != a && matches!(doc.node(*i).unwrap().board, Some(BoardItem::Shape { .. }))).expect("a new shape"); + let line = doc.ids().find(|i| matches!(doc.node(*i).unwrap().board, Some(BoardItem::Connector(_)))).expect("a connector"); + let centre = screen_box(&u, next).center(); + assert!((centre - to).length() < 1.0, "centred where it was let go: {centre:?}, not {to:?}"); + assert!(matches!(&doc.node(line).unwrap().board, Some(BoardItem::Connector(c)) if c.from.node() == Some(a) && c.to.node() == Some(next))); + assert!(u.app.session.ds().unwrap().text_edit.is_some(), "typing in the new shape"); + figcraft_engine::textedit::end(&mut u.app.session).unwrap(); + u.app.session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(u.app.session.doc().unwrap().ids().count(), before, "undo takes the shape and its connector away"); +} + +/// A "+" dragged onto another sticky or shape joins the two with a connector instead of making a +/// new shape (#1919). +#[test] +fn dropping_a_handle_on_another_shape_joins_them() { + let (mut u, a) = board_with_shape(); + let b = id(&u.app.session.execute("board.shape", &json!({"shape": "ellipse", "x": 400, "y": 300, "width": 160, "height": 100})).unwrap()); + u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap(); + u.frame(vec![]); + u.frame(vec![]); + let shapes = |u: &Ui| { + let doc = u.app.session.doc().unwrap(); + doc.ids().filter(|i| matches!(doc.node(*i).unwrap().board, Some(BoardItem::Shape { .. }))).count() + }; + assert_eq!(shapes(&u), 2); + let from = handle(&u, "right").expect("a handle right").center(); + let to = screen_box(&u, b).center(); + u.drag_to(from, to); + u.button(to, false); + u.frame(vec![]); + assert_eq!(shapes(&u), 2, "no new shape"); + let doc = u.app.session.doc().unwrap(); + let line = doc.ids().find(|i| matches!(doc.node(*i).unwrap().board, Some(BoardItem::Connector(_)))).expect("a connector"); + assert!(matches!(&doc.node(line).unwrap().board, Some(BoardItem::Connector(c)) if c.from.node() == Some(a) && c.to.node() == Some(b))); +} diff --git a/crates/ui-egui/src/canvas/board_connect.rs b/crates/ui-egui/src/canvas/board_connect.rs index 87211055b..aaac45af9 100644 --- a/crates/ui-egui/src/canvas/board_connect.rs +++ b/crates/ui-egui/src/canvas/board_connect.rs @@ -1,11 +1,13 @@ //! Boards: a "+" beside each side of the one selected sticky or shape (#1597). Hovering one shows //! where the next one goes; clicking it makes the next of the same kind there, joined by a -//! connector, and starts typing in it (`board.addConnected`). +//! connector, and starts typing in it (`board.addConnected`). Dragging one carries the preview +//! ("drag the preview to any location on your board", #1919): let go on empty board and the next +//! one is made there, joined; let go on another sticky or shape and a connector joins the two. -use egui::{Area, Color32, CornerRadius, Id, LayerId, Order, Pos2, Rect, Sense, Shape, Stroke, pos2, vec2}; +use egui::{Area, Color32, CornerRadius, Id, LayerId, Order, Pos2, Rect, Sense, Shape, Stroke, StrokeKind, pos2, vec2}; use figcraft_doc::{BoardItem, NodeId}; use figcraft_engine::ToolId; -use figcraft_engine::board::{STICKY, connected_place}; +use figcraft_engine::board::{STICKY, connected_place, object_at}; use serde_json::json; use crate::FigApp; @@ -18,6 +20,17 @@ pub(crate) const REACH: f32 = 36.0; const RADIUS: f32 = 9.0; const SIDES: [&str; 4] = ["above", "right", "below", "left"]; +/// A drag from a "+": the object and the side it started from, kept while the button is down. +#[derive(Clone)] +struct Drag { + from: NodeId, + side: &'static str, +} + +fn drag_id() -> Id { + Id::unique("board_connect_drag") +} + /// The sticky or shape the handles are for: its id, its box on the page and the next one's size. fn target(app: &FigApp) -> Option<(NodeId, figcraft_geom::Rect, (f64, f64))> { let editable = app.session.active_read_only().is_none(); @@ -51,8 +64,35 @@ fn handle_at(r: Rect, side: &str) -> Pos2 { } } +/// The middle of `side` of the object's screen box `r`, where its connector leaves. +fn side_middle(r: Rect, side: &str) -> Pos2 { + match side { + "above" => r.center_top(), + "right" => r.right_center(), + "below" => r.center_bottom(), + _ => r.left_center(), + } +} + +/// A "+" side as `board.connector` names it. +fn connector_side(side: &str) -> &'static str { + match side { + "above" => "top", + "below" => "bottom", + "left" => "left", + _ => "right", + } +} + pub fn show(app: &mut FigApp, ctx: &egui::Context) { - let Some((id, b, next)) = target(app) else { return }; + let drag: Option = ctx.data(|d| d.get_temp(drag_id())); + let Some((id, b, next)) = target(app) else { + // The selection or the tool changed under a drag: it is over. + if drag.is_some() { + ctx.data_mut(|d| d.remove::(drag_id())); + } + return; + }; let r = Rect::from_two_pos(app.to_screen(b.x0, b.y0), app.to_screen(b.x1, b.y1)); // Too small on screen to tell the handles from the object. if r.width() < 2.0 * RADIUS || r.height() < 2.0 * RADIUS { @@ -63,16 +103,18 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) { // Not over the toolbar at the bottom of the canvas. let toolbar = crate::toolbar::pill_rect(app.canvas.rect, crate::toolbar::bar_width(app)).expand(RADIUS); let mut picked = None; + let mut started = None; + let mut let_go = false; for side in SIDES { let c = handle_at(r, side); if !app.canvas.rect.shrink(RADIUS).contains(c) || toolbar.contains(c) { continue; } let area = Area::new(Id::unique(("board_connect", side))).fixed_pos(c - vec2(RADIUS, RADIUS)).order(Order::Middle); - let clicked = area + let (clicked, drag_started, drag_stopped) = area .show(ctx, |ui| { - let (rect, resp) = ui.allocate_exact_size(vec2(2.0 * RADIUS, 2.0 * RADIUS), Sense::click()); - let hot = resp.hovered(); + let (rect, resp) = ui.allocate_exact_size(vec2(2.0 * RADIUS, 2.0 * RADIUS), Sense::click_and_drag()); + let hot = resp.hovered() || resp.dragged(); let p = ui.painter(); p.circle_filled(rect.center(), RADIUS, if hot { accent } else { t.panel }); p.circle_stroke(rect.center(), RADIUS, Stroke::new(1.0, if hot { accent } else { t.border })); @@ -80,19 +122,58 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) { let arm = RADIUS * 0.45; p.line_segment([rect.center() - vec2(arm, 0.0), rect.center() + vec2(arm, 0.0)], ink); p.line_segment([rect.center() - vec2(0.0, arm), rect.center() + vec2(0.0, arm)], ink); - if hot { + // Where a click puts the next one; a drag shows its own preview. + if hot && drag.is_none() && !resp.dragged() { preview(app, ctx, b, next, side, accent); } - resp.on_hover_text(tr("Add a connected shape")).clicked() + let resp = resp.on_hover_text(tr("Add a connected shape")); + (resp.clicked(), resp.drag_started(), resp.drag_stopped()) }) .inner; if clicked { picked = Some(side); } + if drag_started { + started = Some(side); + } + let_go |= drag_stopped; } if let Some(side) = picked { app.run("board.addConnected", json!({"id": id, "side": side, "edit": true})); } + if let Some(side) = started { + ctx.data_mut(|d| d.insert_temp(drag_id(), Drag { from: id, side })); + } + // A drag carries the preview: the next one centred on the pointer, or the object under it, + // which the connector joins instead. + let Some(Drag { from, side }) = drag.filter(|d| d.from == id) else { return }; + let Some(pointer) = ctx.input(|i| i.pointer.latest_pos()) else { return }; + let over = object_under(app, from, pointer); + drag_preview(app, ctx, (b, next, side), pointer, over); + if let_go { + ctx.data_mut(|d| d.remove::(drag_id())); + match over { + Some(to) => { + app.run("board.connector", json!({"from": from, "to": to, "fromSide": connector_side(side)})); + } + None => { + let q = app.to_page(pointer); + app.run("board.addConnected", json!({"id": from, "side": side, "at": [q.x, q.y], "edit": true})); + } + } + } else if !ctx.input(|i| i.pointer.any_down()) { + // The button came up without the handle hearing of it (the pointer left the window). + ctx.data_mut(|d| d.remove::(drag_id())); + } +} + +/// The sticky, shape or other object under the screen point `p` on the canvas, other than `except`. +fn object_under(app: &FigApp, except: NodeId, p: Pos2) -> Option { + if !app.canvas.rect.contains(p) { + return None; + } + let ds = app.session.ds().ok()?; + object_at(&ds.doc, ds.page, app.to_page(p), Some(except)) } /// Where the next one goes for `side`, faintly: its box and the connector's line to it. @@ -107,9 +188,46 @@ fn preview(app: &FigApp, ctx: &egui::Context, b: figcraft_geom::Rect, next: (f64 _ => (from.left_center(), ghost.right_center()), }; let p = ctx.layer_painter(LayerId::new(Order::Middle, Id::unique("board_connect_preview"))); + let faint = Stroke::new(1.5, accent.gamma_multiply(0.6)); + ghost_box(&p, ghost, accent); + p.line_segment([a, z], faint); +} + +/// The next one's box, faintly: a tint and a dashed outline. +fn ghost_box(p: &egui::Painter, ghost: Rect, accent: Color32) { let faint = Stroke::new(1.5, accent.gamma_multiply(0.6)); p.rect_filled(ghost, CornerRadius::same(8), accent.gamma_multiply(0.08)); let corners = [ghost.left_top(), ghost.right_top(), ghost.right_bottom(), ghost.left_bottom(), ghost.left_top()]; p.extend(Shape::dashed_line(&corners, faint, 6.0, 4.0)); - p.line_segment([a, z], faint); +} + +/// The dragged preview: the next one centred on `pointer` and the connector's line to it from +/// `side` of the object's box `b`, or, over another object, that object outlined and the line to +/// it; the line arrives at the side of the box facing the object. +fn drag_preview(app: &FigApp, ctx: &egui::Context, (b, next, side): (figcraft_geom::Rect, (f64, f64), &str), pointer: Pos2, over: Option) { + let accent = crate::theme::canvas_accent(ctx); + let from = Rect::from_two_pos(app.to_screen(b.x0, b.y0), app.to_screen(b.x1, b.y1)); + let p = ctx.layer_painter(LayerId::new(Order::Middle, Id::unique("board_connect_preview"))); + let to_box = match over.and_then(|o| app.session.doc().ok()?.world_bounds(o)) { + Some(ob) => { + let r = Rect::from_two_pos(app.to_screen(ob.x0, ob.y0), app.to_screen(ob.x1, ob.y1)); + p.rect_stroke(r, CornerRadius::same(4), Stroke::new(1.5, accent), StrokeKind::Outside); + r + } + None => { + let size = app.to_screen(next.0, next.1) - app.to_screen(0.0, 0.0); + let ghost = Rect::from_center_size(pointer, size); + ghost_box(&p, ghost, accent); + ghost + } + }; + let d = to_box.center() - from.center(); + let z = if d.x.abs() >= d.y.abs() { + if d.x >= 0.0 { to_box.left_center() } else { to_box.right_center() } + } else if d.y >= 0.0 { + to_box.center_top() + } else { + to_box.center_bottom() + }; + p.line_segment([side_middle(from, side), z], Stroke::new(1.5, accent.gamma_multiply(0.6))); } diff --git a/docs/boards-parity.md b/docs/boards-parity.md index 7526d39aa..dd14d1b9f 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -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-03 · **Change:** minor (a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); 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 @@ -38,7 +38,7 @@ all end with the same geometry. | 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 | -| 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 | +| 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. Dragging a "+" carries the preview ("drag the preview to any location on your board"): let go on empty board and the next one is made there, centred on the pointer, joined by a connector whose ends take the sides facing each other (`at: [x, y]`); let go on another sticky or shape and a connector joins the two instead, the object outlined while over it (`board_connect_tests`, #1919) | | 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 | | Connector paths reshaped by hand | done | a selected elbow or curved connector shows path handles: one on each run long enough to take one, one in the middle of a curve. 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 and is saved with the file; changing the style or moving an end to something else goes back to routing itself. No way back by itself otherwise: the public help describes none | @@ -70,6 +70,7 @@ all end with the same geometry. | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | M12, #1919: as the quick create help says ("Click to select and create the next shape in that direction, or drag the preview to any location on your board"; "A new shape is created with a connector and its text field active"), a "+" beside the selected sticky or shape can be dragged: the preview follows the pointer and, let go on empty board, the next one is made there, centred on the pointer and joined by a connector whose ends take the sides facing each other (`board.addConnected` gains `at: [x, y]`); let go on another sticky or shape, a connector joins the two instead (`board.connector`), that object outlined while the pointer is over it. The click is as before. A shape picker on drop and choosing the connector type are not done (the help doesn't describe them). Tests: `board_connect_tests` (two), engine `board_connected_tests::the_next_one_goes_where_it_is_dropped`. 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. | From 246a89733ca0b4472280d4729e008c75c699d0f5 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 3 Nov 2026 12:44:59 -0500 Subject: [PATCH 052/102] M12: quick-create drag: stickies and shapes in sections, parent coordinates, the handle's side, no drop off the canvas (#1919) Review: the drop target is the topmost sticky or shape under the pointer, sections and frames looked into (board::sticky_or_shape_at, instead of the stamp's any-layer hit test on the page's children); the drop point is placed in the parent's coordinates; the connector leaves by the handle's side (as the preview draws it) and arrives by the facing side; a handle let go off the canvas makes nothing; the parity rows on quick-create handles agree. Tests: dropping_a_handle_on_a_shape_inside_a_frame_joins_it, letting_a_handle_go_over_a_panel_makes_nothing, the_next_one_goes_where_it_is_dropped (frame case). Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/board_connected_tests.rs | 13 ++++++- crates/engine/src/boards/board.rs | 35 +++++++++++++++--- crates/engine/src/boards/board/items.rs | 11 +++++- crates/ui-egui/src/board_connect_tests.rs | 43 ++++++++++++++++++++++ crates/ui-egui/src/canvas/board_connect.rs | 19 +++++++--- docs/boards-parity.md | 8 ++-- 6 files changed, 111 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/board_connected_tests.rs b/crates/engine/src/board_connected_tests.rs index d6b962449..d23129c19 100644 --- a/crates/engine/src/board_connected_tests.rs +++ b/crates/engine/src/board_connected_tests.rs @@ -116,7 +116,18 @@ fn the_next_one_goes_where_it_is_dropped() { let (b, c) = (id(&r, "id"), id(&r, "connector")); assert_eq!(at(&s, b), (600.0, 0.0), "centred on the point"); let k = connector(&s, c); - assert_eq!((k.from, k.to), (End::Node { node: a, side: Side::Auto, at: None }, End::Node { node: b, side: Side::Auto, at: None })); + assert_eq!( + (k.from, k.to), + (End::Node { node: a, side: Side::Bottom, at: None }, End::Node { node: b, side: Side::Auto, at: None }), + "leaves by the handle's side" + ); + // Inside a frame at (1000, 500): the page point lands in the frame's coordinates. + let f = id(&s.execute("frame.create", &json!({"x": 1000, "y": 500, "width": 800, "height": 600})).unwrap(), "id"); + let inner = id(&s.execute("board.shape", &json!({"shape": "ellipse", "x": 0, "y": 0, "width": 200, "height": 120, "parent": f})).unwrap(), "id"); + let r = s.execute("board.addConnected", &json!({"id": inner, "at": [1300, 700]})).unwrap(); + let placed = id(&r, "id"); + assert_eq!(node(&s, placed).parent, Some(f), "beside it, in the frame"); + assert_eq!(at(&s, placed), (200.0, 140.0), "centred on the page point, in the frame's coordinates"); for wrong in [json!([1]), json!("x"), json!([0, "y"]), json!({"x": 1, "y": 2})] { assert!(s.execute("board.addConnected", &json!({"id": a, "at": wrong})).is_err(), "{wrong}"); } diff --git a/crates/engine/src/boards/board.rs b/crates/engine/src/boards/board.rs index d6c5dc255..1f10f5d94 100644 --- a/crates/engine/src/boards/board.rs +++ b/crates/engine/src/boards/board.rs @@ -34,11 +34,34 @@ use connectors::{connector_cmd, reattach}; pub use derived::route; pub(crate) use derived::{settle_routes, settle_stamps, settle_text, stamp_target}; -/// The sticky, shape or other object at `p` on `page`: the topmost layer of the page whose box -/// holds it (stamps, connectors, their labels and ink aside), other than `except`. What a stamp -/// sticks to, and what a "+" handle dragged onto it joins (#1919). -pub fn object_at(doc: &Document, page: NodeId, p: Point, except: Option) -> Option { - stamp_target(doc, page, p, except) +/// The topmost sticky or shape at `p` on `page`, other than `except`, sections and frames looked +/// into: what a "+" handle dragged onto it joins (#1919). +pub fn sticky_or_shape_at(doc: &Document, page: NodeId, p: Point, except: Option) -> Option { + fn find(doc: &Document, id: NodeId, p: Point, except: Option, depth: usize) -> Option { + let n = doc.node(id)?; + for c in n.children.iter().rev() { + let Some(k) = doc.node(*c) else { continue }; + if !k.visible { + continue; + } + match k.board { + Some(BoardItem::Sticky { .. } | BoardItem::Shape { .. }) => { + if Some(*c) != except && doc.world_bounds(*c).is_some_and(|b| b.contains(p)) { + return Some(*c); + } + } + // Not a board object of its own (a section, a frame): what is inside it may be. + None if depth < 32 => { + if let Some(hit) = find(doc, *c, p, except, depth + 1) { + return Some(hit); + } + } + _ => {} + } + } + None + } + find(doc, page, p, except, 0) } pub use edit::label_of; pub(crate) use edit::{copied_items, copy_map, rejoin}; @@ -121,7 +144,7 @@ pub fn specs() -> Vec { spec!( "board.addConnected", "Add connected shape", - "{id? (a sticky or shape; default the selected or edited one), side?: right|below|left|above (default right), at? ([x, y] on the page: the next one's centre, anywhere, instead of its place on that side; the connector then takes the sides facing each other), edit? (start typing in it; default false)} → {id, text, connector} the next one of the same kind, size and colour on that side, joined by a connector", + "{id? (a sticky or shape; default the selected or edited one), side?: right|below|left|above (default right), at? ([x, y] on the page: the next one's centre, anywhere, instead of its place on that side; the connector then leaves by `side` and arrives by the side facing it), edit? (start typing in it; default false)} → {id, text, connector} the next one of the same kind, size and colour on that side, joined by a connector", true, add_connected ), diff --git a/crates/engine/src/boards/board/items.rs b/crates/engine/src/boards/board/items.rs index 981a8399e..b409eeb90 100644 --- a/crates/engine/src/boards/board/items.rs +++ b/crates/engine/src/boards/board/items.rs @@ -224,9 +224,16 @@ pub(super) fn add_connected(s: &mut Session, p: &Value) -> Result { let (to_at, from_side, to_side) = connected_place((at.x, at.y), (n.width, n.height), next, &side) .ok_or_else(|| bad(cmd, format!("`side` is right, below, left or above, not `{side}`")))?; // Dropped somewhere by hand ("drag the preview to any location on your board", #1919): the - // next one is centred there, and the connector joins the sides facing each other. + // next one is centred on that point of the page (placed in the parent's coordinates), and the + // connector leaves by the handle's side and arrives by the side facing it. let (to_at, from_side, to_side) = match drop_point(cmd, p)? { - Some((x, y)) => ((x - next.0 / 2.0, y - next.1 / 2.0), Side::Auto, Side::Auto), + Some((x, y)) => { + let local = doc.world_transform(parent).inverse() * figcraft_geom::Point::new(x, y); + if !(local.x.is_finite() && local.y.is_finite()) { + return Err(bad(cmd, "`at` can't be placed in that parent")); + } + ((local.x - next.0 / 2.0, local.y - next.1 / 2.0), from_side, Side::Auto) + } None => (to_at, from_side, to_side), }; let (routing, author, page) = (s.tool.board.routing, author(s), s.page()?); diff --git a/crates/ui-egui/src/board_connect_tests.rs b/crates/ui-egui/src/board_connect_tests.rs index f3e4dc612..7d109dbb3 100644 --- a/crates/ui-egui/src/board_connect_tests.rs +++ b/crates/ui-egui/src/board_connect_tests.rs @@ -193,3 +193,46 @@ fn dropping_a_handle_on_another_shape_joins_them() { let line = doc.ids().find(|i| matches!(doc.node(*i).unwrap().board, Some(BoardItem::Connector(_)))).expect("a connector"); assert!(matches!(&doc.node(line).unwrap().board, Some(BoardItem::Connector(c)) if c.from.node() == Some(a) && c.to.node() == Some(b))); } + +/// A sticky or shape inside a section or frame takes the drop too (review): the connector joins it. +#[test] +fn dropping_a_handle_on_a_shape_inside_a_frame_joins_it() { + let (mut u, a) = board_with_shape(); + let f = id(&u.app.session.execute("frame.create", &json!({"x": 300, "y": 200, "width": 500, "height": 400})).unwrap()); + let b = id(&u + .app + .session + .execute("board.shape", &json!({"shape": "ellipse", "x": 100, "y": 100, "width": 160, "height": 100, "parent": f})) + .unwrap()); + u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap(); + u.frame(vec![]); + u.frame(vec![]); + let from = handle(&u, "right").expect("a handle right").center(); + let to = screen_box(&u, b).center(); + u.drag_to(from, to); + u.button(to, false); + u.frame(vec![]); + let doc = u.app.session.doc().unwrap(); + let line = doc.ids().find(|i| matches!(doc.node(*i).unwrap().board, Some(BoardItem::Connector(_)))).expect("a connector"); + assert!( + matches!(&doc.node(line).unwrap().board, Some(BoardItem::Connector(c)) if c.from.node() == Some(a) && c.to.node() == Some(b)), + "joined to the shape in the frame, not the frame" + ); +} + +/// A handle let go off the canvas, over a panel, makes nothing (review). +#[test] +fn letting_a_handle_go_over_a_panel_makes_nothing() { + let (mut u, a) = board_with_shape(); + u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap(); + u.frame(vec![]); + u.frame(vec![]); + let before = u.app.session.doc().unwrap().ids().count(); + let from = handle(&u, "left").expect("a handle left").center(); + // The left sidebar. + let to = Pos2::new(u.app.canvas.rect.min.x - 60.0, from.y); + u.drag_to(from, to); + u.button(to, false); + u.frame(vec![]); + assert_eq!(u.app.session.doc().unwrap().ids().count(), before, "nothing made"); +} diff --git a/crates/ui-egui/src/canvas/board_connect.rs b/crates/ui-egui/src/canvas/board_connect.rs index aaac45af9..4ea0d9a4d 100644 --- a/crates/ui-egui/src/canvas/board_connect.rs +++ b/crates/ui-egui/src/canvas/board_connect.rs @@ -2,12 +2,13 @@ //! where the next one goes; clicking it makes the next of the same kind there, joined by a //! connector, and starts typing in it (`board.addConnected`). Dragging one carries the preview //! ("drag the preview to any location on your board", #1919): let go on empty board and the next -//! one is made there, joined; let go on another sticky or shape and a connector joins the two. +//! one is made there, joined by a connector leaving by the handle's side; let go on another sticky +//! or shape (inside a section too) and a connector joins the two; let go off the canvas, nothing. use egui::{Area, Color32, CornerRadius, Id, LayerId, Order, Pos2, Rect, Sense, Shape, Stroke, StrokeKind, pos2, vec2}; use figcraft_doc::{BoardItem, NodeId}; use figcraft_engine::ToolId; -use figcraft_engine::board::{STICKY, connected_place, object_at}; +use figcraft_engine::board::{STICKY, connected_place, sticky_or_shape_at}; use serde_json::json; use crate::FigApp; @@ -149,9 +150,16 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) { let Some(Drag { from, side }) = drag.filter(|d| d.from == id) else { return }; let Some(pointer) = ctx.input(|i| i.pointer.latest_pos()) else { return }; let over = object_under(app, from, pointer); - drag_preview(app, ctx, (b, next, side), pointer, over); + // Off the canvas (over a panel) there is nothing to show and nothing to make. + let on_canvas = app.canvas.rect.contains(pointer); + if on_canvas { + drag_preview(app, ctx, (b, next, side), pointer, over); + } if let_go { ctx.data_mut(|d| d.remove::(drag_id())); + if !on_canvas { + return; + } match over { Some(to) => { app.run("board.connector", json!({"from": from, "to": to, "fromSide": connector_side(side)})); @@ -167,13 +175,14 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) { } } -/// The sticky, shape or other object under the screen point `p` on the canvas, other than `except`. +/// The sticky or shape under the screen point `p` on the canvas (inside a section or frame too), +/// other than `except`. fn object_under(app: &FigApp, except: NodeId, p: Pos2) -> Option { if !app.canvas.rect.contains(p) { return None; } let ds = app.session.ds().ok()?; - object_at(&ds.doc, ds.page, app.to_page(p), Some(except)) + sticky_or_shape_at(&ds.doc, ds.page, app.to_page(p), Some(except)) } /// Where the next one goes for `side`, faintly: its box and the connector's line to it. diff --git a/docs/boards-parity.md b/docs/boards-parity.md index dd14d1b9f..115885f0b 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -38,13 +38,13 @@ all end with the same geometry. | 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 | -| 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. Dragging a "+" carries the preview ("drag the preview to any location on your board"): let go on empty board and the next one is made there, centred on the pointer, joined by a connector whose ends take the sides facing each other (`at: [x, y]`); let go on another sticky or shape and a connector joins the two instead, the object outlined while over it (`board_connect_tests`, #1919) | +| 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. Dragging a "+" carries the preview ("drag the preview to any location on your board"): let go on empty board and the next one is made there, centred on the pointer, joined by a connector leaving by the handle's side (`at: [x, y]`, a point of the page); let go on another sticky or shape, inside a section too, and a connector joins the two instead, the object outlined while over it; let go off the canvas, nothing (`board_connect_tests`, #1919) | | 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 | | Connector paths reshaped by hand | done | a selected elbow or curved connector shows path handles: one on each run long enough to take one, one in the middle of a curve. 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 and is saved with the file; changing the style or moving an end to something else goes back to routing itself. No way back by itself otherwise: the public help describes none | -| Quick-create handles (drag out a connected copy) | missing | | +| Quick-create handles (drag out a connected copy) | done | a "+" dragged carries the preview: the next one is made where it is let go, joined; or a connector joins the sticky or shape it is let go on (#1919) | | Connector waypoints placed by hand | missing | routes are computed from the ends; no bend points of your own | -| Quick-create handles | partial | a "+" beside each side of the one selected sticky or shape makes the next one there, joined by a connector (`board.addConnected`, also Shift+Cmd/Ctrl+Enter); no dragging a handle out to place it | +| Quick-create handles | done | a "+" beside each side of the one selected sticky or shape makes the next one there, joined by a connector (`board.addConnected`, also Shift+Cmd/Ctrl+Enter); dragged, it places the next one where it is let go, or joins the sticky or shape it is let go on (#1919) | | Marker and highlighter | done | the Pencil's stroke fitting with board presets: marker opaque, highlighter wide, see-through and multiplying | | Eraser | done | drag over marker and highlighter strokes to remove them, one undo step | | Pen colours and widths in the toolbar | partial | `tool.marker {color}`, `tool.highlighter {color}`; colour changes on a selected stroke from the contextual bar | @@ -70,7 +70,7 @@ all end with the same geometry. | Date | Change | Summary | |---|---|---| -| 2026-11-03 | minor | M12, #1919: as the quick create help says ("Click to select and create the next shape in that direction, or drag the preview to any location on your board"; "A new shape is created with a connector and its text field active"), a "+" beside the selected sticky or shape can be dragged: the preview follows the pointer and, let go on empty board, the next one is made there, centred on the pointer and joined by a connector whose ends take the sides facing each other (`board.addConnected` gains `at: [x, y]`); let go on another sticky or shape, a connector joins the two instead (`board.connector`), that object outlined while the pointer is over it. The click is as before. A shape picker on drop and choosing the connector type are not done (the help doesn't describe them). Tests: `board_connect_tests` (two), engine `board_connected_tests::the_next_one_goes_where_it_is_dropped`. Numbers unchanged. | +| 2026-11-03 | minor | M12, #1919: as the quick create help says ("Click to select and create the next shape in that direction, or drag the preview to any location on your board"; "A new shape is created with a connector and its text field active"), a "+" beside the selected sticky or shape can be dragged: the preview follows the pointer and, let go on empty board, the next one is made there, centred on the pointer, and joined by a connector leaving by the handle's side and arriving by the side facing it (`board.addConnected` gains `at: [x, y]`, a point of the page placed in the parent's coordinates); let go on another sticky or shape, inside a section or frame too (`board::sticky_or_shape_at`), a connector joins the two instead (`board.connector`), that object outlined while the pointer is over it; let go off the canvas, nothing. The click is as before. A shape picker on drop and choosing the connector type are not done (the help doesn't describe them). Tests: `board_connect_tests` (two), engine `board_connected_tests::the_next_one_goes_where_it_is_dropped`. 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. | From 96ef28cc67f56421b71b615022a3b6728d29978a Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 3 Nov 2026 13:42:03 -0500 Subject: [PATCH 053/102] M12: quick-create drag ends when the selection moves; no drop on the toolbar (#1919) Review: a drag whose object is no longer the selected one is dropped from egui's data at once (it lingered when the selection moved to another sticky or shape and could still act once the first was selected again); a handle let go over the floating toolbar, which lies inside the canvas rectangle, makes nothing, like one let go over a panel. Tests: a_drag_ends_when_the_selection_moves_to_another_shape, letting_a_handle_go_over_the_toolbar_makes_nothing. Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/board_connect_tests.rs | 39 ++++++++++++++++++++++ crates/ui-egui/src/canvas/board_connect.rs | 12 +++++-- 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/board_connect_tests.rs b/crates/ui-egui/src/board_connect_tests.rs index 7d109dbb3..b6466a9ff 100644 --- a/crates/ui-egui/src/board_connect_tests.rs +++ b/crates/ui-egui/src/board_connect_tests.rs @@ -236,3 +236,42 @@ fn letting_a_handle_go_over_a_panel_makes_nothing() { u.frame(vec![]); assert_eq!(u.app.session.doc().unwrap().ids().count(), before, "nothing made"); } + +/// A handle let go over the floating toolbar at the bottom of the canvas makes nothing either +/// (review): the toolbar lies inside the canvas rectangle. +#[test] +fn letting_a_handle_go_over_the_toolbar_makes_nothing() { + let (mut u, a) = board_with_shape(); + u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap(); + u.frame(vec![]); + u.frame(vec![]); + let before = u.app.session.doc().unwrap().ids().count(); + let from = handle(&u, "below").expect("a handle below").center(); + let to = crate::toolbar::pill_rect(u.app.canvas.rect, crate::toolbar::bar_width(&u.app)).center(); + u.drag_to(from, to); + u.button(to, false); + u.frame(vec![]); + assert_eq!(u.app.session.doc().unwrap().ids().count(), before, "nothing made behind the toolbar"); +} + +/// The selection moving to another shape under a drag ends the drag (review): letting go later, +/// even with the first shape selected again, makes nothing. +#[test] +fn a_drag_ends_when_the_selection_moves_to_another_shape() { + let (mut u, a) = board_with_shape(); + let b = id(&u.app.session.execute("board.shape", &json!({"shape": "ellipse", "x": 600, "y": 0, "width": 160, "height": 100})).unwrap()); + u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap(); + u.frame(vec![]); + u.frame(vec![]); + let before = u.app.session.doc().unwrap().ids().count(); + let from = handle(&u, "below").expect("a handle below").center(); + let to = from + egui::vec2(0.0, 160.0); + u.drag_to(from, to); + u.app.session.execute("select.set", &json!({"ids": [b]})).unwrap(); + u.frame(vec![Event::PointerMoved(to)]); + u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap(); + u.frame(vec![Event::PointerMoved(to)]); + u.button(to, false); + u.frame(vec![]); + assert_eq!(u.app.session.doc().unwrap().ids().count(), before, "the drag was over"); +} diff --git a/crates/ui-egui/src/canvas/board_connect.rs b/crates/ui-egui/src/canvas/board_connect.rs index 4ea0d9a4d..b78946ef3 100644 --- a/crates/ui-egui/src/canvas/board_connect.rs +++ b/crates/ui-egui/src/canvas/board_connect.rs @@ -147,11 +147,17 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) { } // A drag carries the preview: the next one centred on the pointer, or the object under it, // which the connector joins instead. - let Some(Drag { from, side }) = drag.filter(|d| d.from == id) else { return }; + let Some(Drag { from, side }) = drag else { return }; + // The selection moved to another sticky or shape under the drag: it is over too. + if from != id { + ctx.data_mut(|d| d.remove::(drag_id())); + return; + } let Some(pointer) = ctx.input(|i| i.pointer.latest_pos()) else { return }; let over = object_under(app, from, pointer); - // Off the canvas (over a panel) there is nothing to show and nothing to make. - let on_canvas = app.canvas.rect.contains(pointer); + // Off the canvas (over a panel) or over the floating toolbar there is nothing to show and + // nothing to make. + let on_canvas = app.canvas.rect.contains(pointer) && !toolbar.contains(pointer); if on_canvas { drag_preview(app, ctx, (b, next, side), pointer, over); } From a23c9df9d60d15150d497ab10f3c3e747e266796 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 19:03:55 +0000 Subject: [PATCH 054/102] fix(engine): escape Vue attribute values that follow literal text in a Code Connect template --- crates/engine/src/code_connect_tests.rs | 3 +++ crates/engine/src/dev/code_connect.rs | 28 ++++++++++++++----------- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/code_connect_tests.rs b/crates/engine/src/code_connect_tests.rs index 24e03e4bb..69f655ec6 100644 --- a/crates/engine/src/code_connect_tests.rs +++ b/crates/engine/src/code_connect_tests.rs @@ -260,6 +260,9 @@ fn vue_links_are_a_default_import_with_quoted_bindings() { ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Title": "Say \"hi\""}})); ex(&mut s, "codeConnect.set", json!({"id": i, "language": "vue", "template": ""})); assert_eq!(code(&mut s, i, "vue"), "import Card from \"./Card.vue\";\n\n\n"); + // Literal text before the first placeholder keeps it inside the attribute value. + ex(&mut s, "codeConnect.set", json!({"id": i, "language": "vue", "template": ""})); + assert_eq!(code(&mut s, i, "vue"), "import Card from \"./Card.vue\";\n\n\n"); // Text after a completed tag is text, even when it contains `=`. ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Title": "Buy"}})); ex(&mut s, "codeConnect.set", json!({"id": i, "language": "vue", "template": "

Total = {title}

"})); diff --git a/crates/engine/src/dev/code_connect.rs b/crates/engine/src/dev/code_connect.rs index 33bb594b0..fe67ba1e9 100644 --- a/crates/engine/src/dev/code_connect.rs +++ b/crates/engine/src/dev/code_connect.rs @@ -288,41 +288,45 @@ fn pieces(t: &str) -> Vec> { checkable.then(|| parse(t).ok()).flatten().unwrap_or_else(|| vec![Piece::Text(t)]) } -/// Whether `s` ends inside an unclosed opening tag (no `>` outside quotes since the last `<`). -fn inside_open_tag(s: &str) -> bool { +/// Whether `s` ends inside an unclosed opening tag (no `>` outside quotes since the last `<`), and +/// the quote (with its byte offset) still open there. +fn tag_state(s: &str) -> (bool, Option<(char, usize)>) { let mut in_tag = false; let mut quote = None; - let mut chars = s.chars().peekable(); - while let Some(c) = chars.next() { + let mut chars = s.char_indices().peekable(); + while let Some((i, c)) = chars.next() { match quote { - Some(q) => { + Some((q, _)) => { if c == q { quote = None; } } None => match c { - '<' if !in_tag && chars.peek().is_some_and(|ch| ch.is_ascii_alphabetic() || matches!(*ch, '/' | '!' | '?')) => { + '<' if !in_tag && chars.peek().is_some_and(|(_, ch)| ch.is_ascii_alphabetic() || matches!(*ch, '/' | '!' | '?')) => { in_tag = true; } '>' if in_tag => in_tag = false, - '"' | '\'' if in_tag => quote = Some(c), + '"' | '\'' if in_tag => quote = Some((c, i)), _ => {} }, } } - in_tag + (in_tag, quote) } /// Where a placeholder sits in a Vue template: whether the attribute is bound, and the quote the /// template already opened (if any). `None` when it isn't in an attribute at all. fn vue_attribute(out: &str) -> Option<(bool, Option)> { let end = out.trim_end(); - if !inside_open_tag(end) { + let (in_tag, open) = tag_state(out); + if !in_tag { return None; } - let (after, quote) = match end.chars().last() { - Some(q @ ('"' | '\'')) => (&end[..end.len() - q.len_utf8()], Some(q)), - _ => (end, None), + // A quote still open, with literal text after it (`title="Buy {x}"`), puts the placeholder in + // that attribute's value as much as one directly after the quote does. + let (after, quote) = match open { + Some((q, at)) => (&out[..at], Some(q)), + None => (end, None), }; let after = after.trim_end(); let eq = after.rfind('=')?; From 024b7fe45284ce0206b4e732720a7506b7ad53fa Mon Sep 17 00:00:00 2001 From: MortenHusted Date: Tue, 3 Nov 2026 09:53:18 +0100 Subject: [PATCH 055/102] M3: importing a file keeps its own variables and styles when their ids are already taken `file.import` of a FigCraft file kept the document's style, variable or collection for every id both files used, and the pasted layers kept those ids. Ids are numbered per file, so two files made apart share them, and the imported layers were bound to the document's unrelated variables, modes and styles. `append_pages` now gives the incoming file new ids first (`Renames`): - an incoming style, variable or collection is shared, as before, only when the document has the same under its id and everything it names is shared too (the same file imported again); a collection and its variables are shared only together; library copies keep their ids; - every other id the document already uses gets a new one from its allocators, which now take ids to avoid (the incoming file's own); - layers' style links, bindings, explicit modes and prototype actions, styles' bindings, variables' collections, aliases, calculations and extensions, and the renamed collections' mode ids follow. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/ids.rs | 27 +- crates/doc/src/ids_tests.rs | 16 ++ crates/engine/src/cmd/file.rs | 1 + crates/engine/src/cmd/file/import_ids.rs | 254 +++++++++++++++++++ crates/engine/src/cmd/file/open.rs | 13 +- crates/engine/src/import_ids_tests.rs | 172 +++++++++++++ crates/engine/src/lib.rs | 2 + crates/engine/src/library_variables_tests.rs | 28 ++ 8 files changed, 508 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/cmd/file/import_ids.rs create mode 100644 crates/engine/src/import_ids_tests.rs diff --git a/crates/doc/src/ids.rs b/crates/doc/src/ids.rs index 7e244fbb0..622ca807e 100644 --- a/crates/doc/src/ids.rs +++ b/crates/doc/src/ids.rs @@ -14,6 +14,8 @@ //! space 0. The session server accepts a new object only with an id in its creator's space or //! space 0, so two people never make the same id. +use std::collections::BTreeSet; + use crate::{CollectionId, Document, ModeId, NodeId, StyleId, VariableId}; /// What style ids start with. @@ -74,25 +76,42 @@ impl Document { /// A new style id. pub fn new_style_id(&mut self) -> StyleId { - let taken: Vec = self.styles.iter().filter_map(|s| id_number(&s.id, STYLE_ID_PREFIX)).collect(); + self.new_style_id_avoiding(&BTreeSet::new()) + } + + /// A new style id that is none of `avoid` either: ids of styles about to come in with a file + /// being imported. + pub fn new_style_id_avoiding(&mut self, avoid: &BTreeSet) -> StyleId { + let taken: Vec = self.styles.iter().map(|s| &s.id).chain(avoid).filter_map(|id| id_number(id, STYLE_ID_PREFIX)).collect(); if let Some(n) = self.session_number(taken) { return format!("{STYLE_ID_PREFIX}{n}"); } (self.styles.len() + 1..) .map(|k| format!("{STYLE_ID_PREFIX}{k}")) - .find(|id| self.style(id).is_none()) + .find(|id| self.style(id).is_none() && !avoid.contains(id)) .unwrap_or_else(|| format!("{STYLE_ID_PREFIX}0")) } /// A new variable id. pub fn new_variable_id(&mut self) -> VariableId { - let taken: Vec = self.variables.variables.iter().filter_map(|v| id_number(&v.id, VARIABLE_ID_PREFIX)).collect(); + self.new_variable_id_avoiding(&BTreeSet::new()) + } + + /// A new variable id that is none of `avoid` either (see [`Self::new_style_id_avoiding`]). + pub fn new_variable_id_avoiding(&mut self, avoid: &BTreeSet) -> VariableId { + let taken = self.variables.variables.iter().map(|v| &v.id).chain(avoid).filter_map(|id| id_number(id, VARIABLE_ID_PREFIX)).collect(); self.new_numbered_id(VARIABLE_ID_PREFIX, taken) } /// A new variable collection id. pub fn new_collection_id(&mut self) -> CollectionId { - let taken: Vec = self.variables.collections.iter().filter_map(|c| id_number(&c.id, COLLECTION_ID_PREFIX)).collect(); + self.new_collection_id_avoiding(&BTreeSet::new()) + } + + /// A new variable collection id that is none of `avoid` either (see + /// [`Self::new_style_id_avoiding`]). + pub fn new_collection_id_avoiding(&mut self, avoid: &BTreeSet) -> CollectionId { + let taken = self.variables.collections.iter().map(|c| &c.id).chain(avoid).filter_map(|id| id_number(id, COLLECTION_ID_PREFIX)).collect(); self.new_numbered_id(COLLECTION_ID_PREFIX, taken) } diff --git a/crates/doc/src/ids_tests.rs b/crates/doc/src/ids_tests.rs index a0091623d..e725c2ce4 100644 --- a/crates/doc/src/ids_tests.rs +++ b/crates/doc/src/ids_tests.rs @@ -1,6 +1,8 @@ //! Ids of styles, variables, collections, modes and comments: unchanged outside a live session, //! from the client's own space during one. +use std::collections::BTreeSet; + use crate::ids::{COLLECTION_ID_PREFIX, id_number, id_space, mode_number, space_of}; use crate::{Collection, Comment, Document, Message, Mode, NodeId, NodeKind, Style, StyleKind}; @@ -93,6 +95,20 @@ fn ids_of_the_space_already_in_the_document_stay_taken() { assert_eq!(e.new_style_id(), format!("S:{}", C3 | 1)); } +#[test] +fn new_ids_can_avoid_ids_about_to_come_in() { + let mut d = Document::new("a"); + d.styles.push(style("S:1")); + let avoid: BTreeSet = ["S:2", "S:3", "VariableID:4", "VariableCollectionId:2", "lib:VariableID:9"].map(String::from).into(); + assert_eq!(d.new_style_id_avoiding(&avoid), "S:4"); + assert_eq!(d.new_variable_id_avoiding(&avoid), "VariableID:5"); + assert_eq!(d.new_collection_id_avoiding(&avoid), "VariableCollectionId:3"); + // In a session the numbers come from the client's space, above those of it to avoid. + let avoid: BTreeSet = [format!("VariableID:{}", C3 | 7)].into(); + d.set_client_id(3); + assert_eq!(d.new_variable_id_avoiding(&avoid), format!("VariableID:{}", C3 | 8)); +} + #[test] fn the_highest_space_counts_every_kind_of_id() { let mut d = Document::new("a"); diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 0cfdd1ffa..79de7c28c 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -15,6 +15,7 @@ use crate::params::{bool_of, boolean, get, id, num, num_or, req_index, req_strin use crate::{DocState, EngineError, Result, Session, bad, spec}; mod export; +mod import_ids; mod load; mod open; mod save; diff --git a/crates/engine/src/cmd/file/import_ids.rs b/crates/engine/src/cmd/file/import_ids.rs new file mode 100644 index 000000000..2b6a7e697 --- /dev/null +++ b/crates/engine/src/cmd/file/import_ids.rs @@ -0,0 +1,254 @@ +//! Ids a file being imported brings that the document already uses for something else. +//! +//! Style, variable and collection ids are numbered per file (`S:1`, `VariableID:1`, +//! `VariableCollectionId:1`; see [`figcraft_doc::ids`]), so two files made apart use the same ones +//! for unrelated things. Kept as they were, the imported layers would show the document's +//! variables and styles instead of their own. + +use std::collections::{BTreeMap, BTreeSet}; + +use figcraft_doc::ids::MODE_ID_INFIX; +use figcraft_doc::proto::{Action, Expr, MAX_EXPR_DEPTH, walk_mut}; +use figcraft_doc::{Document, ModeId, NodeId, NodeKind, VariableValue, Variables}; + +/// A style, variable or collection of the file being imported. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum Asset<'a> { + Style(&'a str), + Variable(&'a str), + Collection(&'a str), +} + +/// New ids for styles, variables and collections of a file being imported (its id → the new one). +#[derive(Debug, Default)] +pub(super) struct Renames { + styles: BTreeMap, + variables: BTreeMap, + collections: BTreeMap, +} + +impl Renames { + /// The new ids `other`'s styles, variables and collections take when appended to `doc`. + /// + /// One whose id `doc` doesn't use keeps it. One `doc` already has is shared and keeps its id: + /// the same content under the same id, naming only things that are shared too (the same file + /// imported again). A collection and its variables are shared only all together, so variables + /// of one file never join a collection of another. Library copies keep their ids and are shared + /// with the document's copies, as before (`merge_store` records them). Every other id `doc` + /// already uses is replaced by a new one from `doc`'s allocators, clear of `other`'s ids too. + pub(super) fn new(doc: &mut Document, other: &Document) -> Renames { + let (theirs, libs) = (&other.variables, &other.libraries); + // Each with whether `doc` has the same under its id (None: nothing there), and whether + // it's a library copy. + let styles = other.styles.iter().map(|s| { + let here = doc.styles.iter().find(|m| m.id == s.id); + (Asset::Style(&s.id), here.map(|m| m == s), libs.style_import(&s.id).is_some()) + }); + let colls = theirs.collections.iter().map(|c| { + let here = doc.variables.collection_by_id(&c.id); + (Asset::Collection(&c.id), here.map(|m| m == c), libs.collection_import(&c.id).is_some()) + }); + let vars = theirs.variables.iter().map(|v| { + let here = doc.variables.get_by_id(&v.id); + (Asset::Variable(&v.id), here.map(|m| m == v), libs.variable_import(&v.id).is_some()) + }); + // `taken`: ids `doc` uses; `differs`: what `doc` doesn't have the same of. + let (mut taken, mut copies, mut differs) = (BTreeSet::new(), BTreeSet::new(), BTreeSet::new()); + for (a, same, copy) in styles.chain(colls).chain(vars) { + match same { + None => { + differs.insert(a); + } + Some(same) => { + taken.insert(a); + if copy { + copies.insert(a); + } else if !same { + differs.insert(a); + } + } + } + } + // What differs makes what names it differ (library copies aside), and a collection and its + // variables differ together. + let mut named_by: BTreeMap> = BTreeMap::new(); + for v in &theirs.variables { + let (var, coll) = (Asset::Variable(&v.id), Asset::Collection(&v.collection)); + named_by.entry(coll).or_default().push(var); + named_by.entry(var).or_default().push(coll); + for r in v.values.values().flat_map(VariableValue::references).chain(&v.extends) { + named_by.entry(Asset::Variable(r)).or_default().push(var); + } + } + for c in &theirs.collections { + if let Some(e) = &c.extends { + named_by.entry(Asset::Collection(e)).or_default().push(Asset::Collection(&c.id)); + } + } + for s in &other.styles { + for v in s.bound.values() { + named_by.entry(Asset::Variable(v)).or_default().push(Asset::Style(&s.id)); + } + } + let mut todo: Vec = differs.iter().copied().collect(); + while let Some(a) = todo.pop() { + for &n in named_by.get(&a).into_iter().flatten() { + if !copies.contains(&n) && differs.insert(n) { + todo.push(n); + } + } + } + let renamed = |a: Asset| taken.contains(&a) && differs.contains(&a); + Renames { + collections: fresh( + theirs.collections.iter().map(|c| &c.id), + |id| renamed(Asset::Collection(id)), + |avoid| doc.new_collection_id_avoiding(avoid), + ), + variables: fresh(theirs.variables.iter().map(|v| &v.id), |id| renamed(Asset::Variable(id)), |avoid| doc.new_variable_id_avoiding(avoid)), + styles: fresh(other.styles.iter().map(|s| &s.id), |id| renamed(Asset::Style(id)), |avoid| doc.new_style_id_avoiding(avoid)), + } + } + + pub(super) fn is_empty(&self) -> bool { + self.styles.is_empty() && self.variables.is_empty() && self.collections.is_empty() + } + + /// `other` with the renamed styles, variables and collections under their new ids, and what + /// names them following: layers' style links (text ranges too), bindings, explicit modes and + /// prototype actions; styles' bindings; variables' collections, aliases and calculations; what + /// extended collections and their variables extend; and the ids of the renamed collections' + /// modes, which name their collection (`/mode`). + pub(super) fn applied(&self, other: &Document) -> Document { + let theirs = &other.variables; + let mut doc = other.clone(); + let (styles, vars, colls) = (&self.styles, &self.variables, &self.collections); + for s in &mut doc.styles { + rename(styles, &mut s.id); + s.bound.values_mut().for_each(|v| rename(vars, v)); + } + for c in &mut doc.variables.collections { + for m in &mut c.modes { + self.mode(theirs, &c.id, &mut m.id); + } + for id in std::iter::once(&mut c.id).chain(&mut c.extends) { + rename(colls, id); + } + } + for v in &mut doc.variables.variables { + let values = std::mem::take(&mut v.values).into_iter().map(|(mut mode, mut val)| { + self.mode(theirs, &v.collection, &mut mode); + val.references_mut().into_iter().for_each(|r| rename(vars, r)); + (mode, val) + }); + v.values = values.collect(); + let overrides = std::mem::take(&mut v.overrides).into_iter().map(|mut mode| { + self.mode(theirs, &v.collection, &mut mode); + mode + }); + v.overrides = overrides.collect(); + rename(colls, &mut v.collection); + for id in std::iter::once(&mut v.id).chain(&mut v.extends) { + rename(vars, id); + } + } + let ids: Vec = doc.ids().collect(); + for id in ids { + let Some(n) = doc.node_mut(id) else { continue }; + let links = [&mut n.styles.fill, &mut n.styles.stroke, &mut n.styles.effect, &mut n.styles.grid, &mut n.styles.text]; + for s in links.into_iter().flatten() { + rename(styles, s); + } + if let NodeKind::Text(t) = &mut n.kind { + t.map_text_styles(|s| Some(styles.get(s).cloned().unwrap_or_else(|| s.to_string()))); + } + n.bound.values_mut().for_each(|v| rename(vars, v)); + n.var_modes = std::mem::take(&mut n.var_modes) + .into_iter() + .map(|(mut c, mut mode)| { + self.mode(theirs, &c, &mut mode); + rename(colls, &mut c); + (c, mode) + }) + .collect(); + for it in &mut n.interactions { + walk_mut(&mut it.actions, &mut |a| self.action(theirs, a)); + } + } + doc + } + + /// Rename mode `mode` of collection `of` (`theirs`: the imported file's variables as they were). + /// A mode id names the collection it was made in: `of`, or one `of` extends (an extended + /// collection has the modes of the one it extends). Library copies keep their library's mode + /// ids, which may name one of the file's own collections. + fn mode(&self, theirs: &Variables, of: &str, mode: &mut ModeId) { + let mut at = Some(of); + for _ in 0..=theirs.collections.len() { + let Some(c) = at else { return }; + if let Some(k) = mode.strip_prefix(c).and_then(|rest| rest.strip_prefix(MODE_ID_INFIX)) { + if let Some(new) = self.collections.get(c) { + *mode = format!("{new}{MODE_ID_INFIX}{k}"); + } + return; + } + at = theirs.collection_by_id(c).and_then(|c| c.extends.as_deref()); + } + } + + /// Rename what one prototype action names (not the actions nested in it). + fn action(&self, theirs: &Variables, a: &mut Action) { + match a { + Action::SetVariable { variable, expr, .. } => { + rename(&self.variables, variable); + if let Some(e) = expr { + self.expr(theirs, e, 0); + } + } + Action::SetVariableMode { collection, mode } => { + self.mode(theirs, collection, mode); + rename(&self.collections, collection); + } + Action::Conditional { blocks } => blocks.iter_mut().filter_map(|b| b.condition.as_mut()).for_each(|c| self.expr(theirs, c, 0)), + _ => {} + } + } + + fn expr(&self, theirs: &Variables, e: &mut Expr, depth: usize) { + match e { + Expr::Value(v) => v.references_mut().into_iter().for_each(|r| rename(&self.variables, r)), + Expr::Op { args, .. } if depth < MAX_EXPR_DEPTH => args.iter_mut().for_each(|a| self.expr(theirs, a, depth + 1)), + Expr::Op { .. } => {} + Expr::Mode { collection } => rename(&self.collections, collection), + Expr::InMode { variable, mode } => { + if let Some(v) = theirs.get_by_id(variable) { + self.mode(theirs, &v.collection, mode); + } + rename(&self.variables, variable); + } + } + } +} + +/// New ids, from `new_id`, for those of `ids` that `pick` picks; each clear of all of `ids`. +fn fresh<'a>( + ids: impl Iterator + Clone, + pick: impl Fn(&str) -> bool, + mut new_id: impl FnMut(&BTreeSet) -> String, +) -> BTreeMap { + let mut avoid: BTreeSet = ids.clone().cloned().collect(); + let mut out = BTreeMap::new(); + for id in ids.filter(|id| pick(id)) { + let new = new_id(&avoid); + avoid.insert(new.clone()); + out.insert(id.clone(), new); + } + out +} + +/// `id` as `map` renames it. +fn rename(map: &BTreeMap, id: &mut String) { + if let Some(new) = map.get(id.as_str()) { + *id = new.clone(); + } +} diff --git a/crates/engine/src/cmd/file/open.rs b/crates/engine/src/cmd/file/open.rs index 59afad98d..795584595 100644 --- a/crates/engine/src/cmd/file/open.rs +++ b/crates/engine/src/cmd/file/open.rs @@ -1,3 +1,4 @@ +use super::import_ids::Renames; use super::load::{ext, file_stem, import_summary, load_path, load_with, read, rest_images, sibling_variables, variables_param}; use super::*; @@ -218,8 +219,18 @@ pub(super) fn import(s: &mut Session, p: &Value) -> Result { /// Append `other`'s pages (with their settings and flows, its images, styles and variables) to /// `doc`. Ids are remapped across all pages at once, so instances keep their main, instance layers /// their source and interactions and flows their targets wherever those are. Styles, variables and -/// collections whose id the document already has are kept as they are. +/// collections the document already has (the same under the same id, as when a file comes in +/// again) and library copies are shared; others whose id the document uses for something else get +/// new ids, and what comes in names them by those ([`Renames`]). pub(super) fn append_pages(doc: &mut Document, other: &Document) -> Result> { + let renames = Renames::new(doc, other); + let renamed; + let other = if renames.is_empty() { + other + } else { + renamed = renames.applied(other); + &renamed + }; for (k, v) in &other.images { doc.images.entry(k.clone()).or_insert_with(|| v.clone()); } diff --git a/crates/engine/src/import_ids_tests.rs b/crates/engine/src/import_ids_tests.rs new file mode 100644 index 000000000..263aa8169 --- /dev/null +++ b/crates/engine/src/import_ids_tests.rs @@ -0,0 +1,172 @@ +//! `file.import` of a file whose style, variable and collection ids the document already uses for +//! other things: ids are numbered per file, so two files made apart share them. The imported +//! layers keep their own variables, modes and styles, and a file imported again still shares what +//! it brought the first time. + +use base64::Engine as _; +use figcraft_doc::proto::Action; +use figcraft_doc::{Document, Node, NodeId, VariableValue}; +use serde_json::{Value, json}; + +use crate::Session; +use crate::components::tests::ex; +use crate::params::id_of; + +fn idv(v: &Value) -> NodeId { + id_of(&v["id"]).unwrap() +} + +fn var_id(s: &Session, name: &str) -> String { + s.doc().unwrap().variables.get(name).unwrap().id.clone() +} + +fn fill(s: &Session, id: NodeId) -> String { + s.doc().unwrap().node(id).unwrap().fills.first().and_then(|p| p.solid_color()).map(|c| c.to_hex()).unwrap_or_default() +} + +/// The document's file: collection A (Light, Dark) with colours `a1`…`a4`, paint style `Host` +/// and a frame filled with `a1`. +fn host() -> (Session, NodeId) { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "A", "modes": ["Light", "Dark"]})); + for i in 1..=4 { + ex(&mut s, "variable.create", json!({"collection": "A", "name": format!("a{i}"), "type": "color", "value": format!("#A{i}0000")})); + } + ex(&mut s, "style.create", json!({"type": "paint", "name": "Host", "value": "#FF0000"})); + let f = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50, "name": "Host frame"}))); + ex(&mut s, "variable.bind", json!({"ids": [f], "field": "fill", "variable": "a1"})); + (s, f) +} + +/// Another file made apart: collection B (Light, Dark) with `b1` (green in each mode), `b2` (an +/// alias of `b1`) and `size`; paint style `Brand` bound to `b1`. Frame `Card` shows B in Dark, its +/// corners bound to `size`; in it `Swatch` is filled with `b2` and on click sets B to Dark and +/// `size` to `size + 1`, and `Styled` uses `Brand`. +fn other() -> Session { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "B", "modes": ["Light", "Dark"]})); + ex(&mut s, "variable.create", json!({"collection": "B", "name": "b1", "type": "color", "values": {"Light": "#00B000", "Dark": "#004000"}})); + ex(&mut s, "variable.create", json!({"collection": "B", "name": "b2", "type": "color", "value": {"alias": "b1"}})); + ex(&mut s, "variable.create", json!({"collection": "B", "name": "size", "type": "number", "value": 8})); + let brand = ex(&mut s, "style.create", json!({"type": "paint", "name": "Brand", "value": "#00B000"}))["id"].clone(); + ex(&mut s, "style.bind", json!({"style": brand, "field": "fill", "variable": "b1"})); + let card = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 100, "name": "Card"}))); + ex(&mut s, "variable.setMode", json!({"ids": [card], "collection": "B", "mode": "Dark"})); + ex(&mut s, "variable.bind", json!({"ids": [card], "field": "cornerRadius", "variable": "size"})); + let swatch = idv(&ex(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40, "parent": card, "name": "Swatch"}))); + ex(&mut s, "variable.bind", json!({"ids": [swatch], "field": "fill", "variable": "b2"})); + let actions = json!([ + {"type": "setVariableMode", "collection": "B", "mode": "Dark"}, + {"type": "setVariable", "variable": "size", "expression": "size + 1"} + ]); + ex(&mut s, "proto.interaction.add", json!({"id": swatch, "actions": actions})); + let styled = idv(&ex(&mut s, "shape.rectangle", json!({"x": 60, "y": 10, "width": 40, "height": 40, "parent": card, "name": "Styled"}))); + ex(&mut s, "style.apply", json!({"ids": [styled], "style": "Brand"})); + s +} + +fn import(s: &mut Session, file: &Session) -> Value { + let bytes = figcraft_format::save_bytes(file.doc().unwrap(), None).unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(bytes); + ex(s, "file.import", json!({"data": data, "name": "other.figcraft"})) +} + +/// The layers on the pages after the first `kept` pages. +fn layers_after(doc: &Document, kept: usize) -> Vec<&Node> { + doc.pages[kept..].iter().flat_map(|p| doc.subtree(*p).into_iter().skip(1)).filter_map(|id| doc.node(id)).collect() +} + +fn layer<'a>(doc: &'a Document, kept: usize, name: &str) -> &'a Node { + layers_after(doc, kept).into_iter().find(|n| n.name == name).unwrap() +} + +#[test] +fn imported_layers_keep_their_own_variables_and_styles_when_the_ids_are_taken() { + let (mut s, frame) = host(); + let file = other(); + assert_eq!(var_id(&file, "b1"), var_id(&s, "a1"), "the ids must collide for this test"); + assert_eq!(file.doc().unwrap().styles[0].id, s.doc().unwrap().styles[0].id); + let before = s.doc().unwrap().clone(); + import(&mut s, &file); + let doc = s.doc().unwrap(); + assert_eq!(doc.variables.variables.len(), 4 + 3); + assert_eq!(doc.variables.collections.iter().map(|c| c.name.as_str()).collect::>(), ["A", "B"]); + assert_eq!(doc.styles.iter().map(|st| st.name.as_str()).collect::>(), ["Host", "Brand"]); + // The document's own are as they were. + assert_eq!(doc.variables.variables[..4], before.variables.variables[..]); + assert_eq!(doc.variables.collections[0], before.variables.collections[0]); + assert_eq!(doc.styles[0], before.styles[0]); + // Everything imported names B's variables, B and Brand. + let b = doc.variables.collection("B").unwrap().id.clone(); + let imported = layers_after(doc, before.pages.len()); + assert!(imported.iter().any(|n| !n.bound.is_empty())); + for n in imported { + for v in n.bound.values() { + assert_eq!(doc.variables.get_by_id(v).unwrap().collection, b, "{}: {v}", n.name); + } + assert!(n.var_modes.keys().all(|c| *c == b), "{}: {:?}", n.name, n.var_modes); + if let Some(st) = &n.styles.fill { + assert_eq!(doc.styles.iter().find(|x| x.id == *st).unwrap().name, "Brand"); + } + } + let brand = doc.styles.iter().find(|st| st.name == "Brand").unwrap(); + assert_eq!(brand.bound.values().map(|v| doc.variables.get_by_id(v).unwrap().name.as_str()).collect::>(), ["b1"]); + // Bindings applied again leave the imported layers alone. + let swatch = layer(doc, before.pages.len(), "Swatch").id; + let a2 = var_id(&s, "a2"); + ex(&mut s, "variable.set", json!({"variable": a2, "value": "#123456"})); + assert_eq!(fill(&s, swatch), "004000"); + assert_eq!(fill(&s, frame), "A10000"); + assert!(s.doc().unwrap().validate().is_empty()); +} + +#[test] +fn an_alias_a_frame_mode_and_prototype_actions_follow_the_renamed_collection() { + let (mut s, _) = host(); + let file = other(); + let kept = s.doc().unwrap().pages.len(); + import(&mut s, &file); + let doc = s.doc().unwrap(); + let vars = &doc.variables; + let b = vars.collection("B").unwrap(); + let in_b = |name: &str| vars.variables.iter().find(|v| v.name == name && v.collection == b.id).unwrap(); + let (b1, b2, size) = (in_b("b1"), in_b("b2"), in_b("size")); + assert!(b2.values.values().all(|v| *v == VariableValue::Alias(b1.id.clone())), "{:?}", b2.values); + // B's mode ids name B's new id, and its variables' values are by those. + let modes: Vec<&str> = b.modes.iter().map(|m| m.id.as_str()).collect(); + assert_eq!(modes, [format!("{}/mode1", b.id), format!("{}/mode2", b.id)]); + assert!([b1, b2, size].iter().all(|v| v.values.keys().all(|m| modes.contains(&m.as_str())))); + // The frame shows B in Dark: its mode is one of B's. + let card = layer(doc, kept, "Card"); + let dark = b.find_mode("Dark").unwrap().id.clone(); + assert_eq!(card.var_modes.iter().collect::>(), [(&b.id, &dark)]); + assert_eq!(card.bound.get("cornerRadius"), Some(&size.id)); + let swatch = layer(doc, kept, "Swatch"); + assert_eq!(swatch.bound.get("fill"), Some(&b2.id)); + let shown = vars.resolve(&b2.id, &doc.modes_for(swatch.id)); + assert!(matches!(shown, Some(VariableValue::Color(c)) if c.to_hex() == "004000"), "{shown:?}"); + let actions = &swatch.interactions[0].actions; + assert_eq!(actions[0], Action::SetVariableMode { collection: b.id.clone(), mode: dark }); + let Action::SetVariable { variable, expr: Some(e), .. } = &actions[1] else { panic!("{actions:?}") }; + assert_eq!((variable, e.variables()), (&size.id, vec![size.id.as_str()])); +} + +#[test] +fn importing_the_same_file_again_shares_what_it_brought() { + let file = other(); + let mut s = other(); + let before = s.doc().unwrap().clone(); + import(&mut s, &file); + let doc = s.doc().unwrap(); + assert_eq!(doc.variables, before.variables); + assert_eq!(doc.styles, before.styles); + let swatch = layer(doc, before.pages.len(), "Swatch"); + assert_eq!(swatch.bound.get("fill"), Some(&var_id(&s, "b2"))); + // A file imported into an empty one, then again: one copy of its variables. + let mut t = Session::new(); + import(&mut t, &file); + import(&mut t, &file); + let doc = t.doc().unwrap(); + assert_eq!((doc.variables.variables.len(), doc.variables.collections.len(), doc.styles.len()), (3, 1, 1)); + assert!(layers_after(doc, 1).iter().flat_map(|n| n.bound.values()).all(|v| doc.variables.get_by_id(v).is_some())); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e919444e2..0dee66b47 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -367,6 +367,8 @@ mod images_left_in_file_tests; #[cfg(test)] mod import_export_tests; #[cfg(test)] +mod import_ids_tests; +#[cfg(test)] mod import_journal_tests; #[cfg(test)] mod inspect_behaviour_tests; diff --git a/crates/engine/src/library_variables_tests.rs b/crates/engine/src/library_variables_tests.rs index 5a6b329d3..bc82f7a94 100644 --- a/crates/engine/src/library_variables_tests.rs +++ b/crates/engine/src/library_variables_tests.rs @@ -385,6 +385,34 @@ fn library_components_keep_their_variable_bindings() { let _ = std::fs::remove_dir_all(&d); } +#[test] +fn a_file_bringing_older_copies_of_the_same_library_variables_shares_them() { + let d = dir("older-copies"); + let lib_path = path_str(&d.join("kit.figcraft")); + let mut lib = Session::new(); + theme(&mut lib); + let lid = publish_to(&mut lib, &lib_path); + let mut s = Session::new(); + ex(&mut s, "library.add", json!({"path": lib_path})); + let r = idv(&ex(&mut s, "shape.rectangle", json!({"width": 10, "height": 10, "name": "Swatch"}))); + ex(&mut s, "library.bindVariable", json!({"library": lid, "variable": "primary", "field": "fill", "ids": [r]})); + let old_path = path_str(&d.join("old.figcraft")); + ex(&mut s, "file.saveAs", json!({"path": old_path})); + // The copies take an update; the saved file keeps the older ones under the same ids. + ex(&mut lib, "variable.set", json!({"variable": "primary", "mode": "Light", "value": "#444444"})); + republish(&mut lib); + ex(&mut s, "library.acceptUpdates", json!({})); + let before = s.doc().unwrap().clone(); + ex(&mut s, "file.import", json!({"path": old_path})); + let doc = s.doc().unwrap(); + assert_eq!((&doc.variables, &doc.libraries.variables), (&before.variables, &before.libraries.variables), "shared by id, as before"); + let swatches: Vec<&Node> = doc.nodes().filter(|n| n.name == "Swatch").collect(); + assert_eq!(swatches.len(), 2); + assert!(swatches.iter().all(|n| n.bound.get("fill") == Some(©_of(&s, "primary").id))); + healthy(&s); + let _ = std::fs::remove_dir_all(&d); +} + #[test] fn library_variable_commands_fail_cleanly() { let mut s = Session::new(); From 5eb28b310adb6ac9872e69fee0d926198768eea6 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 3 Nov 2026 14:47:46 -0500 Subject: [PATCH 056/102] M12: the bar above the selection stays away while a quick-create handle is dragged (#1919) Review: letting a handle go over the selection bar made the next shape behind it. The bar hides while a "+" is dragged, as it does for any drag (board_connect::dragging), so there is nothing to drop behind; the drop makes the next one where the bar was, and the bar is back once typing in it ends. Test the_bar_stays_away_while_a_handle_is_dragged; the docs rows say the toolbar and the bar. Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/board_connect_tests.rs | 34 ++++++++++++++++++++++ crates/ui-egui/src/canvas/board_bar.rs | 5 ++-- crates/ui-egui/src/canvas/board_connect.rs | 9 +++++- docs/boards-parity.md | 4 +-- 4 files changed, 47 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/board_connect_tests.rs b/crates/ui-egui/src/board_connect_tests.rs index b6466a9ff..fffa1f61c 100644 --- a/crates/ui-egui/src/board_connect_tests.rs +++ b/crates/ui-egui/src/board_connect_tests.rs @@ -34,6 +34,12 @@ fn handle(u: &Ui, side: &str) -> Option { u.ctx.memory(|m| m.areas().visible_last_frame(&layer)).then(|| u.ctx.memory(|m| m.area_rect(layer.id))).flatten() } +/// Where the bar above the selection shows, if it does. +fn bar(u: &Ui) -> Option { + let layer = LayerId::new(Order::Middle, Id::unique("board_bar")); + u.ctx.memory(|m| m.areas().visible_last_frame(&layer)).then(|| u.ctx.memory(|m| m.area_rect(layer.id))).flatten() +} + fn click(u: &mut Ui, p: Pos2) { for pressed in [true, false] { u.frame(vec![Event::PointerMoved(p), Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); @@ -275,3 +281,31 @@ fn a_drag_ends_when_the_selection_moves_to_another_shape() { u.frame(vec![]); assert_eq!(u.app.session.doc().unwrap().ids().count(), before, "the drag was over"); } + +/// The bar above the selection stays away while a handle is dragged, as for any drag (review): +/// letting go where it was makes the next one there, not behind it, and the bar is back after. +#[test] +fn the_bar_stays_away_while_a_handle_is_dragged() { + let (mut u, a) = board_with_shape(); + u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap(); + u.frame(vec![]); + u.frame(vec![]); + let r = bar(&u).expect("the bar shows"); + let from = handle(&u, "above").expect("a handle above").center(); + let to = r.center(); + u.drag_to(from, to); + assert!(bar(&u).is_none(), "no bar while a handle is dragged"); + u.button(to, false); + u.frame(vec![]); + let doc = u.app.session.doc().unwrap(); + let next = doc.ids().find(|i| *i != a && matches!(doc.node(*i).unwrap().board, Some(BoardItem::Shape { .. }))).expect("a new shape"); + let line = doc.ids().find(|i| matches!(doc.node(*i).unwrap().board, Some(BoardItem::Connector(_)))).expect("a connector"); + let centre = screen_box(&u, next).center(); + assert!((centre - to).length() < 1.0, "centred where the bar was: {centre:?}, not {to:?}"); + assert!(matches!(&doc.node(line).unwrap().board, Some(BoardItem::Connector(c)) if c.from.node() == Some(a) && c.to.node() == Some(next))); + // Typing in the new one keeps the bar away, as before; done typing, it is back. + figcraft_engine::textedit::end(&mut u.app.session).unwrap(); + u.frame(vec![]); + u.frame(vec![]); + assert!(bar(&u).is_some(), "the bar is back for the new selection"); +} diff --git a/crates/ui-egui/src/canvas/board_bar.rs b/crates/ui-egui/src/canvas/board_bar.rs index f9a43935c..d85f14901 100644 --- a/crates/ui-egui/src/canvas/board_bar.rs +++ b/crates/ui-egui/src/canvas/board_bar.rs @@ -191,10 +191,11 @@ pub(crate) fn place(sel: Rect, size: egui::Vec2, canvas: Rect) -> Pos2 { pos2(cx - w / 2.0, y) } -/// The bar above a board's selection, while nothing is being dragged and the file can be edited. +/// The bar above a board's selection, while nothing is being dragged (a "+" handle included) and +/// the file can be edited. pub fn show(app: &mut FigApp, ctx: &egui::Context) { let editable = app.session.active_read_only().is_none(); - if app.session.tool.busy() || !editable || !app.session.doc().is_ok_and(figcraft_engine::board::is_board) { + if app.session.tool.busy() || !editable || !app.session.doc().is_ok_and(figcraft_engine::board::is_board) || crate::board_connect::dragging(ctx) { return; } let Some(h) = has(app) else { return }; diff --git a/crates/ui-egui/src/canvas/board_connect.rs b/crates/ui-egui/src/canvas/board_connect.rs index b78946ef3..ea96e922a 100644 --- a/crates/ui-egui/src/canvas/board_connect.rs +++ b/crates/ui-egui/src/canvas/board_connect.rs @@ -3,7 +3,8 @@ //! connector, and starts typing in it (`board.addConnected`). Dragging one carries the preview //! ("drag the preview to any location on your board", #1919): let go on empty board and the next //! one is made there, joined by a connector leaving by the handle's side; let go on another sticky -//! or shape (inside a section too) and a connector joins the two; let go off the canvas, nothing. +//! or shape (inside a section too) and a connector joins the two; let go off the canvas or over the +//! toolbar, nothing. The bar above the selection stays away while a "+" is dragged, as for any drag. use egui::{Area, Color32, CornerRadius, Id, LayerId, Order, Pos2, Rect, Sense, Shape, Stroke, StrokeKind, pos2, vec2}; use figcraft_doc::{BoardItem, NodeId}; @@ -55,6 +56,12 @@ pub(crate) fn shown(app: &FigApp) -> bool { target(app).is_some() } +/// A "+" is being dragged: the bar above the selection stays away meanwhile, as for any drag, so +/// nothing is made behind it. +pub(crate) fn dragging(ctx: &egui::Context) -> bool { + ctx.data(|d| d.get_temp::(drag_id())).is_some() +} + /// The centre of the "+" for `side` of the object's screen box `r`. fn handle_at(r: Rect, side: &str) -> Pos2 { match side { diff --git a/docs/boards-parity.md b/docs/boards-parity.md index 115885f0b..2ea4f6e95 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -38,7 +38,7 @@ all end with the same geometry. | 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 | -| 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. Dragging a "+" carries the preview ("drag the preview to any location on your board"): let go on empty board and the next one is made there, centred on the pointer, joined by a connector leaving by the handle's side (`at: [x, y]`, a point of the page); let go on another sticky or shape, inside a section too, and a connector joins the two instead, the object outlined while over it; let go off the canvas, nothing (`board_connect_tests`, #1919) | +| 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. Dragging a "+" carries the preview ("drag the preview to any location on your board"): let go on empty board and the next one is made there, centred on the pointer, joined by a connector leaving by the handle's side (`at: [x, y]`, a point of the page); let go on another sticky or shape, inside a section too, and a connector joins the two instead, the object outlined while over it; let go off the canvas or over the toolbar, nothing, and the bar above the selection stays away meanwhile (`board_connect_tests`, #1919) | | 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 | | Connector paths reshaped by hand | done | a selected elbow or curved connector shows path handles: one on each run long enough to take one, one in the middle of a curve. 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 and is saved with the file; changing the style or moving an end to something else goes back to routing itself. No way back by itself otherwise: the public help describes none | @@ -70,7 +70,7 @@ all end with the same geometry. | Date | Change | Summary | |---|---|---| -| 2026-11-03 | minor | M12, #1919: as the quick create help says ("Click to select and create the next shape in that direction, or drag the preview to any location on your board"; "A new shape is created with a connector and its text field active"), a "+" beside the selected sticky or shape can be dragged: the preview follows the pointer and, let go on empty board, the next one is made there, centred on the pointer, and joined by a connector leaving by the handle's side and arriving by the side facing it (`board.addConnected` gains `at: [x, y]`, a point of the page placed in the parent's coordinates); let go on another sticky or shape, inside a section or frame too (`board::sticky_or_shape_at`), a connector joins the two instead (`board.connector`), that object outlined while the pointer is over it; let go off the canvas, nothing. The click is as before. A shape picker on drop and choosing the connector type are not done (the help doesn't describe them). Tests: `board_connect_tests` (two), engine `board_connected_tests::the_next_one_goes_where_it_is_dropped`. Numbers unchanged. | +| 2026-11-03 | minor | M12, #1919: as the quick create help says ("Click to select and create the next shape in that direction, or drag the preview to any location on your board"; "A new shape is created with a connector and its text field active"), a "+" beside the selected sticky or shape can be dragged: the preview follows the pointer and, let go on empty board, the next one is made there, centred on the pointer, and joined by a connector leaving by the handle's side and arriving by the side facing it (`board.addConnected` gains `at: [x, y]`, a point of the page placed in the parent's coordinates); let go on another sticky or shape, inside a section or frame too (`board::sticky_or_shape_at`), a connector joins the two instead (`board.connector`), that object outlined while the pointer is over it; let go off the canvas or over the toolbar, nothing, and the bar above the selection stays away meanwhile, as for any drag. The click is as before. A shape picker on drop and choosing the connector type are not done (the help doesn't describe them). Tests: `board_connect_tests` (the drag ones), engine `board_connected_tests::the_next_one_goes_where_it_is_dropped`. 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. | From 4cd7313ca2ccfaa6a71308b03c8f5ad472d7bf6a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 00:20:16 +0000 Subject: [PATCH 057/102] address review: give plugins a fixed message for library failures --- crates/engine/src/doc_list_paths_tests.rs | 17 +++++++++++++++++ crates/engine/src/extensions/plugins.rs | 22 +++++++++++++--------- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/doc_list_paths_tests.rs b/crates/engine/src/doc_list_paths_tests.rs index f69941919..0d73d0736 100644 --- a/crates/engine/src/doc_list_paths_tests.rs +++ b/crates/engine/src/doc_list_paths_tests.rs @@ -63,3 +63,20 @@ fn a_plugin_gets_library_names_but_not_their_links() { assert!(out.contains("Kit"), "{out}"); assert!(!out.contains("per-file-secret") && !out.contains("\\\"path\\\""), "{out}"); } + +#[test] +fn a_plugin_gets_a_fixed_message_for_library_update_failures() { + const LINK: &str = "/home/someone/private/kits/kit.figcraft"; + let mut s = Session::new(); + s.doc_mut().unwrap().libraries_mut().enabled.push(figcraft_doc::LibraryLink { + id: "lib".into(), + name: "Kit".into(), + path: LINK.into(), + version: 3, + }); + let tail = "(call $set_output (i32.const 40000) (call $reply_read (i32.const 40000) (i32.const 20000))) (return (i32.const 0))"; + install(&mut s, manifest("org.test.upd", "read", &[]), &script(&[("library.updates", json!({}))], OnRefusal::Fail, tail)); + let out = ex(&mut s, "plugin.run", json!({"id": "org.test.upd"}))["output"].to_string(); + assert!(out.contains("could not be read"), "{out}"); + assert!(!out.contains("someone") && !out.contains("private"), "{out}"); +} diff --git a/crates/engine/src/extensions/plugins.rs b/crates/engine/src/extensions/plugins.rs index 78044ee71..7677a9b7d 100644 --- a/crates/engine/src/extensions/plugins.rs +++ b/crates/engine/src/extensions/plugins.rs @@ -264,16 +264,20 @@ impl figcraft_plugin::Host for EngineHost<'_> { r.map(|mut v| { // A plugin gets the open files' and libraries' names, not where they are on disk or // the share links (with their tokens) that reach them (#1117). - if matches!(command, "doc.list" | "library.list") { - // `doc.list` is a list; `library.list` keeps its list under `libraries`. - let list = if command == "library.list" { v.get_mut("libraries") } else { Some(&mut v) }; + if matches!(command, "doc.list" | "library.list" | "library.updates") { + // `doc.list` is a list; `library.list` keeps its list under `libraries`, and + // `library.updates` its failures under `errors`. + let list = match command { + "library.list" => v.get_mut("libraries"), + "library.updates" => v.get_mut("errors"), + _ => Some(&mut v), + }; for e in list.and_then(Value::as_array_mut).into_iter().flatten().filter_map(Value::as_object_mut) { - // An error may quote the path too. - if let Some(Value::String(path)) = e.remove("path") - && !path.is_empty() - && let Some(Value::String(err)) = e.get_mut("error") - { - *err = err.replace(&path, "the library"); + e.remove("path"); + // A failure's text may quote the path, a token or another form of it: the + // plugin gets a fixed message. + if let Some(err) = e.get_mut("error").filter(|v| v.is_string()) { + *err = json!("the library could not be read"); } } } From 9aad73169324d1e2ca6dee90cb56efd5966511ca Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 01:29:49 +0000 Subject: [PATCH 058/102] address review: use the request-reply timeout for the reply deadline --- crates/collab-net/src/manage.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/collab-net/src/manage.rs b/crates/collab-net/src/manage.rs index eecbca964..aa73a2ec5 100644 --- a/crates/collab-net/src/manage.rs +++ b/crates/collab-net/src/manage.rs @@ -209,7 +209,9 @@ fn reply(ws: &mut Ws, limits: &NetLimits, pick: impl Fn(ServerMsg) -> Option< // One deadline for the whole answer: pings, pongs and a message trickling in each renew the // read timeout, so without it a server could keep a request (and the refresh permit the // caller holds) waiting for as long as it liked. - let until = std::time::Instant::now() + limits.idle_timeout; + // The request-reply bound, not the session idle one: a publish uploads a whole file and can + // legitimately take minutes to be answered (see `connect`). + let until = std::time::Instant::now() + limits.request_reply_timeout; ws.get_mut().read_until(Some(until)); loop { if std::time::Instant::now() >= until { @@ -259,6 +261,27 @@ mod tests { rx.recv_timeout(Duration::from_secs(3)).is_ok() } + /// A server that keeps pinging and never answers ends the wait at the request-reply bound. + #[test] + fn reply_gives_up_at_the_request_reply_deadline_against_a_pinging_server() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + std::thread::spawn(move || { + let (s, _) = listener.accept().unwrap(); + if let Ok(mut ws) = tungstenite::accept(s) { + while ws.send(Message::Ping(Bytes::new())).is_ok() { + std::thread::sleep(Duration::from_millis(10)); + } + } + }); + let limits = NetLimits { request_reply_timeout: Duration::from_millis(400), ..NetLimits::default() }; + let server = Endpoint { host: addr.to_string(), path: "/".into(), secure: false }; + let mut ws = connect(&server, &limits, Duration::from_secs(2)).unwrap(); + let started = std::time::Instant::now(); + assert!(reply::<()>(&mut ws, &limits, |_| None).is_err()); + assert!(started.elapsed() < Duration::from_secs(3), "{:?}", started.elapsed()); + } + /// A server that keeps pinging and never answers the close must not pin `close` forever. #[test] fn close_returns_against_a_server_that_keeps_pinging() { From e9ec7564c247fb123f0a51537d40e2e2aafc8d03 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 04:07:45 +0000 Subject: [PATCH 059/102] fix(server): a refused batch counts toward a log's size, not toward a snapshot rewrite --- apps/figcraft-server/src/store/backend.rs | 4 +++- apps/figcraft-server/src/store_tests.rs | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/apps/figcraft-server/src/store/backend.rs b/apps/figcraft-server/src/store/backend.rs index ee4091a8b..5d4a3bfe9 100644 --- a/apps/figcraft-server/src/store/backend.rs +++ b/apps/figcraft-server/src/store/backend.rs @@ -68,7 +68,9 @@ impl Backend for Store { Err(err) => log::error!("file {file}: a change couldn't be logged: {err}"), } } - log.entries += journal.len(); + // A refusal changes nothing in the document: it counts toward the log's size (bytes), but + // not toward the entries that make a snapshot rewrite worthwhile. + log.entries += journal.iter().filter(|j| !matches!(j, figcraft_collab::Journal::Refused { .. })).count(); log.dirty = true; e.meta.updated = now(); if log.entries >= after || log.bytes + log.pending.len() as u64 >= max_bytes { diff --git a/apps/figcraft-server/src/store_tests.rs b/apps/figcraft-server/src/store_tests.rs index f94e76f02..f2074d879 100644 --- a/apps/figcraft-server/src/store_tests.rs +++ b/apps/figcraft-server/src/store_tests.rs @@ -155,6 +155,24 @@ fn read_only_sessions_keep_client_ids_without_rewriting_the_snapshot() { } } +#[test] +fn a_viewers_refused_batches_do_not_rewrite_the_snapshot() { + let dir = TempDir::new("refusals"); + let c = StoreConfig { compact_after: 3, ..cfg(dir.path()) }; + let mut store = Store::open(dir.path(), c).unwrap(); + let (id, _, _) = publish(&mut store, "Busy"); + let mut server = store.open(&id).unwrap(); + let mut v = join(&mut server, Access::View); + store.changed(&id, &mut server); + let generation = || disk::check_snapshot(&fs::read(dir.path().join(FILES).join(&id).join(SNAPSHOT)).unwrap()).unwrap(); + assert_eq!(generation(), 1); + for i in 0..10 { + rename(&mut server, &mut v, &format!("P{i}")); + store.changed(&id, &mut server); + } + assert_eq!(generation(), 1, "refusals are logged, not compacted"); +} + #[test] fn a_long_log_is_compacted_while_open() { let dir = TempDir::new("compact"); From 44bec70a47bb8727e5a4c4a4a7acbfa4bf4384ff Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 04:25:42 +0000 Subject: [PATCH 060/102] fix(pathops): cap an arrowhead's weight like a stroke's width --- crates/pathops/src/lib.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index e69cb9bb1..e478c850e 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -459,6 +459,8 @@ fn path_end(path: &BezPath, at_end: bool) -> Option<(Point, Vec2)> { /// The filled arrowhead shape for `cap` at one end of an open path. pub fn arrowhead(path: &BezPath, cap: StrokeCap, weight: f64, at_end: bool) -> Option { + // Capped like a stroke's width: the circle below is flattened at a fixed tolerance. + let weight = weight.min(MAX_STROKE_WIDTH); let (tip, dir) = path_end(path, at_end)?; let n = Vec2::new(-dir.y, dir.x); let s = (weight * 3.0).max(6.0); @@ -760,6 +762,15 @@ mod tests { assert!((b.x0 + 5.0).abs() < 0.01); } + #[test] + fn an_absurd_arrow_weight_is_capped() { + let mut line = BezPath::new(); + line.move_to((0.0, 0.0)); + line.line_to((100.0, 0.0)); + let head = arrowhead(&line, StrokeCap::CircleFilled, 1e300, true).unwrap(); + assert!(head.elements().len() < 10_000, "{}", head.elements().len()); + } + #[test] fn arrows_on_open_paths() { let mut line = BezPath::new(); From ad9894a90fabf079a23aea1afdd7c0dcc8f092b7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 04:31:52 +0000 Subject: [PATCH 061/102] fix(doc): give render bounds a visit budget so a repeating child list ends --- crates/doc/src/lib.rs | 18 +++++++++++------- crates/doc/src/tests.rs | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 0181ffd21..f3ee25c53 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -760,16 +760,20 @@ impl Document { /// children only within their mask). A group, or an unclipped frame past its box, is what its /// children show grown by its effects, which apply to all of it. pub fn world_render_bounds(&self, id: NodeId) -> Option { - self.render_bounds_at(id, 0) + // A tree visits each node once; a child list deserialized with repeats (a graph) is cut off + // after twice the document's node count rather than walked in full. + self.render_bounds_at(id, 0, &std::cell::Cell::new(self.nodes.len().saturating_mul(2).saturating_add(8))) } - fn render_bounds_at(&self, id: NodeId, depth: usize) -> Option { + fn render_bounds_at(&self, id: NodeId, depth: usize, left: &std::cell::Cell) -> Option { let n = self.node(id)?; let own = n.own_paint_bounds(self.world_transform(id)); - if (n.clip && n.kind.is_frame_like() && !n.kind.bounds_follow_children()) || depth >= MAX_RENDER_DEPTH { + let visit = left.get(); + left.set(visit.saturating_sub(1)); + if (n.clip && n.kind.is_frame_like() && !n.kind.bounds_follow_children()) || depth >= MAX_RENDER_DEPTH || visit == 0 { return Some(own); } - Some(match (self.children_render_bounds(n, depth + 1), &n.kind) { + Some(match (self.children_render_bounds(n, depth + 1, left), &n.kind) { (Some(kids), NodeKind::Group) => n.grow_by_effects(kids), // An unclipped frame's effects apply to its children too, past its box included. (Some(kids), _) => own.union(n.grow_by_effects(kids)), @@ -778,15 +782,15 @@ impl Document { } /// What `n`'s visible children show, together: each mask's run within the mask's bounds. - fn children_render_bounds(&self, n: &Node, depth: usize) -> Option { + fn children_render_bounds(&self, n: &Node, depth: usize, left: &std::cell::Cell) -> Option { let shown = |i: &NodeId| self.node(*i).is_some_and(|c| c.visible && !c.is_mask); let mut out: Option = None; for run in self.paint_runs(n) { let ids = n.children.get(run).unwrap_or(&[]); let mask = ids.first().copied().filter(|m| self.node(*m).is_some_and(|c| c.is_mask && c.visible)); - let r = ids.iter().filter(|i| shown(i)).filter_map(|i| self.render_bounds_at(*i, depth)).reduce(|a, b| a.union(b)); + let r = ids.iter().filter(|i| shown(i)).filter_map(|i| self.render_bounds_at(*i, depth, left)).reduce(|a, b| a.union(b)); let r = match mask { - Some(m) => r.zip(self.render_bounds_at(m, depth)).map(|(a, b)| a.intersect(b)).filter(|x| x.width() > 0.0 && x.height() > 0.0), + Some(m) => r.zip(self.render_bounds_at(m, depth, left)).map(|(a, b)| a.intersect(b)).filter(|x| x.width() > 0.0 && x.height() > 0.0), None => r, }; out = match (out, r) { diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index a5c8e8e7a..75de3541e 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -582,6 +582,22 @@ fn is_ancestor_holds_for_very_deep_chains() { assert!(matches!(d.reparent(root, leaf, None), Err(DocError::Cycle(..)))); } +#[test] +fn render_bounds_of_a_doubled_child_list_end_at_once() { + // A file can list a child twice at every level: 2^40 visits if each is walked. + let mut d = Document::new("x"); + let mut parent = page(&d); + let mut groups = Vec::new(); + for _ in 0..40 { + parent = d.create(parent, NodeKind::Group, "G", 0.0, 0.0, 10.0, 10.0).unwrap(); + groups.push(parent); + } + for w in groups.windows(2) { + d.node_mut(w[0]).unwrap().children.push(w[1]); + } + assert!(d.world_render_bounds(groups[0]).is_some()); +} + #[test] fn render_bounds_stop_where_drawing_stops_on_very_deep_chains() { // A crafted file nests groups far deeper than anything draws (#1062). The leaf counts while From ddb8bfa6652e6644f9cd1ef56687866fdef1b13a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 04:44:24 +0000 Subject: [PATCH 062/102] fix(format): cap the bytes copied to fill a variable's missing modes --- crates/format/src/rest/variables.rs | 44 +++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/crates/format/src/rest/variables.rs b/crates/format/src/rest/variables.rs index 94ca03f6b..ba2467423 100644 --- a/crates/format/src/rest/variables.rs +++ b/crates/format/src/rest/variables.rs @@ -20,6 +20,9 @@ const MAX_VARIABLES: usize = 100_000; const MAX_MODES: usize = 1_000; /// Longest string variable value kept (characters). const MAX_STRING: usize = 10_000; +/// The copies of fallback values that fill missing modes, in bytes, for one import: variables, modes +/// and string length are each capped, but not their product. Past it, modes stay empty. +const MAX_FILLED_BYTES: usize = 64 << 20; /// The object holding `variableCollections` and `variables`: a local variables response's `meta`, /// or `v` itself. @@ -287,14 +290,10 @@ impl Ctx<'_> { if dropped { self.warn("variable aliases to variables that aren't in the variables JSON (or of another type) were skipped"); } + let mut budget = MAX_FILLED_BYTES; for v in found.iter_mut() { let Some(modes) = self.var_modes.get(&v.collection) else { continue }; - let fallback = modes.first().and_then(|m| v.values.get(m)).or_else(|| v.values.values().next()).cloned(); - if let Some(f) = fallback { - for m in modes { - v.values.entry(m.clone()).or_insert_with(|| f.clone()); - } - } + fill_modes(&mut v.values, modes, &mut budget); } } @@ -521,3 +520,36 @@ fn field_type(field: &str) -> VariableType { _ => VariableType::Number, } } + +/// Give each of `modes` without a value a copy of the first mode's (else any) value, while the +/// copies' bytes fit in `budget`. +fn fill_modes(values: &mut BTreeMap, modes: &[String], budget: &mut usize) { + let Some(f) = modes.first().and_then(|m| values.get(m)).or_else(|| values.values().next()).cloned() else { return }; + let cost = + 64 + modes.iter().map(String::len).max().unwrap_or(0) + if let VariableValue::String(t) | VariableValue::Alias(t) = &f { t.len() } else { 0 }; + for m in modes { + if values.contains_key(m) { + continue; + } + let Some(left) = budget.checked_sub(cost) else { return }; + *budget = left; + values.insert(m.clone(), f.clone()); + } +} + +#[cfg(test)] +mod fill_tests { + use super::*; + + #[test] + fn missing_modes_are_filled_only_within_the_budget() { + let modes: Vec = (0..10).map(|i| format!("m{i}")).collect(); + let mut v = BTreeMap::from([("m0".to_string(), VariableValue::String("x".repeat(100)))]); + let mut budget = 1_000; + fill_modes(&mut v, &modes, &mut budget); + assert!(v.len() > 1 && v.len() < 10, "{}", v.len()); + let mut v = BTreeMap::from([("m0".to_string(), VariableValue::Number(1.0))]); + fill_modes(&mut v, &modes, &mut { MAX_FILLED_BYTES }); + assert_eq!(v.len(), 10); + } +} From 453e0b9af88196d90efcc38ee48d15948d9f51d6 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 3 Nov 2026 23:48:36 -0500 Subject: [PATCH 063/102] M8: a whole-turn hue is 0, a negative hue counts back, and calc() is refused (tests) Review asks on #1773: `css_hue_wraps_a_whole_turn_and_calc_is_not_a_number` checks that 360, 1turn, 400grad, 2 pi rad and -1turn all read as hue 0, that -90deg, -0.25turn, -100grad and 630 all read as 270, the same in oklch() and lch(), and that `calc(NaN)`, `calc(infinity)`, `calc(1)` and `calc(1turn)` are refused as non-numbers rather than read as 0 or clamped. Co-Authored-By: Claude Fable 5.1 --- crates/color/src/tests.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/color/src/tests.rs b/crates/color/src/tests.rs index 41e7acaf7..d4bb69676 100644 --- a/crates/color/src/tests.rs +++ b/crates/color/src/tests.rs @@ -271,3 +271,26 @@ fn to_css_sanitizes_an_unclamped_alpha() { } assert_eq!(Color { r: 1.0, g: 0.0, b: 0.0, a: f32::INFINITY }.to_css(), "#FF0000"); } + +#[test] +fn css_hue_wraps_a_whole_turn_and_calc_is_not_a_number() { + // A hue is an angle (CSS Color 4 §4.3): a whole turn (360, 1turn, 400grad, 2 pi rad) is 0 and a + // negative hue counts back from it, in hsl() and in the polar spaces alike. `calc()` is not + // read, so `calc(NaN)` and `calc(infinity)` are refused like any other non-number rather than + // read as 0 or clamped. + let red = Color::parse_css("hsl(0 100% 50%)").unwrap().to_rgba8(); + for s in ["hsl(360 100% 50%)", "hsl(1turn 100% 50%)", "hsl(400grad 100% 50%)", "hsl(6.2831855rad 100% 50%)", "hsl(-1turn 100% 50%)"] { + assert_eq!(Color::parse_css(s).map(|c| c.to_rgba8()), Some(red), "{s}"); + } + let violet = Color::parse_css("hsl(270 100% 50%)").unwrap().to_rgba8(); + for s in ["hsl(-90deg 100% 50%)", "hsl(-0.25turn 100% 50%)", "hsl(-100grad 100% 50%)", "hsl(630 100% 50%)"] { + assert_eq!(Color::parse_css(s).map(|c| c.to_rgba8()), Some(violet), "{s}"); + } + assert_eq!(Color::parse_css("oklch(0.5 0.1 1turn)").map(|c| c.to_rgba8()), Color::parse_css("oklch(0.5 0.1 0)").map(|c| c.to_rgba8())); + assert_eq!(Color::parse_css("lch(50 50 400grad)").map(|c| c.to_rgba8()), Color::parse_css("lch(50 50 0)").map(|c| c.to_rgba8())); + assert_eq!(Color::parse_css("oklch(0.5 0.1 -90deg)").map(|c| c.to_rgba8()), Color::parse_css("oklch(0.5 0.1 270)").map(|c| c.to_rgba8())); + for s in ["hsl(calc(NaN) 100% 50%)", "rgb(calc(infinity) 0 0)", "rgb(0 0 0 / calc(1))", "oklch(0.5 0.1 calc(20deg))", "hsl(calc(1turn) 100% 50%)"] + { + assert_eq!(Color::parse_css(s), None, "{s}"); + } +} From deee3d8acf47e971b023ebbff8a8abc73ccac821 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 04:50:11 +0000 Subject: [PATCH 064/102] fix(format): bound the characters Sketch text runs write in all --- crates/format/src/sketch/text.rs | 9 +++++++++ crates/format/src/sketch/text_tests.rs | 10 ++++++++++ 2 files changed, 19 insertions(+) diff --git a/crates/format/src/sketch/text.rs b/crates/format/src/sketch/text.rs index 74cfa21c9..4a7fe18ad 100644 --- a/crates/format/src/sketch/text.rs +++ b/crates/format/src/sketch/text.rs @@ -14,6 +14,9 @@ use super::tree::{Cx, color}; const MAX_CHARS: usize = 1 << 20; /// Most runs read from one text layer. const MAX_RUNS: usize = 10_000; +/// Most characters that styled runs may write in all, overlaps counted again (a run's range is +/// rewritten in full, even where later runs overwrite it). +const MAX_RUN_WORK: usize = 16 * MAX_CHARS; /// Fill `node` (a TEXT node) from text layer `l`. pub(crate) fn node(cx: &mut Cx, l: &Value, node: &mut JsonMap) { @@ -80,10 +83,16 @@ pub(crate) fn node(cx: &mut Cx, l: &Value, node: &mut JsonMap) { // Runs that differ from the first: a style id per UTF-16 unit. let mut ids = vec![0u64; units]; let mut table = JsonMap::new(); + let mut work = 0usize; for (start, end, s) in &styles { if *s == base { continue; } + work = work.saturating_add(end.saturating_sub(*start)); + if work > MAX_RUN_WORK { + cx.warn("text whose styled runs overlap a great deal keeps the first runs' styles"); + break; + } let id = table.len() as u64 + 1; table.insert(id.to_string(), s.clone()); for slot in ids.get_mut(*start..*end).into_iter().flatten() { diff --git a/crates/format/src/sketch/text_tests.rs b/crates/format/src/sketch/text_tests.rs index 0e8a4a279..f50bf74df 100644 --- a/crates/format/src/sketch/text_tests.rs +++ b/crates/format/src/sketch/text_tests.rs @@ -271,3 +271,13 @@ fn later_runs_dont_inherit_the_first_runs_settings() { assert_eq!(second.line_height, figcraft_doc::LineHeight::Auto, "{second:?}"); assert!(second.variations.is_empty(), "{second:?}"); } + +#[test] +fn runs_that_overlap_a_great_deal_stop_being_applied() { + // 17 runs over the whole of a text of 2^20 characters: 17 × 2^20 writes without the limit. + let n = 1 << 20; + let mut runs = vec![(0, 1, "Helvetica", 10.0, BLACK)]; + runs.extend((0..17).map(|i| (0, n, "Helvetica", 11.0 + f64::from(i), BLACK))); + let (_, warnings) = open(vec![text("Long", 0.0, 0.0, 200.0, 20.0, &"a".repeat(n), &runs)]); + assert!(warnings.iter().any(|w| w.contains("overlap a great deal")), "{warnings:?}"); +} From bda7ca910d287663322f7bf932094636ae4f7712 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 4 Nov 2026 01:52:02 -0500 Subject: [PATCH 065/102] M6: a FigJam elbow connector saved with its path keeps it on import (#1910) The `.jam` importer routed every elbowed connector itself, so one drawn around a layer by hand in FigJam came in routed through it. FigJam saves the path as `connectorControlPoints`: one per run between the first and the last, each a point on its run (in the connector's parent's coordinates) with the run's axis; the first run leaves the start's side and the last arrives at the end's. They become the `ConnectorPath::Runs` a board connector reshaped by hand has, walked by `figcraft_doc::route_along`, so the path is kept exactly. Points that don't make such a path (off both axes, two runs the same way in a row, a first or last run sideways to its side, more runs than a hand could make) leave the connector to the router as before, and only connectors routed here count in the "own routing" note. `figcraft_doc::attach_points` and `MAX_RUNS` are exported for it. Docs: file-format-parity.md, boards-parity.md. Co-Authored-By: Claude Fable 5.1 --- crates/doc/src/board_route.rs | 11 +++- crates/doc/src/lib.rs | 2 +- crates/format/src/fig/map/connector.rs | 50 +++++++++++++++-- crates/format/src/fig/tail_tests.rs | 77 ++++++++++++++++++++++++++ crates/format/src/fig/tests.rs | 3 +- docs/boards-parity.md | 2 +- docs/file-format-parity.md | 7 ++- 7 files changed, 140 insertions(+), 12 deletions(-) diff --git a/crates/doc/src/board_route.rs b/crates/doc/src/board_route.rs index 1aa45c810..38efbef9b 100644 --- a/crates/doc/src/board_route.rs +++ b/crates/doc/src/board_route.rs @@ -66,6 +66,12 @@ pub fn attached_sides(from: RouteEnd, to: RouteEnd) -> (Option, Option (Point, Point) { + (attach(from, to.centre()).0, attach(to, from.centre()).0) +} + /// The route's path handles: one for each run of an elbow and one for a curve, with the portion /// of the path each moves and where it sits. pub fn path_handles(pts: &[Point], routing: Routing) -> Vec<(usize, Point)> { @@ -90,8 +96,9 @@ pub fn reshaped(from: RouteEnd, to: RouteEnd, routing: Routing, path: Option<&Co } } -/// A path of more runs than this can't be made by hand: [`reshaped`] refuses another. -const MAX_RUNS: usize = 64; +/// A path of more runs than this can't be made by hand: [`reshaped`] refuses another, and an +/// importer leaves a saved one to the router. +pub const MAX_RUNS: usize = 64; /// The runs of the right-angled route `pts` with run `portion` moved to `p`. fn reshaped_runs(pts: &[Point], portion: usize, p: Point) -> Option { diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 1349aac1d..b60a65ada 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -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::{MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points}; pub use colors::*; pub use comments::*; pub use facilitation::*; diff --git a/crates/format/src/fig/map/connector.rs b/crates/format/src/fig/map/connector.rs index de2ff501c..01c07c00e 100644 --- a/crates/format/src/fig/map/connector.rs +++ b/crates/format/src/fig/map/connector.rs @@ -2,7 +2,7 @@ use super::layer::{cap_name, own_text, svg_path, valid_size}; use super::paint::{paint, stroke}; use super::{Affine, Kv, Mapper, NO_STYLE, Obj, Point, Value, View, generated_record, guid, json, matrix, network, num, rows}; use figcraft_doc::geom::kurbo::{BezPath, PathEl, Rect, Shape}; -use figcraft_doc::{RouteEnd, Routing, Side, route_points}; +use figcraft_doc::{ConnectorPath, MAX_RUNS, RouteEnd, Routing, Side, attach_points, attached_sides, route_along}; /// How a connector imports: from its saved snapshot (`terminal`: as one vector, no room for its /// label), or drawn from its ends, as a frame with its line and `label` when it has one. @@ -48,7 +48,8 @@ impl<'a> Mapper<'a> { /// A connector's end caps, and when it has no saved outline or network its line between its /// ends (free points, or a sibling layer): straight to the point given on the layer (its - /// centre unless given), or elbowed or curved from a side of it, as a board connector runs. + /// centre unless given), or elbowed or curved from a side of it, as a board connector runs; + /// an elbow saved with its path (FigJam's control points) runs along it (#1910). /// Returns the middle of that line by length, in the connector's own coordinates. pub(super) fn connector(&mut self, o: &mut Obj, v: &View<'a>, space: Affine) -> Option { for (from, to) in [("connectorStartCap", "strokeCapStart"), ("connectorEndCap", "strokeCapEnd")] { @@ -94,11 +95,13 @@ impl<'a> Mapper<'a> { }; ok.then_some(end) }; - let Some(pts) = end("connectorStart").zip(end("connectorEnd")).and_then(|(a, b)| route_points(a, b, routing)) else { + let ends = end("connectorStart").zip(end("connectorEnd")); + let path = ends.filter(|_| routing == Routing::Elbow).and_then(|(a, b)| saved_runs(v, a, b)); + let Some(pts) = ends.and_then(|(a, b)| route_along(a, b, routing, path.as_ref())) else { self.warn("connectors whose ends can't be placed are empty"); return None; }; - if routing != Routing::Straight { + if routing != Routing::Straight && path.is_none() { self.warn("elbowed and curved connectors without a saved path follow FigCraft's own routing"); } // A curved route is one curve: its ends and the two control points between them. @@ -407,6 +410,45 @@ pub(super) fn connector_has_saved_label(v: &View<'_>) -> bool { .is_some_and(|s| !s.trim().is_empty()) } +/// The path a FigJam elbow connector was saved with: its `connectorControlPoints`, one per run +/// between the first and the last, each a point on its run (in the connector's parent's +/// coordinates, like its ends) with the run's axis; the first run leaves the start's side and the +/// last arrives at the end's, so neither is saved. `None` without any, or when they don't make +/// such a path: a point off both axes, two runs in a row the same way, a first or last run that +/// would leave or arrive sideways to its side, or more runs than a hand could make here. +fn saved_runs(v: &View<'_>, from: RouteEnd, to: RouteEnd) -> Option { + let saved = v.list("connectorControlPoints"); + if saved.is_empty() || saved.len() + 2 > MAX_RUNS { + return None; + } + let (p0, p1) = attach_points(from, to); + let mid = p0.midpoint(p1); + let mut at = Vec::with_capacity(saved.len()); + let (mut first, mut last) = (None, None); + for p in saved { + let pos = p.get("position").and_then(|q| Some(Point::new(num(q, "x")?, num(q, "y")?)))?; + let (ax, ay) = p.get("axis").and_then(|q| Some((num(q, "x")?, num(q, "y")?)))?; + let sideways = match (ax != 0.0, ay != 0.0) { + (true, false) => true, + (false, true) => false, + _ => return None, + }; + if last == Some(sideways) { + return None; + } + first.get_or_insert(!sideways); + last = Some(sideways); + at.push(if sideways { pos.y - mid.y } else { pos.x - mid.x }); + } + // The run through each end goes the way its side faces: the first at right angles to the first + // saved run, the last to the last. + let (across, last) = (first?, last?); + let faces_across = |s: Side| matches!(s, Side::Left | Side::Right); + let (s0, s1) = attached_sides(from, to); + let fits = s0.is_none_or(|s| faces_across(s) == across) && s1.is_none_or(|s| faces_across(s) != last); + fits.then_some(ConnectorPath::Runs { across, at }) +} + /// The side of its layer a connector end leaves from: the `magnet` the file names, else the edge /// its point on the layer (`relativePosition`, 0–1) lies on, else the side facing the other end. fn side(e: &Kv<'_>, at: Option<(f64, f64)>) -> Side { diff --git a/crates/format/src/fig/tail_tests.rs b/crates/format/src/fig/tail_tests.rs index 2c8cce032..09e6ed85a 100644 --- a/crates/format/src/fig/tail_tests.rs +++ b/crates/format/src/fig/tail_tests.rs @@ -863,3 +863,80 @@ fn write_fixture() { std::fs::write(out, zip_file(&tail_canvas())).unwrap(); } } + +/// An elbow connector saved with its path (#1910): FigJam's control points, one per run between +/// the first and the last, each on its run with the run's axis, give the path the connector keeps; +/// the first run leaves the start's side and the last arrives at the end's. +#[test] +fn an_elbow_connector_saved_with_its_path_keeps_it() { + let mut message = tail_message(); + let Kv::Array(nodes) = field_mut(&mut message, "nodeChanges").unwrap() else { panic!() }; + let box_at = |id, name: &str, x, y| node(id, Some((1, "*")), "RECTANGLE", name, vec![("size", xy(100.0, 100.0)), ("transform", at(x, y))]); + let point = |x, y, ax, ay| o(vec![("position", xy(x, y)), ("axis", xy(ax, ay))]); + // From A's bottom, across at y 740, down at x 200, into B's left: four runs. + let saved = node( + 66, + Some((1, "+")), + "CONNECTOR", + "Saved", + vec![ + ("strokePaints", arr(vec![solid(0.0, 0.0, 0.0)])), + ("connectorStart", o(vec![("endpointNodeID", g(64)), ("relativePosition", xy(0.5, 1.0))])), + ("connectorEnd", o(vec![("endpointNodeID", g(65)), ("relativePosition", xy(0.0, 0.5))])), + ("connectorLineStyle", e("ELBOWED")), + ("connectorControlPoints", arr(vec![point(150.0, 740.0, 1.0, 0.0), point(200.0, 800.0, 0.0, 1.0)])), + ], + ); + nodes.extend([box_at(64, "A", 0.0, 600.0), box_at(65, "B", 300.0, 800.0), saved]); + let (doc, warnings) = import(&canvas(&schema(), &message), "Saved path").unwrap(); + let world = doc.world_transform(named(&doc, "Saved").id); + let line: Vec<_> = + network_of(&doc, "Saved").vertices.iter().map(|v| world * figcraft_doc::geom::Point::new(v.x, v.y)).map(|p| (p.x, p.y)).collect(); + assert_eq!(line, [(50.0, 700.0), (50.0, 740.0), (200.0, 740.0), (200.0, 850.0), (300.0, 850.0)]); + // The fixture's own Link, saved without a path, is routed here: the note counts it alone. + let routed: Vec<_> = warnings.iter().filter(|w| w.contains("FigCraft's own routing")).collect(); + assert_eq!(routed.len(), 1, "{warnings:?}"); + assert!(!routed[0].contains('×'), "a connector with its path isn't counted among those routed here: {routed:?}"); +} + +/// Saved control points that don't make a path from the connector's sides (#1910): a first run +/// that would leave the bottom sideways, a point off both axes, or two runs in a row the same way +/// leave the connector to FigCraft's routing, as one saved without a path is. +#[test] +fn an_elbow_whose_saved_path_doesnt_fit_its_sides_is_routed_here() { + let mut message = tail_message(); + let Kv::Array(nodes) = field_mut(&mut message, "nodeChanges").unwrap() else { panic!() }; + let box_at = |id, name: &str, x, y| node(id, Some((1, "*")), "RECTANGLE", name, vec![("size", xy(100.0, 100.0)), ("transform", at(x, y))]); + let point = |x, y, ax, ay| o(vec![("position", xy(x, y)), ("axis", xy(ax, ay))]); + let elbow = |id, name: &str, points: Vec>| { + let mut fields = vec![ + ("strokePaints", arr(vec![solid(0.0, 0.0, 0.0)])), + ("connectorStart", o(vec![("endpointNodeID", g(64)), ("relativePosition", xy(0.5, 1.0))])), + ("connectorEnd", o(vec![("endpointNodeID", g(65)), ("relativePosition", xy(0.0, 0.5))])), + ("connectorLineStyle", e("ELBOWED")), + ]; + if !points.is_empty() { + fields.push(("connectorControlPoints", arr(points))); + } + node(id, Some((1, "+")), "CONNECTOR", name, fields) + }; + nodes.extend([ + box_at(64, "A", 0.0, 600.0), + box_at(65, "B", 300.0, 800.0), + elbow(66, "Plain", vec![]), + elbow(67, "Sideways", vec![point(100.0, 650.0, 0.0, 1.0)]), + elbow(68, "Askew", vec![point(150.0, 740.0, 1.0, 1.0)]), + elbow(69, "Repeated", vec![point(150.0, 740.0, 1.0, 0.0), point(150.0, 760.0, 1.0, 0.0)]), + ]); + let (doc, warnings) = import(&canvas(&schema(), &message), "Unfit paths").unwrap(); + let line = |name: &str| -> Vec<(f64, f64)> { + let world = doc.world_transform(named(&doc, name).id); + network_of(&doc, name).vertices.iter().map(|v| world * figcraft_doc::geom::Point::new(v.x, v.y)).map(|p| (p.x, p.y)).collect() + }; + let plain = line("Plain"); + assert!(plain.len() >= 3, "routed in right angles: {plain:?}"); + for name in ["Sideways", "Askew", "Repeated"] { + assert_eq!(line(name), plain, "{name} is routed as one without a path"); + } + assert!(warnings.iter().any(|w| w.contains("FigCraft's own routing")), "{warnings:?}"); +} diff --git a/crates/format/src/fig/tests.rs b/crates/format/src/fig/tests.rs index 2d4a1f7d6..317d0c6f5 100644 --- a/crates/format/src/fig/tests.rs +++ b/crates/format/src/fig/tests.rs @@ -51,6 +51,7 @@ message VariableSetID GUID guid, AssetRef assetRef message ConditionalActions Action[] actions, VariableData condition message VectorData uint vectorNetworkBlob, Vector normalizedSize, NodeChange[] styleOverrideTable message ConnectorEndpoint GUID endpointNodeID, Vector position, Vector relativePosition +message ConnectorControlPoint Vector position, Vector axis message VariableData AnyValue value, DataType dataType message Paint PaintType type, Color color, float opacity, bool visible, Image image, Matrix transform, ColorStop[] stops, VariableData colorVar, ImageScaleMode imageScaleMode message ParentIndex GUID guid, string position @@ -74,7 +75,7 @@ message Event InteractionType interactionType message Action GUID transitionNodeID, TransitionType transitionType, float transitionDuration, EasingType easingType, ConnectionType connectionType, NavigationType navigationType, VariableTarget targetVariable, VariableData targetVariableData, VariableSetID targetVariableSetID, GUID targetVariableModeID, ConditionalActions[] conditionalActions message Interaction Event event, Action[] actions message StartingPoint string name, string position -message NodeChange GUID guid, ParentIndex parentIndex, NodeType type, string name, bool visible, float opacity, Vector size, Matrix transform, Paint[] fillPaints, Paint[] strokePaints, float strokeWeight, float cornerRadius, bool resizeToFit, bool internalOnly, float fontSize, FontName fontName, TextData textData, uint styleID, Path[] fillGeometry, Path[] strokeGeometry, StyleType styleType, StyleId styleIdForFill, SymbolData symbolData, PropDef[] componentPropDefs, PropAssignment[] componentPropAssignments, VariableDataMap parameterConsumptionMap, SetMode[] variableSetModes, VariableID variableSetID, ResolvedType variableResolvedType, Values variableDataValues, ModeMap variableModeBySetMap, Interaction[] prototypeInteractions, StartingPoint prototypeStartingPoint, GUIDPath guidPath, StackMode stackMode, float stackSpacing, float stackHorizontalPadding, float stackVerticalPadding, uint count, float starInnerScale, VectorData vectorData, StrokeCap strokeCap, StrokeJoin strokeJoin, VectorMirror handleMirroring, ShapeWithTextType shapeWithTextType, ConnectorEndpoint connectorStart, ConnectorEndpoint connectorEnd, StrokeCap connectorStartCap, StrokeCap connectorEndCap, ConnectorLineStyle connectorLineStyle, ConstraintType horizontalConstraint, ConstraintType verticalConstraint, NodeChange[] derivedSymbolData, string key, string version, LeadingTrim leadingTrim, float[] dashPattern +message NodeChange GUID guid, ParentIndex parentIndex, NodeType type, string name, bool visible, float opacity, Vector size, Matrix transform, Paint[] fillPaints, Paint[] strokePaints, float strokeWeight, float cornerRadius, bool resizeToFit, bool internalOnly, float fontSize, FontName fontName, TextData textData, uint styleID, Path[] fillGeometry, Path[] strokeGeometry, StyleType styleType, StyleId styleIdForFill, SymbolData symbolData, PropDef[] componentPropDefs, PropAssignment[] componentPropAssignments, VariableDataMap parameterConsumptionMap, SetMode[] variableSetModes, VariableID variableSetID, ResolvedType variableResolvedType, Values variableDataValues, ModeMap variableModeBySetMap, Interaction[] prototypeInteractions, StartingPoint prototypeStartingPoint, GUIDPath guidPath, StackMode stackMode, float stackSpacing, float stackHorizontalPadding, float stackVerticalPadding, uint count, float starInnerScale, VectorData vectorData, StrokeCap strokeCap, StrokeJoin strokeJoin, VectorMirror handleMirroring, ShapeWithTextType shapeWithTextType, ConnectorEndpoint connectorStart, ConnectorEndpoint connectorEnd, StrokeCap connectorStartCap, StrokeCap connectorEndCap, ConnectorLineStyle connectorLineStyle, ConstraintType horizontalConstraint, ConstraintType verticalConstraint, NodeChange[] derivedSymbolData, string key, string version, LeadingTrim leadingTrim, float[] dashPattern, ConnectorControlPoint[] connectorControlPoints message Blob byte[] bytes message Message NodeChange[] nodeChanges, Blob[] blobs "; diff --git a/docs/boards-parity.md b/docs/boards-parity.md index 7526d39aa..ef7c4a8b3 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -64,7 +64,7 @@ all end with the same geometry. | Audio and huddles | missing | | | AI features (summaries, sorting stickies, generating boards) | missing | | | Grid on the page | done | the canvas render draws it after the page colour and before the layers (`figcraft_render::Dots`), so objects cover it. Dots by default, or lines, graph paper (a strong line every 2–12 cells over fainter ones, like Japanese section paper) or none; spacing (4–512), mark size and contrast are settings kept with the preferences (`board.grid`; Preferences ▸ Board grid). Zoomed out it thins out (dots and lines by halves, graph paper down to its strong lines) until the marks are at least 14 points apart (10 for lines), the marks the next step drops fading out first; dots stay about a point and a half across on screen (1 to 3 points), scaled by the size setting. Dark marks on a light page, light ones on a dark page, from the theme's ink; written straight into the image, no allocation per mark, a crossing of two lines blended once; never in exports. FigCraft's own settings: the incumbent's board grid has none | -| `.jam` import and export | **partial**: a `.jam` opens as a board, best effort (#1342): its stickies and shapes with text come in as frames with their generated layers and its connectors as vectors, not as native board objects; no export | see [`file-format-parity.md`](file-format-parity.md) | +| `.jam` import and export | **partial**: a `.jam` opens as a board, best effort (#1342): its stickies and shapes with text come in as frames with their generated layers and its connectors as vectors, not as native board objects (an elbowed connector keeps the path it was saved with, #1910); no export | see [`file-format-parity.md`](file-format-parity.md) | ## Revision history diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 56cc701a2..835e3ac00 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of `/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's @@ -17,10 +17,10 @@ and prototype interactions are still unchecked there. | Format | Figma | FigCraft read | FigCraft write | Fidelity / testing | Hours | |---|---|---|---|---|---| -| `.fig` (Figma Design, `com.figma.document`, `application/x-figma`) | native (cloud; "Save local copy") | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP) | **experimental** ([below](#export-to-fig-experimental)) | `.fig` files open (best effort): the zip, its deflate/zstd chunks and the kiwi schema are decoded generically and mapped by field name onto the REST importer, so pages, the layer tree, geometry, paints (styles resolved), strokes, effects, text with styled runs, vectors as editable vector networks with region-specific fill paints (points, curved segments, filled areas with their winding, per-point corner radius and handle mirroring, end caps; outlines when the network is missing or damaged), auto layout (grid included; a flow that records no primary-axis sizing hugs on that axis, an instance that records no auto layout has its main's), constraints, ellipse arcs, boolean operations, components, sets (with their descriptions), instances (expanded from their main with overrides, derived layout and property values; the size and resizing their layers override stay overrides), styles, variables with modes and bindings, prototyping (set-variable, set-variable-mode and conditional actions included) and image fills from the archive come across; sticky notes and shapes with text keep their generated backgrounds, styled text, text paints, saved child bounds and sticky author lines as editable frame children, including saved vector networks without geometry paths, outer fill/stroke outlines when generated geometry is damaged, and outer body text when its generated child is unusable even if an author survives (#1341, #1397); connectors, tables, code blocks, slides and similar layers come in as the closest frames, text layers and vectors, with a warning; anything else is a warning. Since 2026-10-17 (community batches #727, #728): an instance's own identity and the cached library components a file carries, overrides applied by key and order, local text values and instance overrides over a shared text style, grid track sizes (fixed, content-sized, fill), slot content, labels of connectors saved with their drawn path (a static snapshot; the ends aren't live), skip ink, paragraph options and hanging lists, list start numbers, vertical trim, per-point stroke joins, editable text on a path, image adjustments and images carried in the message; since 2026-10-29, style links that name a library style by asset key and version (the file's own copy of it), with override rows above the linking one still winning, and override rows restating a nested level's overrides applied at that level, below the instance's own (#1234), and the line breaks the file saved with a text, followed until an edit or a resize could move one, or where a line would come out more than 3% wider than its box in the fonts at hand (#1236). Budgets come from the file's own size (four decoded values per compressed byte, 20M–128M, lower ceilings on 32-bit targets; the layer cap follows the file's size too), so a 15.4 MB synthetic file with 300,000 layers opens whole; ZIP image reads have a separate total budget of 4 GiB (1 GiB on 32-bit targets) of decompressed ZIP-member bytes containing encoded images, with the 256 MiB per-image cap kept: a member that cannot fit is skipped before its output buffer is allocated, and the import report names the budget and counts skipped images (#1076). Failed reads and invalid image contents still consume the bytes read; a reference used by several layers is read once. This is not a limit on decoded pixels or total import memory; images carried inside the message are unchanged. The file's bytes stay out of the command journal; an import report lists what was left out or changed once the file opens. Elbowed and curved connectors without a saved path are routed as FigCraft's board connectors are (right angles, or one curve, from the sides of the layers they join), and a connector routed here takes its line's paint, weight, cap and dashes from the file's generated line record, as one with a saved snapshot does (#1807). A connector's label without a saved snapshot is kept as text centred on its line, without its background. Not read: table cells beyond their own layers, live style and variable links for vector region fills, variables bound to fields the editor can't bind, video fills. Tested on fixtures generated in code (`crates/format/src/fig/tests.rs`, `tail_tests.rs` and the per-feature `*_tests.rs` beside them, fuzzed), `crates/engine/src/shapebuilder_region_paints_tests.rs`, and by reading back what the export writes; the FigJam report sample from #1341 checked locally only; no representative real-world corpus yet | read tail 5–10, write: checks against real files 5–15 | +| `.fig` (Figma Design, `com.figma.document`, `application/x-figma`) | native (cloud; "Save local copy") | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP) | **experimental** ([below](#export-to-fig-experimental)) | `.fig` files open (best effort): the zip, its deflate/zstd chunks and the kiwi schema are decoded generically and mapped by field name onto the REST importer, so pages, the layer tree, geometry, paints (styles resolved), strokes, effects, text with styled runs, vectors as editable vector networks with region-specific fill paints (points, curved segments, filled areas with their winding, per-point corner radius and handle mirroring, end caps; outlines when the network is missing or damaged), auto layout (grid included; a flow that records no primary-axis sizing hugs on that axis, an instance that records no auto layout has its main's), constraints, ellipse arcs, boolean operations, components, sets (with their descriptions), instances (expanded from their main with overrides, derived layout and property values; the size and resizing their layers override stay overrides), styles, variables with modes and bindings, prototyping (set-variable, set-variable-mode and conditional actions included) and image fills from the archive come across; sticky notes and shapes with text keep their generated backgrounds, styled text, text paints, saved child bounds and sticky author lines as editable frame children, including saved vector networks without geometry paths, outer fill/stroke outlines when generated geometry is damaged, and outer body text when its generated child is unusable even if an author survives (#1341, #1397); connectors, tables, code blocks, slides and similar layers come in as the closest frames, text layers and vectors, with a warning; anything else is a warning. Since 2026-10-17 (community batches #727, #728): an instance's own identity and the cached library components a file carries, overrides applied by key and order, local text values and instance overrides over a shared text style, grid track sizes (fixed, content-sized, fill), slot content, labels of connectors saved with their drawn path (a static snapshot; the ends aren't live), skip ink, paragraph options and hanging lists, list start numbers, vertical trim, per-point stroke joins, editable text on a path, image adjustments and images carried in the message; since 2026-10-29, style links that name a library style by asset key and version (the file's own copy of it), with override rows above the linking one still winning, and override rows restating a nested level's overrides applied at that level, below the instance's own (#1234), and the line breaks the file saved with a text, followed until an edit or a resize could move one, or where a line would come out more than 3% wider than its box in the fonts at hand (#1236). Budgets come from the file's own size (four decoded values per compressed byte, 20M–128M, lower ceilings on 32-bit targets; the layer cap follows the file's size too), so a 15.4 MB synthetic file with 300,000 layers opens whole; ZIP image reads have a separate total budget of 4 GiB (1 GiB on 32-bit targets) of decompressed ZIP-member bytes containing encoded images, with the 256 MiB per-image cap kept: a member that cannot fit is skipped before its output buffer is allocated, and the import report names the budget and counts skipped images (#1076). Failed reads and invalid image contents still consume the bytes read; a reference used by several layers is read once. This is not a limit on decoded pixels or total import memory; images carried inside the message are unchanged. The file's bytes stay out of the command journal; an import report lists what was left out or changed once the file opens. Elbowed and curved connectors without a saved path are routed as FigCraft's board connectors are (right angles, or one curve, from the sides of the layers they join); an elbowed one saved with its path (`connectorControlPoints`: a point and an axis per run between the first and the last) keeps that path when it leaves and arrives by the ends' sides (#1910), and a curved one's saved `connectorBezierControlPoints` are not read; a connector routed here takes its line's paint, weight, cap and dashes from the file's generated line record, as one with a saved snapshot does (#1807). A connector's label without a saved snapshot is kept as text centred on its line, without its background. Not read: table cells beyond their own layers, live style and variable links for vector region fills, variables bound to fields the editor can't bind, video fills. Tested on fixtures generated in code (`crates/format/src/fig/tests.rs`, `tail_tests.rs` and the per-feature `*_tests.rs` beside them, fuzzed), `crates/engine/src/shapebuilder_region_paints_tests.rs`, and by reading back what the export writes; the FigJam report sample from #1341 checked locally only; no representative real-world corpus yet | read tail 5–10, write: checks against real files 5–15 | | `.penpot` (Penpot 2.x ZIP export) | — | **yes, offline** (open, import, drop, CLI, MCP) | **yes, offline** (export, CLI convert) | Editable layers, supported flex/grid layout, components, tokens and prototypes using the existing model. Unsupported layouts retain saved positions and bounded metadata; toggle-overlay and embedded font binaries are reported. Font references remain editable; no downloads. Synthetic regression coverage; live Penpot and cross-platform QA remain open. See [Penpot reference](penpot.md). | further live Penpot and cross-platform QA | | `.sketch` (Sketch 48 and newer) | import (file browser ▸ Import or drop, desktop app too; converted to a Figma file, symbols as components; per the help center) | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP; Open With from Finder, Explorer and Linux file managers once installed; recent files show its `previews/preview.png`) | no (out of scope) | zip + JSON read from the public format description; Sketch 43–47 (text as binary property lists) and older (SQLite) files are refused with a message to resave them in a newer Sketch. Pages, artboards as frames with their background, groups; Sketch 2025 and newer: frames (clipping or not) with their style, graphics, stacks as auto layout (direction, gap, alignment, padding, wrap, hug/fill sizing, stretching filling every item across, items ignoring the stack), corners in the style (rounded, smooth with its smoothing; angled, inside square and inside arc as paths), pins and sizing, per-side borders, lists of blurs (progressive background blurs, glass), inner shadows in the shadow list, tints (a graphic's, group's or instance's fill colouring its layers, and colour overrides; from Sketch 64, before which a group's fill draws nothing), text colour and visibility overrides, text sized by its sizing; rectangles with corner radii, ovals, stars and polygons while their points are the generated ones, paths as editable vector networks, shape groups as their shape, as one compound path (children without an operation, by the group's winding rule) or as boolean operations (mixed operations nested from the left); operands' own borders ignored as Sketch does; open paths filled as if closed, edited ovals and rectangles as paths, bitmaps (their image under their style's fills; colour adjustments as image filters with Sketch's tone curve, contrast and then brightness added), slices, hotspots; transforms (rotation, flips after it), resizing constraints; fills (solid, gradients with Sketch's geometry, gradients mixed in OKLab or OKLCH as sRGB stops along the same colours, image patterns), borders (the first enabled border's width and position), shadows, inner shadows, layer, motion and background blurs (Sketch's radius is the standard deviation), opacity and blend modes; clipping masks (an outline mask that shows its own style draws a copy under itself, as Sketch does, and its opacity fades it and what it clips together; alpha masks only mask; broken mask chains wrapped), progressive opacity (Fade) as an alpha mask of its gradient; text with styled runs (UTF-16 ranges), paragraph and vertical alignment, lines placed by Sketch's line spacing behaviour, box sizing, fonts found by their PostScript names among the installed ones (else the family read from the name), variable font axes, Sketch's natural line (ascent and descent rounded, no line gap, a fifth more for classic Mac fonts) for text without a fixed line height; symbols as components (library copies on a page of their own) and instances carrying their masters' layers with overrides (text, nested swaps and hiding, images, also on shapes' image fills, layer and text styles, nested paths), clipping only where the master clips (`clippingBehavior` 1), laid out for their size the way Sketch does it (proportional sharing per pins from format 110, scaling before) and still live; master backgrounds in instances only when the master includes them in both instances and exports, as on Sketch's canvas and renders; Apple's system fonts found under the names designs use, with the platform's tracking kept as letter spacing; shared layer styles as paint (fills, border colours) and effect styles, shared text styles as text styles; Color Variables (also library ones) as colour variables with bindings; prototype links, flow starts, export options, layout and square grids (hidden, as Sketch shows them only in its layout view). Instances of a stack laid out at their size and texts an override changed measured again on open, an auto-width one growing from its aligned edge. Warnings: noise fills, OKLab and OKLCH gradients, motion and zoom blurs (drawn as plain blurs), fonts embedded with their data (not used), Smart Layout (kept as laid out), locked overrides, scaled instances. Tested on fixtures built in code (`crates/format/src/sketch/*_tests.rs`, fuzzed) and locally (`FIGCRAFT_SKETCH_SAMPLES`) on one real Sketch 50 file and the public Apache-2.0 IBM Carbon Design Kit saved by Sketch 68 and 83 (70,000 layers open in ~3 s, debug build; its edition saved by Sketch 47 is refused, as it should be); compared artboard by artboard with Sketch 2026's own renders (`FIGCRAFT_SKETCHTOOL`, black-box): the Sketch 50 file's 73 artboards differ in at most 2.3% of their pixels (0.8% on average) (text metrics, fonts FigCraft doesn't find, antialiasing), Carbon 11's 69 1.1% on average and at most 4.4% (text in IBM Plex, which the file embeds and FigCraft doesn't use yet), a Sketch 64 file's 65 artboards 2.1% on average, a Sketch 2026 showcase file's 16 frames 0.9% on average (at most 1.9%); the rules for master backgrounds, symbol clipping, mask opacity, bitmap fills, image overrides, stretching stacks, blur radii, colour adjustments, gradient interpolation and text growth checked against Sketch's renders of files built for each case (black-box, synthetic) | 5–10 (Smart Layout as auto layout, motion and zoom blurs, several borders of different widths; fonts embedded in the file once `.figcraft` documents can carry fonts: until then they would only last the session). Known limitations: a plain group (not a frame) that fills a stack keeps its layers' size where Sketch stretches them; a font Sketch can't find draws in the installed family's own weight (Sketch falls back to a regular face); text in the system SF Pro comes out a few percent narrower than Sketch's; macOS's reserved system fonts (PingFang) aren't found; brightness past about +0.4 is approximated (image filters can't add); OKLab gradients become sRGB stops (FigCraft gradients mix in sRGB) | -| `.jam` (whiteboards) | native to FigJam | **yes, best effort** (`file.open`, `file.import`, File ▸ Open, drop, CLI, MCP) | no | the same archive as a `.fig` (its canvas header reads `fig-jam.`) through the same reader (#1342): it opens as a board (the file kind; a `.fig` stays a design file), with generated sticky and shape backgrounds and text kept (#1341) as ordinary layers rather than native board objects (see [boards-parity](boards-parity.md)); tables, stamps, code blocks and the like come in as frames with their text and connectors as vectors, with an import note; a layer type the reader doesn't know is left out with a note naming it; writing `.jam` is not supported | — | +| `.jam` (whiteboards) | native to FigJam | **yes, best effort** (`file.open`, `file.import`, File ▸ Open, drop, CLI, MCP) | no | the same archive as a `.fig` (its canvas header reads `fig-jam.`) through the same reader (#1342): it opens as a board (the file kind; a `.fig` stays a design file), with generated sticky and shape backgrounds and text kept (#1341) as ordinary layers rather than native board objects (see [boards-parity](boards-parity.md)); tables, stamps, code blocks and the like come in as frames with their text and connectors as vectors (an elbowed connector keeps the path it was saved with, #1910), with an import note; a layer type the reader doesn't know is left out with a note naming it; writing `.jam` is not supported | — | | `.deck` (Slides) | native to other Figma products | no | no | out of scope | — | | REST API file JSON (`GET /v1/files/:key`) + local variables JSON + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints, strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings, image adjustments (the same tint sign as `.fig`); the import report after opening; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — | | `.figcraft` (ours: zip of `document.json` + images, versions inside) | — | yes | yes | streamed JSON, 50k layers save ~0.09 s / load ~0.16 s (`cargo xtask bench`); old files keep opening (`large_tests.rs`); image members are `images/`, and a key that can't be one — path text, a space, over 128 chars — is left out with a complaint instead of loaded (`image_tests`); saves write a unique staging file and rename it into place (#284); optional auto-save of files with a path (`pref.autoSave`, #305); Save and auto-save refuse to write over a file another app (figcraft-cli, say) changed since it was opened or saved here, judged by its size and modification time: Revert to saved loads those changes, Save as keeps both, `file.save {overwrite: true}` replaces them (#1330); `kind: "board"` marks a board (left out for design files, so files from before boards are design files; the home screen reads it for the file's mark); board objects keep their `board` metadata on the layer; Dev Mode measurements are kept on the layer they start from (`measurements: [{to} | {side}]`, left out when there are none, so older files open with none) | — | @@ -187,6 +187,7 @@ source paint coordinates. | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | `.fig` and `.jam` import, #1910: an elbowed connector saved with its path keeps it. FigJam stores `connectorControlPoints`, one per run between the first and the last, each a point on its run (in the connector's parent's coordinates) with the run's axis; the first run leaves the start's side and the last arrives at the end's. They become the `ConnectorPath::Runs` a board connector reshaped by hand has (`figcraft_doc::route_along`), so a connector drawn around a layer in FigJam stays around it instead of being routed through it. Points that don't make such a path (off both axes, two runs in a row the same way, a first or last run sideways to its side, more runs than a hand could make) leave the connector to the router as before, and only connectors routed here count in the "follow FigCraft's own routing" note. A curved connector's `connectorBezierControlPoints` are still not read. Tests: `tail_tests::an_elbow_connector_saved_with_its_path_keeps_it`, `tail_tests::an_elbow_whose_saved_path_doesnt_fit_its_sides_is_routed_here`. | | 2026-11-01 | patch | `.fig` and `.jam` import: a connector without a saved snapshot (elbowed and curved ones are routed here) took no stroke, so it was invisible (#1807); its line's paint, weight, cap and dashes now come from the file's generated line record, as a saved snapshot's do, and the connector's own values, when it has any, win. Test: `fig::connector_label_tests::a_routed_connector_takes_its_line_style_from_the_generated_record`. 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 | | 2026-10-30 | minor | `.fig` import: a connector's label without a saved snapshot was skipped; now the connector imports as a frame holding its line and the label, as a connector with a saved snapshot does, the label centred on the line's middle by length (in a 200-wide box, laid out again with the fonts at hand), in the connector's fill paints or black. Its background isn't known without the snapshot and is left out. Not checked on real files. Test: `fig::tests::tail::a_labelled_connector_without_a_snapshot_keeps_its_label` | From 5855c8705c81a7f624c8ecbaba1214538cc273f8 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 4 Nov 2026 02:39:24 -0500 Subject: [PATCH 066/102] docs: boards-parity's status line and revision history move with its .jam row (#1910) Review: the row changed without the status line and a history row, which land together. Co-Authored-By: Claude Fable 5.1 --- docs/boards-parity.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/boards-parity.md b/docs/boards-parity.md index ef7c4a8b3..cf72aaa8c 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -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:** patch (a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); 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 @@ -70,6 +70,7 @@ all end with the same geometry. | Date | Change | Summary | |---|---|---| +| 2026-11-04 | patch | M6, #1910: a `.jam` elbowed connector saved with its path (FigJam's `connectorControlPoints`) keeps it on import: the points become the `ConnectorPath::Runs` a connector reshaped by hand has and the line is walked along them, so a connector drawn around a layer stays around it; one whose points don't make a path from its ends' sides is routed as before. Still a vector, not a native board object. Details in [`file-format-parity.md`](file-format-parity.md). | | 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. | From 31dcd0e5feca2d4ff7b80d69a4b996880c476198 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 4 Nov 2026 03:46:49 -0500 Subject: [PATCH 067/102] M6: a saved connector path going back into its object is routed instead (#1910) Review: the first and last runs were checked for lying at right angles to their sides, not for going out of the object, so a path whose first run went up through the start's box (or whose last arrived from inside the end's) was kept and drawn through it. Both runs now have to go the way the side faces; one along the side or back into the object leaves the connector to the router. Two more cases in the routed-here test. Co-Authored-By: Claude Fable 5.1 --- crates/format/src/fig/map/connector.rs | 12 ++++++++---- crates/format/src/fig/tail_tests.rs | 6 +++++- docs/file-format-parity.md | 2 +- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/crates/format/src/fig/map/connector.rs b/crates/format/src/fig/map/connector.rs index 01c07c00e..e89b875ed 100644 --- a/crates/format/src/fig/map/connector.rs +++ b/crates/format/src/fig/map/connector.rs @@ -440,12 +440,16 @@ fn saved_runs(v: &View<'_>, from: RouteEnd, to: RouteEnd) -> Option, p: Point, q: Point| s.is_none_or(|s| (q - p).dot(s.normal()) > 0.0); let (s0, s1) = attached_sides(from, to); - let fits = s0.is_none_or(|s| faces_across(s) == across) && s1.is_none_or(|s| faces_across(s) != last); + let fits = out_of(s0, p0, onto(across, p0, a0)) && out_of(s1, p1, onto(!last, p1, a1)); fits.then_some(ConnectorPath::Runs { across, at }) } diff --git a/crates/format/src/fig/tail_tests.rs b/crates/format/src/fig/tail_tests.rs index 09e6ed85a..773edd4d8 100644 --- a/crates/format/src/fig/tail_tests.rs +++ b/crates/format/src/fig/tail_tests.rs @@ -927,6 +927,10 @@ fn an_elbow_whose_saved_path_doesnt_fit_its_sides_is_routed_here() { elbow(67, "Sideways", vec![point(100.0, 650.0, 0.0, 1.0)]), elbow(68, "Askew", vec![point(150.0, 740.0, 1.0, 1.0)]), elbow(69, "Repeated", vec![point(150.0, 740.0, 1.0, 0.0), point(150.0, 760.0, 1.0, 0.0)]), + // The first run would go up from A's bottom, through A; the last would arrive at B's left + // from inside B. Each run is at right angles to its side, so only the way it goes is wrong. + elbow(70, "Backwards", vec![point(100.0, 650.0, 1.0, 0.0), point(200.0, 740.0, 0.0, 1.0)]), + elbow(71, "Inside", vec![point(150.0, 740.0, 1.0, 0.0), point(350.0, 800.0, 0.0, 1.0)]), ]); let (doc, warnings) = import(&canvas(&schema(), &message), "Unfit paths").unwrap(); let line = |name: &str| -> Vec<(f64, f64)> { @@ -935,7 +939,7 @@ fn an_elbow_whose_saved_path_doesnt_fit_its_sides_is_routed_here() { }; let plain = line("Plain"); assert!(plain.len() >= 3, "routed in right angles: {plain:?}"); - for name in ["Sideways", "Askew", "Repeated"] { + for name in ["Sideways", "Askew", "Repeated", "Backwards", "Inside"] { assert_eq!(line(name), plain, "{name} is routed as one without a path"); } assert!(warnings.iter().any(|w| w.contains("FigCraft's own routing")), "{warnings:?}"); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 835e3ac00..d60a70c0d 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -187,7 +187,7 @@ source paint coordinates. | Date | Change | Summary | |---|---|---| -| 2026-11-04 | minor | `.fig` and `.jam` import, #1910: an elbowed connector saved with its path keeps it. FigJam stores `connectorControlPoints`, one per run between the first and the last, each a point on its run (in the connector's parent's coordinates) with the run's axis; the first run leaves the start's side and the last arrives at the end's. They become the `ConnectorPath::Runs` a board connector reshaped by hand has (`figcraft_doc::route_along`), so a connector drawn around a layer in FigJam stays around it instead of being routed through it. Points that don't make such a path (off both axes, two runs in a row the same way, a first or last run sideways to its side, more runs than a hand could make) leave the connector to the router as before, and only connectors routed here count in the "follow FigCraft's own routing" note. A curved connector's `connectorBezierControlPoints` are still not read. Tests: `tail_tests::an_elbow_connector_saved_with_its_path_keeps_it`, `tail_tests::an_elbow_whose_saved_path_doesnt_fit_its_sides_is_routed_here`. | +| 2026-11-04 | minor | `.fig` and `.jam` import, #1910: an elbowed connector saved with its path keeps it. FigJam stores `connectorControlPoints`, one per run between the first and the last, each a point on its run (in the connector's parent's coordinates) with the run's axis; the first run leaves the start's side and the last arrives at the end's. They become the `ConnectorPath::Runs` a board connector reshaped by hand has (`figcraft_doc::route_along`), so a connector drawn around a layer in FigJam stays around it instead of being routed through it. Points that don't make such a path (off both axes, two runs in a row the same way, a first or last run sideways to its side or going back into its object, more runs than a hand could make) leave the connector to the router as before, and only connectors routed here count in the "follow FigCraft's own routing" note. A curved connector's `connectorBezierControlPoints` are still not read. Tests: `tail_tests::an_elbow_connector_saved_with_its_path_keeps_it`, `tail_tests::an_elbow_whose_saved_path_doesnt_fit_its_sides_is_routed_here`. | | 2026-11-01 | patch | `.fig` and `.jam` import: a connector without a saved snapshot (elbowed and curved ones are routed here) took no stroke, so it was invisible (#1807); its line's paint, weight, cap and dashes now come from the file's generated line record, as a saved snapshot's do, and the connector's own values, when it has any, win. Test: `fig::connector_label_tests::a_routed_connector_takes_its_line_style_from_the_generated_record`. 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 | | 2026-10-30 | minor | `.fig` import: a connector's label without a saved snapshot was skipped; now the connector imports as a frame holding its line and the label, as a connector with a saved snapshot does, the label centred on the line's middle by length (in a 200-wide box, laid out again with the fonts at hand), in the connector's fill paints or black. Its background isn't known without the snapshot and is left out. Not checked on real files. Test: `fig::tests::tail::a_labelled_connector_without_a_snapshot_keeps_its_label` | From 95d71a6825477e13a74deddc1f4401ef0a2c0f03 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 4 Nov 2026 03:59:46 -0500 Subject: [PATCH 068/102] M4: justified Chinese, Japanese and Korean text spreads the room between its characters (#1970) Cause: justified lines only widened their spaces, so a line of ideographs, written without any, kept its natural width and its right edge never reached the box's. Fix: the room on a line (but a paragraph's last) also goes into the gaps next to an ideograph, kana, Hangul or full-width form wherever a line could break there (`breaks::justify_between`, beside `break_between`): each is a word of its own, as for line breaking, and no gap opens before a closing mark or after an opening one. Spaces widen as before; mixed text widens both. Co-Authored-By: Claude Fable 5.1 --- crates/text/src/breaks.rs | 9 ++++++++ crates/text/src/layout.rs | 14 ++++++++---- crates/text/src/tests.rs | 45 +++++++++++++++++++++++++++++++++++++++ docs/target-app-parity.md | 5 +++-- 4 files changed, 67 insertions(+), 6 deletions(-) diff --git a/crates/text/src/breaks.rs b/crates/text/src/breaks.rs index 6d094e9dc..f0352f852 100644 --- a/crates/text/src/breaks.rs +++ b/crates/text/src/breaks.rs @@ -79,6 +79,15 @@ pub(crate) fn is_space(c: char) -> bool { class(c) == Class::Space } +/// Whether justified text may widen the gap between `a` and the `b` after it (a space widens on +/// its own): next to an ideograph, kana, Hangul or full-width form, which are written without +/// spaces, so each is a word of its own, as for line breaking, wherever a line may break there (no +/// gap before a closing mark or after an opening one). +pub(crate) fn justify_between(a: char, b: char) -> bool { + let (ca, cb) = (class(a), class(b)); + (ca == Class::Ideo || cb == Class::Ideo) && ca != Class::Space && break_between(a, b) +} + /// Whether `c` is in a script written without spaces between words that the line segmenter has /// word data for (UAX #14 class SA): Thai, Lao, Burmese (with the Myanmar extensions) and Khmer. fn writes_no_spaces(c: char) -> bool { diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index dd728916b..1cb5170fa 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -1259,8 +1259,13 @@ pub fn layout(text: &TextData, box_width: Option, box_height: Option) let hang_r = items.get(vis_end.wrapping_sub(1)).filter(|it| hang_end && !rtl_line && vis_end > *s + 1 && closes(it.ch)).map_or(0.0, |it| it.adv); let gstart = out.glyphs.len(); - // Justify: extra space per gap. - let gaps = items.get(*s..vis_end).unwrap_or(&[]).iter().filter(|it| it.stretches()).count(); + // Justify: extra space per gap (a space, or between ideographs, whose text has no spaces). + let widens = |k: usize| { + items.get(k).is_some_and(|it| { + it.stretches() || (k + 1 < vis_end && items.get(k + 1).is_some_and(|next| crate::breaks::justify_between(it.ch, next.ch))) + }) + }; + let gaps = (*s..vis_end).filter(|k| widens(*k)).count(); let justify_extra = match (text.align_h, wrap) { (TextAlignH::Justified, Some(maxw)) if !para_end && !line_break_after(&items, *e) && gaps > 0 => { ((maxw - line_indent + hang_l + hang_r - width) / gaps as f64).max(0.0) @@ -1349,13 +1354,14 @@ pub fn layout(text: &TextData, box_width: Option, box_height: Option) } else { (0..line_items.len()).collect() }; - for it in order.iter().filter_map(|k| line_items.get(*k)) { + for k in order.iter().copied() { + let Some(it) = line_items.get(k) else { continue }; if is_line_break(it.ch) { continue; } out.glyphs.extend(glyph_at(&styles, it, pen, baseline)); pen += it.adv; - if it.stretches() { + if widens(*s + k) { pen += justify_extra; } } diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 6d341419c..e59438c83 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -590,6 +590,51 @@ fn lower_case_writes_final_sigma() { assert_eq!(gids(&t).iter().map(|g| g.0).collect::>(), want.iter().map(|g| g.0).collect::>(), "split runs"); } +/// Chinese is written without spaces: justified, the room goes between its characters (each a word +/// of its own, as for line breaking), so the last one reaches the right edge too, and none opens +/// where a line couldn't break (before a closing mark, after an opening one). "Justify aligns the +/// first word in each line of text to the left-most edge, and the last to the right-most edge." +#[test] +fn justified_ideographs_spread_the_room_between_characters() { + if !have_fonts() { + return; + } + let lay_out = |s: &str, align, w| { + let mut t = TextData::new(s); + t.style.font_size = 20.0; + t.align_h = align; + t.auto_resize = figcraft_doc::TextAutoResize::Height; + layout(&t, w, None) + }; + // Box width cut inside char `fit`, so the first line is chars 0..fit; how many gaps lie before + // each of its chars. + for (s, fit, gaps_before, why) in [ + ("一二三四五六七八九十", 6, [0, 1, 2, 3, 4, 5], "one gap between each pair of ideographs"), + ("一二三。四五六七八九", 6, [0, 1, 2, 2, 3, 4], "none before the full stop, which never starts a line"), + ("一二三「四五六七八九", 6, [0, 1, 2, 3, 3, 4], "none after the opening bracket, which never ends a line"), + ] { + let natural = lay_out(s, TextAlignH::Left, None); + let (fits, next) = (natural.caret(fit).0, natural.caret(fit + 1).0); + assert!(next > fits, "{why}: chars need advances"); + let w = fits + (next - fits) / 4.0; + let left = lay_out(s, TextAlignH::Left, Some(w)); + let just = lay_out(s, TextAlignH::Justified, Some(w)); + assert!(just.lines.len() >= 2 && just.lines[0].char_end == fit, "{why}: {:?}", just.lines); + let extra = (w - left.lines[0].width) / f64::from(gaps_before[fit - 1]); + assert!(extra > 0.0, "{why}"); + assert_eq!(left.glyphs.len(), just.glyphs.len()); + for (l, j) in left.glyphs.iter().zip(&just.glyphs).filter(|(g, _)| g.char_end <= fit) { + let want = f64::from(gaps_before[l.char_start]) * extra; + assert!((j.x - l.x - want).abs() < 1e-6, "{why}: char {} moved {} (want {want})", l.char_start, j.x - l.x); + } + let last = just.glyphs.iter().rfind(|g| g.char_end <= fit).unwrap(); + assert!((last.x + last.advance - w).abs() < 1e-6, "{why}: the last char ends at the right edge, not {}", last.x + last.advance); + // The last line is left-aligned, as always. + let (l2, j2) = (left.glyphs.iter().find(|g| g.char_start == fit).unwrap(), just.glyphs.iter().find(|g| g.char_start == fit).unwrap()); + assert!((j2.x - l2.x).abs() < 1e-6, "{why}: the last line is not justified"); + } +} + /// Thai is written without spaces between words; U+200B ZERO WIDTH SPACE marks where a line may /// break. ภาษา|ไทย|เขียน|ติดกัน ("Thai is written joined up") ไม่มี|ช่องว่าง|ระหว่าง|คำ ("with no /// spaces between words"), with one real space between the two phrases. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 75a426231..572bb7ffa 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%; last major: full re-measure against Figma desktop 126.10.7; rows for the community batches: Selection colors, smart-selection spacing and a Present tab (#753), `.fig` import fidelity, paste from another design app, a `.fig` copy from Save as; control requests while the window is minimised (#720); catalog counts re-measured; automation roots (#715); number variables in the text content picker (#629); frames and sections convert into each other (#719)) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** patch (justified Chinese, Japanese and Korean text, written without spaces, spreads each line's room between its characters so its right edge aligns (#1970); bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%; last major: full re-measure against Figma desktop 126.10.7; rows for the community batches: Selection colors, smart-selection spacing and a Present tab (#753), `.fig` import fidelity, paste from another design app, a `.fig` copy from Save as; control requests while the window is minimised (#720); catalog counts re-measured; automation roots (#715); number variables in the text content picker (#629); frames and sections convert into each other (#719)) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is @@ -297,7 +297,7 @@ Hours in this narrative are the builders' estimates; the tables above supersede break inside Latin words, kinsoku to JIS X 4051 for closing and opening punctuation, small kana (halfwidth too), the prolonged sound mark, the iteration marks, the (semi-)voiced sound marks and the halfwidth parentheses); Thai, Lao, Khmer and Burmese lines break between words (ICU4X's word - dictionaries, its LSTM models in the browser), never after a leading vowel or before a mark; a style's metrics from its own font, not a fallback; a letter and + dictionaries, its LSTM models in the browser), never after a leading vowel or before a mark; justified text widens each line's spaces but the last line's, and in Chinese, Japanese and Korean text, which has none, the gaps between its characters wherever a line could break (#1970); a style's metrics from its own font, not a fallback; a letter and its combining marks (Vietnamese typed decomposed, say) from one font that has them all; carets, Delete and Backspace by grapheme cluster; double-click and word moves by script run; IME composition with CJK; vertical trim (cap height to baseline). The tail suite (`crates/text/src/tail_tests.rs`, @@ -648,6 +648,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-04 | patch | M4, #1970: justified Chinese, Japanese and Korean text, written without spaces between words, aligns its right edge: the room on each line but a paragraph's last goes between its characters, each a word of its own as for line breaking ("Justify aligns the first word in each line of text to the left-most edge, and the last to the right-most edge"), wherever a line could break there, so none opens before a full stop or closing bracket, nor after an opening one. Latin text widens its spaces as before; mixed text widens both. `figcraft_text::breaks::justify_between`, beside `break_between`, says where. Evidence: `tests::justified_ideographs_spread_the_room_between_characters` (fails on main). | | 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 | From 44f9eccb71bbd337e29faf0047ced5ff9adbb30f Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 4 Nov 2026 04:33:28 -0500 Subject: [PATCH 069/102] M4: a justify gap stays out of grapheme clusters and opens beside a right-to-left run (#1970) Review: a combining mark shaped as a glyph of its own (U+20DD on an ideograph, say) got a gap between it and its base; a gap after the last logical glyph of a right-to-left run opened after that glyph's visual place, inside the word, instead of between the run and the ideograph after it. A gap now needs the next item to start a grapheme cluster, and `visual_gaps` opens each logical gap at its visual boundary: between logical neighbours where they are, between two runs where they meet. Two more rows in the test. Co-Authored-By: Claude Fable 5.1 --- crates/text/src/layout.rs | 60 ++++++++++++++++++++++++++++++++++++--- crates/text/src/tests.rs | 14 +++++---- 2 files changed, 65 insertions(+), 9 deletions(-) diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 1cb5170fa..59e0d5877 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -297,6 +297,48 @@ pub(crate) fn is_rtl_char(c: char) -> bool { matches!(c as u32, 0x0590..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFF | 0x10800..=0x10FFF | 0x1E800..=0x1EFFF | 0x200F | 0x202B | 0x202E | 0x2067) } +/// Which visual positions of `order` (the logical index at each) a justify gap follows. A gap +/// after logical item k (`after[k]`) opens between logically neighbouring glyphs where they are, +/// or where two runs meet (a right-to-left run is laid out reversed) between the runs, so a gap +/// beside a Hebrew word in Chinese text opens beside the word, not inside it; each opens once. +/// From item `trailing` on (a line's trailing spaces) a gap opens after the item itself. +fn visual_gaps(order: &[usize], after: &[bool], trailing: usize) -> Vec { + let run_min = visual_run_starts(order); + let mut applied = vec![false; after.len()]; + let gap_after = |k: usize| after.get(k).copied().unwrap_or(false); + order + .iter() + .enumerate() + .map(|(i, &k)| { + if k >= trailing { + return gap_after(k); + } + let at = match order.get(i + 1) { + Some(&n) if n == k + 1 || k == n + 1 => Some(k.min(n)), + Some(_) => run_min.get(i).copied().max(run_min.get(i + 1).copied()).and_then(|m| m.checked_sub(1)), + None => None, + }; + at.is_some_and(|g| gap_after(g) && applied.get_mut(g).is_some_and(|a| !std::mem::replace(a, true))) + }) + .collect() +} + +/// For each position of `order` (the logical index at each visual position), the smallest +/// logical index of its run: the visually consecutive glyphs whose logical indices step one way. +fn visual_run_starts(order: &[usize]) -> Vec { + let mut out = Vec::with_capacity(order.len()); + let mut start = 0; + for i in 1..=order.len() { + let joined = i < order.len() && order.get(i - 1).zip(order.get(i)).is_some_and(|(&p, &k)| p + 1 == k || k + 1 == p); + if !joined { + let m = order.get(start..i).and_then(|run| run.iter().copied().min()).unwrap_or(0); + out.extend(std::iter::repeat_n(m, i - start)); + start = i; + } + } + out +} + /// Visual order of a line's items from their levels (rule L2: from the highest level down to the /// lowest odd one, reverse every run at that level or above). pub(crate) fn visual_order(levels: &[u8]) -> Vec { @@ -1259,10 +1301,17 @@ pub fn layout(text: &TextData, box_width: Option, box_height: Option) let hang_r = items.get(vis_end.wrapping_sub(1)).filter(|it| hang_end && !rtl_line && vis_end > *s + 1 && closes(it.ch)).map_or(0.0, |it| it.adv); let gstart = out.glyphs.len(); - // Justify: extra space per gap (a space, or between ideographs, whose text has no spaces). + // Justify: extra space per gap (a space, or between ideographs, whose text has no spaces; + // never inside a grapheme cluster, so a mark stays on its base). let widens = |k: usize| { items.get(k).is_some_and(|it| { - it.stretches() || (k + 1 < vis_end && items.get(k + 1).is_some_and(|next| crate::breaks::justify_between(it.ch, next.ch))) + it.stretches() + || (k + 1 < vis_end + && items.get(k + 1).is_some_and(|next| { + next.char_start > it.char_start + && cluster_start.get(next.char_start).copied().unwrap_or(true) + && crate::breaks::justify_between(it.ch, next.ch) + })) }) }; let gaps = (*s..vis_end).filter(|k| widens(*k)).count(); @@ -1354,14 +1403,17 @@ pub fn layout(text: &TextData, box_width: Option, box_height: Option) } else { (0..line_items.len()).collect() }; - for k in order.iter().copied() { + // Each gap opens at its visual boundary; trailing spaces widen where they are. + let after: Vec = (0..line_items.len()).map(|k| widens(*s + k)).collect(); + let gaps_at = visual_gaps(&order, &after, vis_end - *s); + for (i, &k) in order.iter().enumerate() { let Some(it) = line_items.get(k) else { continue }; if is_line_break(it.ch) { continue; } out.glyphs.extend(glyph_at(&styles, it, pen, baseline)); pen += it.adv; - if widens(*s + k) { + if gaps_at.get(i).copied().unwrap_or(false) { pen += justify_extra; } } diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index e59438c83..8082ffed3 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -608,11 +608,14 @@ fn justified_ideographs_spread_the_room_between_characters() { }; // Box width cut inside char `fit`, so the first line is chars 0..fit; how many gaps lie before // each of its chars. - for (s, fit, gaps_before, why) in [ - ("一二三四五六七八九十", 6, [0, 1, 2, 3, 4, 5], "one gap between each pair of ideographs"), - ("一二三。四五六七八九", 6, [0, 1, 2, 2, 3, 4], "none before the full stop, which never starts a line"), - ("一二三「四五六七八九", 6, [0, 1, 2, 3, 3, 4], "none after the opening bracket, which never ends a line"), - ] { + let rows: [(&str, usize, &[i32], &str); 5] = [ + ("一二三四五六七八九十", 6, &[0, 1, 2, 3, 4, 5], "one gap between each pair of ideographs"), + ("一二三。四五六七八九", 6, &[0, 1, 2, 2, 3, 4], "none before the full stop, which never starts a line"), + ("一二三「四五六七八九", 6, &[0, 1, 2, 3, 3, 4], "none after the opening bracket, which never ends a line"), + ("一二三\u{20DD}四五六七八九", 6, &[0, 1, 2, 2, 3, 4], "none inside a grapheme cluster: a combining mark stays on its base"), + ("漢אב字一二三", 4, &[0, 1, 1, 2], "beside a right-to-left word (laid out ב then א), not inside it"), + ]; + for (s, fit, gaps_before, why) in rows { let natural = lay_out(s, TextAlignH::Left, None); let (fits, next) = (natural.caret(fit).0, natural.caret(fit + 1).0); assert!(next > fits, "{why}: chars need advances"); @@ -621,6 +624,7 @@ fn justified_ideographs_spread_the_room_between_characters() { let just = lay_out(s, TextAlignH::Justified, Some(w)); assert!(just.lines.len() >= 2 && just.lines[0].char_end == fit, "{why}: {:?}", just.lines); let extra = (w - left.lines[0].width) / f64::from(gaps_before[fit - 1]); + assert_eq!(left.lines[0].char_end, fit, "{why}: {:?}", left.lines); assert!(extra > 0.0, "{why}"); assert_eq!(left.glyphs.len(), just.glyphs.len()); for (l, j) in left.glyphs.iter().zip(&just.glyphs).filter(|(g, _)| g.char_end <= fit) { From de881846a88555a35ea866e5a89e8ec063fe1359 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 4 Nov 2026 04:35:37 -0500 Subject: [PATCH 070/102] M8: joining the ends of a path broken open closes its fill loop through the new segment (#1951) Cause: deleting a point with Delete (not Shift+Delete) opens the path and leaves its region's loop with a gap, filled closed by a straight line across it; joining the two ends again (the pen onto the other end, Connect, Join) added the segment to the network but not to the loop, which still spanned the gap. Unrounded, the straight line and the segment coincide; once the points are rounded, the fill and the selection outline run straight across while the stroke, walked from the network itself, follows the segment and its arcs (#1506's picture). Fix: `ops::connect` splices the new segment into the loop whose segments are the chain between the two ends, so the loop closes through it; a chain no loop fills still becomes a region of its own. Tests: the chamfer made by Shift+Delete, by Delete then Connect, and drawn with the pen, each rounded, with the fill tracing the stroke (engine); every loop order and segment direction of a chamfered rectangle (doc). Co-Authored-By: Claude Fable 5.1 --- crates/doc/src/tests.rs | 55 +++++++++++++ crates/engine/src/canvas/vectoredit/ops.rs | 12 ++- crates/engine/src/canvas/vectoredit/tests.rs | 82 ++++++++++++++++++++ docs/target-app-parity.md | 6 +- 4 files changed, 151 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 6ac6f455b..3a84a4c34 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -681,6 +681,61 @@ fn two_segment_closed_loop_rounded_corners() { assert!(!path.elements().is_empty()); } +/// A rectangle whose top-right corner was cut off in the vector editor (a diagonal between a point +/// on the top edge and one on the right edge), then rounded: the fill, which the fill and the +/// selection outline draw, is cut by an arc at every point just as the stroke is, however the loop +/// lists its segments and whichever way each one runs (#1951, #1506). +#[test] +fn a_chamfered_rectangles_rounded_fill_is_cut_at_every_point() { + use figcraft_geom::BezPath; + use figcraft_geom::kurbo::{ParamCurveArclen, ParamCurveNearest}; + let corners = [Point::new(0.0, 0.0), Point::new(50.0, 0.0), Point::new(100.0, 50.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)]; + let keeps_off = |path: &BezPath, p: Point| path.segments().map(|s| s.nearest(p, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min); + let length = |path: &BezPath| path.segments().map(|s| s.arclen(1e-9)).sum::(); + for first in 0..corners.len() { + for backwards in [false, true] { + for flipped in 0..(1u32 << corners.len()) { + let mut net = VectorNetwork::from_points(&corners, true); + for v in &mut net.vertices { + v.radius = 43.0; + } + for (i, s) in net.segments.iter_mut().enumerate() { + if flipped & (1 << i) != 0 { + std::mem::swap(&mut s.a, &mut s.b); + std::mem::swap(&mut s.ta, &mut s.tb); + } + } + let lp = &mut net.regions[0].loops[0]; + lp.rotate_left(first); + if backwards { + lp.reverse(); + } + let why = format!("loop from segment {first}{}, segments flipped {flipped:05b}", if backwards { " backwards" } else { "" }); + let stroke = net.stroke_path(); + let fill = net.fill_path(); + let region = net.rounded().unwrap().region_path(0).unwrap(); + for (i, p) in corners.iter().enumerate() { + assert!(keeps_off(&stroke, *p) > 2.0, "{why}: the stroke is cut at point {i} ({:.2} from it)", keeps_off(&stroke, *p)); + assert!(keeps_off(&fill, *p) > 2.0, "{why}: the fill runs into point {i} ({:.2} from it)", keeps_off(&fill, *p)); + assert!(keeps_off(®ion, *p) > 2.0, "{why}: the region runs into point {i} ({:.2} from it)", keeps_off(®ion, *p)); + } + assert!( + (length(&fill) - length(&stroke)).abs() < 1e-6, + "{why}: fill {} and stroke {} trace the same outline", + length(&fill), + length(&stroke) + ); + assert!( + (length(®ion) - length(&stroke)).abs() < 1e-6, + "{why}: region {} and stroke {} trace the same outline", + length(®ion), + length(&stroke) + ); + } + } + } +} + #[test] fn stored_variable_ids_resolve_only_their_exact_collection() { let mut vars = crate::proto_expr_tests::vars(); diff --git a/crates/engine/src/canvas/vectoredit/ops.rs b/crates/engine/src/canvas/vectoredit/ops.rs index b44ee941d..993e45066 100644 --- a/crates/engine/src/canvas/vectoredit/ops.rs +++ b/crates/engine/src/canvas/vectoredit/ops.rs @@ -658,8 +658,16 @@ pub fn connect(net: &mut VectorNetwork, a: usize, b: usize, ta: (f64, f64), tb: net.segments.push(Segment { a, b, ta: finite_t(ta), tb: finite_t(tb) }); let si = net.segments.len() - 1; if ends && let Some(mut lp) = path_between(net, b, a, si) { - let unfilled = !net.regions.iter().any(|r| r.loops.iter().flatten().any(|s| lp.contains(s))); - if unfilled { + let filled = net.regions.iter().any(|r| r.loops.iter().flatten().any(|s| lp.contains(s))); + if filled { + // A loop broken open at these ends (a point of it deleted, say) closes through the new + // segment, so the fill follows it instead of a straight line across the gap (#1951). + for l in net.regions.iter_mut().flat_map(|r| r.loops.iter_mut()) { + if l.len() == lp.len() && l.iter().all(|s| lp.contains(s)) { + *l = std::iter::once(si).chain(lp.iter().copied()).collect(); + } + } + } else { lp.insert(0, si); net.regions.push(Region { loops: vec![lp], winding: WindingRule::NonZero, fills: None, ..Default::default() }); } diff --git a/crates/engine/src/canvas/vectoredit/tests.rs b/crates/engine/src/canvas/vectoredit/tests.rs index 30d62e1af..3812c1b7b 100644 --- a/crates/engine/src/canvas/vectoredit/tests.rs +++ b/crates/engine/src/canvas/vectoredit/tests.rs @@ -597,3 +597,85 @@ fn the_pen_shows_its_ghost_anchor_on_the_segment_under_it() { assert_eq!(net(&s, id).vertices.len(), 5, "the press added the point"); assert_eq!(ve(&s).anchor, None, "the click ended the pen's path"); } + +/// A rectangle's corner cut off in the editor (a point added on each edge next to it, the corner +/// deleted with Shift+Delete so the two join) and the shape rounded: the fill, which the fill and +/// the selection outline draw, traces the stroke's outline, cut at both ends of the diagonal (#1951). +#[test] +fn a_rounded_chamfer_cut_in_the_editor_fills_along_its_arcs() { + for top_first in [true, false] { + let mut s = Session::new(); + let id = rect(&mut s); + // Splitting keeps the split edge's index, so the other edge's stays: top 0, right 1. + let (first, second) = if top_first { (0, 1) } else { (1, 0) }; + ex(&mut s, "vector.edit.addVertex", json!({"segment": first, "t": 0.5})); + ex(&mut s, "vector.edit.addVertex", json!({"segment": second, "t": 0.5})); + let corner = vertex_at(&net(&s, id), 100.0, 0.0); + ex(&mut s, "vector.edit.select", json!({"vertices": [corner]})); + ex(&mut s, "vector.deleteHeal", json!({})); + let n = net(&s, id); + assert_eq!((n.vertices.len(), n.segments.len(), n.regions.len()), (5, 5, 1), "top first {top_first}: a pentagon"); + ex(&mut s, "vector.edit.cornerRadius", json!({"radius": 43, "vertices": [0, 1, 2, 3, 4]})); + fill_traces_stroke(&s, id, &format!("top first {top_first}")); + // A region with a fill of its own is drawn through the region path and the planar normaliser. + if let NodeKind::Vector { network } = &mut s.doc_mut().unwrap().get_mut(id).unwrap().kind { + network.regions[0].fills = Some(vec![figcraft_color::Paint::solid(figcraft_color::Color::BLACK)]); + } + fill_traces_stroke(&s, id, &format!("top first {top_first}, region fill")); + } +} + +/// The chamfer made other ways: the corner deleted plainly, which opens the path between the two +/// new points, and the two connected again; or the pentagon drawn with the pen (#1951). +#[test] +fn a_rounded_chamfer_made_other_ways_fills_along_its_arcs() { + let mut s = Session::new(); + let id = rect(&mut s); + ex(&mut s, "vector.edit.addVertex", json!({"segment": 0, "t": 0.5})); + ex(&mut s, "vector.edit.addVertex", json!({"segment": 1, "t": 0.5})); + let corner = vertex_at(&net(&s, id), 100.0, 0.0); + ex(&mut s, "vector.edit.select", json!({"vertices": [corner]})); + ex(&mut s, "vector.edit.delete", json!({})); + let n = net(&s, id); + assert_eq!((n.segments.len(), n.regions[0].loops[0].len()), (4, 4), "the path opened: {:?}", n.regions); + let (top, right) = (vertex_at(&n, 50.0, 0.0), vertex_at(&n, 100.0, 50.0)); + ex(&mut s, "vector.edit.connect", json!({"a": top, "b": right})); + assert_eq!(net(&s, id).segments.len(), 5, "connected again"); + ex(&mut s, "vector.edit.cornerRadius", json!({"radius": 43, "vertices": [0, 1, 2, 3, 4]})); + fill_traces_stroke(&s, id, "deleted and connected"); + // Drawn with the pen: continue from the end of an open two-point path and close on its start. + let mut s = Session::new(); + let r = ex(&mut s, "vector.create", json!({"points": [[0, 0], [50, 0]], "closed": false})); + let id = crate::params::id_of(&r["id"]).unwrap(); + ex(&mut s, "vector.edit.begin", json!({"id": id})); + ex(&mut s, "vector.edit.tool", json!({"tool": "pen"})); + click(&mut s, 50.0, 0.0); + for (x, y) in [(100.0, 50.0), (100.0, 100.0), (0.0, 100.0), (0.0, 0.0)] { + click(&mut s, x, y); + } + let n = net(&s, id); + assert_eq!((n.vertices.len(), n.segments.len(), n.regions.len()), (5, 5, 1), "closed by the pen"); + ex(&mut s, "vector.edit.cornerRadius", json!({"radius": 43, "vertices": [0, 1, 2, 3, 4]})); + fill_traces_stroke(&s, id, "drawn with the pen"); +} + +/// The rounded chamfered rectangle `id` (five points on the origin's 100×100 box, the top-right +/// corner cut off between (50, 0) and (100, 50)): one region with every segment in its loop, and a +/// fill that keeps off every sharp point and traces the same outline as the stroke. +fn fill_traces_stroke(s: &Session, id: NodeId, why: &str) { + use figcraft_geom::BezPath; + use figcraft_geom::kurbo::{ParamCurveArclen, ParamCurveNearest}; + let n = net(s, id); + assert_eq!(n.regions.len(), 1, "{why}: one region, {:?}", n.regions); + assert_eq!(n.regions[0].loops[0].len(), n.segments.len(), "{why}: every segment in the loop, {:?}", n.regions[0].loops); + let doc = s.doc().unwrap(); + let (fill, _) = figcraft_render::node_outline(doc, doc.node(id).unwrap()).unwrap(); + let stroke = n.stroke_path(); + let keeps_off = |path: &BezPath, p: Point| path.segments().map(|s| s.nearest(p, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min); + let length = |path: &BezPath| path.segments().map(|s| s.arclen(1e-9)).sum::(); + for p in [pt(50.0, 0.0), pt(100.0, 50.0), pt(0.0, 0.0), pt(100.0, 100.0), pt(0.0, 100.0)] { + assert!(keeps_off(&stroke, p) > 2.0, "{why}: the stroke is cut at {p:?} ({:.2} from it)", keeps_off(&stroke, p)); + assert!(keeps_off(&fill, p) > 2.0, "{why}: the fill runs into {p:?} ({:.2} from it)", keeps_off(&fill, p)); + } + assert!((length(&fill) - length(&stroke)).abs() < 1e-3, "{why}: fill {} and stroke {} trace the same outline", length(&fill), length(&stroke)); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 75a426231..2093798ed 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%; last major: full re-measure against Figma desktop 126.10.7; rows for the community batches: Selection colors, smart-selection spacing and a Present tab (#753), `.fig` import fidelity, paste from another design app, a `.fig` copy from Save as; control requests while the window is minimised (#720); catalog counts re-measured; automation roots (#715); number variables in the text content picker (#629); frames and sections convert into each other (#719)) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** patch (joining the two ends of a path broken open by a deleted point closes it again, so its fill and selection outline follow the new segment and its corner radius instead of a straight line across the gap (#1951); bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%; last major: full re-measure against Figma desktop 126.10.7; rows for the community batches: Selection colors, smart-selection spacing and a Present tab (#753), `.fig` import fidelity, paste from another design app, a `.fig` copy from Save as; control requests while the window is minimised (#720); catalog counts re-measured; automation roots (#715); number variables in the text content picker (#629); frames and sections convert into each other (#719)) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is @@ -245,7 +245,8 @@ Hours in this narrative are the builders' estimates; the tables above supersede pen that extends, branches and closes paths (vector networks), paint bucket fill/unfill of any closed area (faces with holes), point/segment selection, handle mirroring (none/angle/angle and length) with a Point panel (position, corner radius, mirroring), smooth/sharp points, join and - merge, delete vs delete-and-heal, nudging, one undo step per gesture, eraser (⇧E), shape builder + merge (joining the two ends of a path broken open by a deleted point closes it again, so its + fill follows the new segment, #1951), delete vs delete-and-heal, nudging, one undo step per gesture, eraser (⇧E), shape builder (⇧M: the regions of overlapping shapes, click or drag to merge, Alt to remove, curves kept), variable width strokes (width profile presets with previews in the stroke settings, the Variable width tool ⇧W: drag the path to add a width point, slide points, drag their handles, Delete; @@ -648,6 +649,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-04 | patch | M8, #1951 (#1506 again): a path broken open by deleting a point (Delete, not Shift+Delete) is filled closed by a straight line across the gap, as an open path's fill is; joining its two ends again (the pen onto the other end, Connect, ⌘J) left the loop without the new segment, so once the points were rounded the fill and the selection outline ran straight across while the stroke followed the segment and its arcs. Joining now closes the loop through the new segment ("Click to close the path."; "You can use the Paint tool to add fills to any closed regions of a vector network."): `ops::connect` splices it into the loop whose segments are the chain between the ends. Evidence: `vectoredit::tests::a_rounded_chamfer_made_other_ways_fills_along_its_arcs` (fails on main: the loop kept 4 of 5 segments), `a_rounded_chamfer_cut_in_the_editor_fills_along_its_arcs` (Shift+Delete, with and without a region fill), `doc::tests::a_chamfered_rectangles_rounded_fill_is_cut_at_every_point` (fill, region path and stroke agree for every loop order and segment direction of a chamfered rectangle). | | 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 | From 4cd01f0a045965a885d064c7e2ef17713c6b0f0e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 4 Nov 2026 06:01:39 -0500 Subject: [PATCH 071/102] M4: a justify gap is reordered with the line's runs, so a nested embedding gets its gaps at its edges (#1970) Cause: `visual_gaps` mapped a gap at a run boundary to the gap before the later run's first item, which for a run nested inside another (a Chinese word in a Hebrew phrase in Chinese text, made with embedding marks) is a gap inside the embedding: one boundary took it, another got none, and the line came up a gap short of the box's edge. Fix: each gap is reordered with the line as a glyph of no width at the lower of its two neighbours' levels (rule N1 for a space between them), through the same `visual_order`: items and gaps keep alternating and each gap lands once at the boundary it belongs to. Test row with explicit embedding marks (red before: "char 8 moved 2 (want 1)"). Co-Authored-By: Claude Fable 5.1 --- crates/text/src/layout.rs | 69 +++++++++++++++------------------------ crates/text/src/tests.rs | 8 ++++- docs/target-app-parity.md | 4 +-- 3 files changed, 36 insertions(+), 45 deletions(-) diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 59e0d5877..e28682d74 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -297,48 +297,37 @@ pub(crate) fn is_rtl_char(c: char) -> bool { matches!(c as u32, 0x0590..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFF | 0x10800..=0x10FFF | 0x1E800..=0x1EFFF | 0x200F | 0x202B | 0x202E | 0x2067) } -/// Which visual positions of `order` (the logical index at each) a justify gap follows. A gap -/// after logical item k (`after[k]`) opens between logically neighbouring glyphs where they are, -/// or where two runs meet (a right-to-left run is laid out reversed) between the runs, so a gap -/// beside a Hebrew word in Chinese text opens beside the word, not inside it; each opens once. -/// From item `trailing` on (a line's trailing spaces) a gap opens after the item itself. -fn visual_gaps(order: &[usize], after: &[bool], trailing: usize) -> Vec { - let run_min = visual_run_starts(order); - let mut applied = vec![false; after.len()]; +/// Which visual positions of a line's items (in `visual_order(levels)`) a justify gap follows. The +/// gap after logical item k (`after[k]`) is reordered like a glyph of no width at the lower of its +/// two neighbours' levels, as rule N1 resolves a space between them: between logically neighbouring +/// glyphs it opens where they are, and where runs meet it opens beside the run it belongs to, so a +/// gap beside a Hebrew word in Chinese text opens beside the word, not inside it, and so does one +/// beside a Chinese word within that Hebrew. From item `trailing` on (a line's trailing spaces) a +/// gap opens after the item itself. +fn visual_gaps(levels: &[u8], after: &[bool], trailing: usize) -> Vec { let gap_after = |k: usize| after.get(k).copied().unwrap_or(false); - order - .iter() - .enumerate() - .map(|(i, &k)| { + let level = |k: usize| levels.get(k).copied().unwrap_or(0); + // Items at the even indices, the gap after item k at 2k + 1 (a gap's level never exceeds its + // neighbours', so every run reversed starts and ends on an item and the two keep alternating). + let mut both = Vec::with_capacity(after.len() * 2); + for k in 0..after.len() { + if k > 0 { + both.push(level(k).min(level(k - 1))); + } + both.push(level(k)); + } + let order = visual_order(&both); + (0..after.len()) + .map(|i| { + let k = order.get(2 * i).copied().unwrap_or(0) / 2; if k >= trailing { return gap_after(k); } - let at = match order.get(i + 1) { - Some(&n) if n == k + 1 || k == n + 1 => Some(k.min(n)), - Some(_) => run_min.get(i).copied().max(run_min.get(i + 1).copied()).and_then(|m| m.checked_sub(1)), - None => None, - }; - at.is_some_and(|g| gap_after(g) && applied.get_mut(g).is_some_and(|a| !std::mem::replace(a, true))) + order.get(2 * i + 1).is_some_and(|&g| g % 2 == 1 && g / 2 < trailing && gap_after(g / 2)) }) .collect() } -/// For each position of `order` (the logical index at each visual position), the smallest -/// logical index of its run: the visually consecutive glyphs whose logical indices step one way. -fn visual_run_starts(order: &[usize]) -> Vec { - let mut out = Vec::with_capacity(order.len()); - let mut start = 0; - for i in 1..=order.len() { - let joined = i < order.len() && order.get(i - 1).zip(order.get(i)).is_some_and(|(&p, &k)| p + 1 == k || k + 1 == p); - if !joined { - let m = order.get(start..i).and_then(|run| run.iter().copied().min()).unwrap_or(0); - out.extend(std::iter::repeat_n(m, i - start)); - start = i; - } - } - out -} - /// Visual order of a line's items from their levels (rule L2: from the highest level down to the /// lowest odd one, reverse every run at that level or above). pub(crate) fn visual_order(levels: &[u8]) -> Vec { @@ -1396,16 +1385,12 @@ pub fn layout(text: &TextData, box_width: Option, box_height: Option) // Right-to-left runs are placed in visual order; trailing spaces take the paragraph's // direction (rule L1). let line_items = items.get(*s..*e).unwrap_or(&[]); - let order: Vec = if bidi.is_some() { - let para_level = u8::from(rtl_line); - let levels: Vec = line_items.iter().enumerate().map(|(k, it)| if *s + k >= vis_end { para_level } else { it.level }).collect(); - visual_order(&levels) - } else { - (0..line_items.len()).collect() - }; + let para_level = u8::from(rtl_line); + let levels: Vec = line_items.iter().enumerate().map(|(k, it)| if *s + k >= vis_end { para_level } else { it.level }).collect(); + let order = visual_order(&levels); // Each gap opens at its visual boundary; trailing spaces widen where they are. let after: Vec = (0..line_items.len()).map(|k| widens(*s + k)).collect(); - let gaps_at = visual_gaps(&order, &after, vis_end - *s); + let gaps_at = visual_gaps(&levels, &after, vis_end - *s); for (i, &k) in order.iter().enumerate() { let Some(it) = line_items.get(k) else { continue }; if is_line_break(it.ch) { diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 8082ffed3..cbd1e9d4c 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -608,12 +608,18 @@ fn justified_ideographs_spread_the_room_between_characters() { }; // Box width cut inside char `fit`, so the first line is chars 0..fit; how many gaps lie before // each of its chars. - let rows: [(&str, usize, &[i32], &str); 5] = [ + let rows: [(&str, usize, &[i32], &str); 6] = [ ("一二三四五六七八九十", 6, &[0, 1, 2, 3, 4, 5], "one gap between each pair of ideographs"), ("一二三。四五六七八九", 6, &[0, 1, 2, 2, 3, 4], "none before the full stop, which never starts a line"), ("一二三「四五六七八九", 6, &[0, 1, 2, 3, 3, 4], "none after the opening bracket, which never ends a line"), ("一二三\u{20DD}四五六七八九", 6, &[0, 1, 2, 2, 3, 4], "none inside a grapheme cluster: a combining mark stays on its base"), ("漢אב字一二三", 4, &[0, 1, 1, 2], "beside a right-to-left word (laid out ב then א), not inside it"), + ( + "漢\u{202B}אב字一גד\u{202C}文一二三", + 10, + &[0, 1, 4, 4, 2, 3, 1, 1, 1, 5], + "beside a Chinese word embedded in a Hebrew phrase embedded in Chinese (laid out 漢 ד ג 字 一 ב א 文, the embedding marks of no width), and beside the phrase", + ), ]; for (s, fit, gaps_before, why) in rows { let natural = lay_out(s, TextAlignH::Left, None); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 572bb7ffa..c7cef88e1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -297,7 +297,7 @@ Hours in this narrative are the builders' estimates; the tables above supersede break inside Latin words, kinsoku to JIS X 4051 for closing and opening punctuation, small kana (halfwidth too), the prolonged sound mark, the iteration marks, the (semi-)voiced sound marks and the halfwidth parentheses); Thai, Lao, Khmer and Burmese lines break between words (ICU4X's word - dictionaries, its LSTM models in the browser), never after a leading vowel or before a mark; justified text widens each line's spaces but the last line's, and in Chinese, Japanese and Korean text, which has none, the gaps between its characters wherever a line could break (#1970); a style's metrics from its own font, not a fallback; a letter and + dictionaries, its LSTM models in the browser), never after a leading vowel or before a mark; justified text widens each line's spaces but the last line's, and in Chinese, Japanese and Korean text, which has none, the gaps between its characters wherever a line could break, a gap beside a right-to-left word opening beside the word (#1970); a style's metrics from its own font, not a fallback; a letter and its combining marks (Vietnamese typed decomposed, say) from one font that has them all; carets, Delete and Backspace by grapheme cluster; double-click and word moves by script run; IME composition with CJK; vertical trim (cap height to baseline). The tail suite (`crates/text/src/tail_tests.rs`, @@ -648,7 +648,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| -| 2026-11-04 | patch | M4, #1970: justified Chinese, Japanese and Korean text, written without spaces between words, aligns its right edge: the room on each line but a paragraph's last goes between its characters, each a word of its own as for line breaking ("Justify aligns the first word in each line of text to the left-most edge, and the last to the right-most edge"), wherever a line could break there, so none opens before a full stop or closing bracket, nor after an opening one. Latin text widens its spaces as before; mixed text widens both. `figcraft_text::breaks::justify_between`, beside `break_between`, says where. Evidence: `tests::justified_ideographs_spread_the_room_between_characters` (fails on main). | +| 2026-11-04 | patch | M4, #1970: justified Chinese, Japanese and Korean text, written without spaces between words, aligns its right edge: the room on each line but a paragraph's last goes between its characters, each a word of its own as for line breaking ("Justify aligns the first word in each line of text to the left-most edge, and the last to the right-most edge"), wherever a line could break there, so none opens before a full stop or closing bracket, nor after an opening one. Latin text widens its spaces as before; mixed text widens both. A gap is reordered with the line's runs as a space of no width would be, so one beside a Hebrew word in Chinese text, or beside a Chinese word within that Hebrew, opens beside the word, not inside it. `figcraft_text::breaks::justify_between`, beside `break_between`, says where. Evidence: `tests::justified_ideographs_spread_the_room_between_characters` (fails on main). | | 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 | From 9ff2105d9be63429d47fce215d7a083c959fc561 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 4 Nov 2026 06:03:00 -0500 Subject: [PATCH 072/102] M8: a reconnected loop keeps its direction, so a hole stays a hole whichever end was clicked first (#1951) Cause: `ops::connect` rebuilt the broken loop along the path from the second end to the first, so connecting the ends in the other order reversed the loop's walk; a hole wound against its outline then wound with it and the non-zero rule filled it. Fix: the new segment goes into the loop at its gap, in the loop's own order. Test: a ring whose hole loses a corner with Delete and is connected again, either end first (red before for one order). Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/canvas/vectoredit/ops.rs | 40 ++++++++++++++++++++-- docs/target-app-parity.md | 2 +- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/canvas/vectoredit/ops.rs b/crates/engine/src/canvas/vectoredit/ops.rs index 993e45066..9e7b9b372 100644 --- a/crates/engine/src/canvas/vectoredit/ops.rs +++ b/crates/engine/src/canvas/vectoredit/ops.rs @@ -661,10 +661,15 @@ pub fn connect(net: &mut VectorNetwork, a: usize, b: usize, ta: (f64, f64), tb: let filled = net.regions.iter().any(|r| r.loops.iter().flatten().any(|s| lp.contains(s))); if filled { // A loop broken open at these ends (a point of it deleted, say) closes through the new - // segment, so the fill follows it instead of a straight line across the gap (#1951). + // segment, so the fill follows it instead of a straight line across the gap (#1951). The + // segment goes in at the gap, in the loop's own order, so the loop keeps its direction: a + // hole wound against its outline stays a hole whichever end was clicked first. + let segs = &net.segments; + let shares = |x: usize, y: usize| segs.get(x).zip(segs.get(y)).is_some_and(|(p, q)| p.a == q.a || p.a == q.b || p.b == q.a || p.b == q.b); for l in net.regions.iter_mut().flat_map(|r| r.loops.iter_mut()) { if l.len() == lp.len() && l.iter().all(|s| lp.contains(s)) { - *l = std::iter::once(si).chain(lp.iter().copied()).collect(); + let gap = (1..l.len()).find(|&k| l.get(k - 1).zip(l.get(k)).is_some_and(|(&x, &y)| !shares(x, y))).unwrap_or(l.len()); + l.insert(gap, si); } } } else { @@ -1005,6 +1010,37 @@ mod tests { assert!(connect(&mut n, 1, 99, (0.0, 0.0), (0.0, 0.0)).is_none()); } + #[test] + fn connecting_the_ends_of_a_hole_keeps_its_winding() { + // A ring: the hole's loop walks the other way round from the outline's, so the non-zero + // rule leaves it empty. + let mut n = square(); + for (x, y) in [(25.0, 25.0), (75.0, 25.0), (75.0, 75.0), (25.0, 75.0)] { + n.vertices.push(Vertex::new(x, y)); + } + for (a, b) in [(4, 5), (5, 6), (6, 7), (7, 4)] { + n.segments.push(Segment::line(a, b)); + } + n.regions[0].loops.push(vec![7, 6, 5, 4]); + let (hole, ring, cut) = (Point::new(40.0, 60.0), Point::new(10.0, 50.0), Point::new(70.0, 30.0)); + assert!(!n.fill_contains(hole) && n.fill_contains(ring) && !n.fill_contains(cut), "a ring to start with"); + // Delete a corner of the hole (the path opens; its fill closes across the gap, so the cut-off + // corner is filled), then connect the two open ends again, either end first: the hole is a + // triangle, still empty. + let at = |m: &VectorNetwork, (x, y): (f64, f64)| m.vertices.iter().position(|v| v.x == x && v.y == y).unwrap(); + for (first, second) in [((25.0, 25.0), (75.0, 75.0)), ((75.0, 75.0), (25.0, 25.0))] { + let mut m = n.clone(); + delete_vertices(&mut m, &[5], false); + assert!(!m.fill_contains(hole) && m.fill_contains(cut), "opened: {:?}", m.regions); + let (a, b) = (at(&m, first), at(&m, second)); + connect(&mut m, a, b, (0.0, 0.0), (0.0, 0.0)).unwrap(); + let loops = &m.regions[0].loops; + assert_eq!((m.regions.len(), loops.len(), loops[1].len()), (1, 2, 3), "{first:?} first: {:?}", m.regions); + assert!(!m.fill_contains(hole), "{first:?} first: the hole is filled, {loops:?}"); + assert!(m.fill_contains(ring) && m.fill_contains(cut), "{first:?} first: the ring is filled"); + } + } + #[test] fn join_merges_overlapping_points_and_connects_ends() { let mut n = open_line(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2093798ed..63f77f30e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -649,7 +649,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| -| 2026-11-04 | patch | M8, #1951 (#1506 again): a path broken open by deleting a point (Delete, not Shift+Delete) is filled closed by a straight line across the gap, as an open path's fill is; joining its two ends again (the pen onto the other end, Connect, ⌘J) left the loop without the new segment, so once the points were rounded the fill and the selection outline ran straight across while the stroke followed the segment and its arcs. Joining now closes the loop through the new segment ("Click to close the path."; "You can use the Paint tool to add fills to any closed regions of a vector network."): `ops::connect` splices it into the loop whose segments are the chain between the ends. Evidence: `vectoredit::tests::a_rounded_chamfer_made_other_ways_fills_along_its_arcs` (fails on main: the loop kept 4 of 5 segments), `a_rounded_chamfer_cut_in_the_editor_fills_along_its_arcs` (Shift+Delete, with and without a region fill), `doc::tests::a_chamfered_rectangles_rounded_fill_is_cut_at_every_point` (fill, region path and stroke agree for every loop order and segment direction of a chamfered rectangle). | +| 2026-11-04 | patch | M8, #1951 (#1506 again): a path broken open by deleting a point (Delete, not Shift+Delete) is filled closed by a straight line across the gap, as an open path's fill is; joining its two ends again (the pen onto the other end, Connect, ⌘J) left the loop without the new segment, so once the points were rounded the fill and the selection outline ran straight across while the stroke followed the segment and its arcs. Joining now closes the loop through the new segment ("Click to close the path."; "You can use the Paint tool to add fills to any closed regions of a vector network."): `ops::connect` puts it into the loop whose segments are the chain between the ends, at the gap and in the loop's own order, so a hole keeps its winding whichever end was clicked first. Evidence: `vectoredit::tests::a_rounded_chamfer_made_other_ways_fills_along_its_arcs` (fails on main: the loop kept 4 of 5 segments), `a_rounded_chamfer_cut_in_the_editor_fills_along_its_arcs` (Shift+Delete, with and without a region fill), `doc::tests::a_chamfered_rectangles_rounded_fill_is_cut_at_every_point` (fill, region path and stroke agree for every loop order and segment direction of a chamfered rectangle). | | 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 | From cacf73a0940c56469b892c4c68e6c7807be443b5 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 4 Nov 2026 06:45:00 -0500 Subject: [PATCH 073/102] M8: a reconnected loop is closed only where the segment makes it one continuous chain (#1951) A loop whose segments are the chain between the two ends but are listed out of walking order has no place for the new segment that makes it continuous; inserting it at the first gap would leave the other gaps. Such a loop is left as it was (the walkers' bridging still draws it), as a loop broken in two places is. Test: the chain A-B-C-D-E with its loop listed out of order, joined A to E. Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/canvas/vectoredit/ops.rs | 23 ++++++++++++++++++++-- docs/target-app-parity.md | 2 +- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/canvas/vectoredit/ops.rs b/crates/engine/src/canvas/vectoredit/ops.rs index 9e7b9b372..32b8eef44 100644 --- a/crates/engine/src/canvas/vectoredit/ops.rs +++ b/crates/engine/src/canvas/vectoredit/ops.rs @@ -663,13 +663,20 @@ pub fn connect(net: &mut VectorNetwork, a: usize, b: usize, ta: (f64, f64), tb: // A loop broken open at these ends (a point of it deleted, say) closes through the new // segment, so the fill follows it instead of a straight line across the gap (#1951). The // segment goes in at the gap, in the loop's own order, so the loop keeps its direction: a - // hole wound against its outline stays a hole whichever end was clicked first. + // hole wound against its outline stays a hole whichever end was clicked first. Only a + // loop the segment makes one continuous chain is closed; one listed out of walking order + // is left as it was. let segs = &net.segments; let shares = |x: usize, y: usize| segs.get(x).zip(segs.get(y)).is_some_and(|(p, q)| p.a == q.a || p.a == q.b || p.b == q.a || p.b == q.b); for l in net.regions.iter_mut().flat_map(|r| r.loops.iter_mut()) { if l.len() == lp.len() && l.iter().all(|s| lp.contains(s)) { let gap = (1..l.len()).find(|&k| l.get(k - 1).zip(l.get(k)).is_some_and(|(&x, &y)| !shares(x, y))).unwrap_or(l.len()); - l.insert(gap, si); + let mut closed = l.clone(); + closed.insert(gap, si); + let n = closed.len(); + if (0..n).all(|k| closed.get(k).zip(closed.get((k + 1) % n)).is_some_and(|(&x, &y)| shares(x, y))) { + *l = closed; + } } } } else { @@ -1041,6 +1048,18 @@ mod tests { } } + #[test] + fn connecting_leaves_a_loop_out_of_walking_order_alone() { + // The open chain A-B-C-D-E with its loop listed out of walking order: no place for the new + // segment makes it one continuous chain, so the loop is left as it was, and no region is added. + let pts = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0), Point::new(-50.0, 50.0)]; + let mut n = VectorNetwork::from_points(&pts, false); + n.regions.push(Region { loops: vec![vec![0, 2, 1, 3]], winding: WindingRule::NonZero, fills: None, ..Default::default() }); + let s = connect(&mut n, 0, 4, (0.0, 0.0), (0.0, 0.0)).unwrap(); + assert_eq!(n.regions.len(), 1); + assert_eq!(n.regions[0].loops, vec![vec![0, 2, 1, 3]], "left as it was, without segment {s}"); + } + #[test] fn join_merges_overlapping_points_and_connects_ends() { let mut n = open_line(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 63f77f30e..2c0cfe224 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -649,7 +649,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| -| 2026-11-04 | patch | M8, #1951 (#1506 again): a path broken open by deleting a point (Delete, not Shift+Delete) is filled closed by a straight line across the gap, as an open path's fill is; joining its two ends again (the pen onto the other end, Connect, ⌘J) left the loop without the new segment, so once the points were rounded the fill and the selection outline ran straight across while the stroke followed the segment and its arcs. Joining now closes the loop through the new segment ("Click to close the path."; "You can use the Paint tool to add fills to any closed regions of a vector network."): `ops::connect` puts it into the loop whose segments are the chain between the ends, at the gap and in the loop's own order, so a hole keeps its winding whichever end was clicked first. Evidence: `vectoredit::tests::a_rounded_chamfer_made_other_ways_fills_along_its_arcs` (fails on main: the loop kept 4 of 5 segments), `a_rounded_chamfer_cut_in_the_editor_fills_along_its_arcs` (Shift+Delete, with and without a region fill), `doc::tests::a_chamfered_rectangles_rounded_fill_is_cut_at_every_point` (fill, region path and stroke agree for every loop order and segment direction of a chamfered rectangle). | +| 2026-11-04 | patch | M8, #1951 (#1506 again): a path broken open by deleting a point (Delete, not Shift+Delete) is filled closed by a straight line across the gap, as an open path's fill is; joining its two ends again (the pen onto the other end, Connect, ⌘J) left the loop without the new segment, so once the points were rounded the fill and the selection outline ran straight across while the stroke followed the segment and its arcs. Joining now closes the loop through the new segment ("Click to close the path."; "You can use the Paint tool to add fills to any closed regions of a vector network."): `ops::connect` puts it into the loop whose segments are the chain between the ends, at the gap and in the loop's own order, so a hole keeps its winding whichever end was clicked first; a loop listed out of walking order is left as it was. Evidence: `vectoredit::tests::a_rounded_chamfer_made_other_ways_fills_along_its_arcs` (fails on main: the loop kept 4 of 5 segments), `a_rounded_chamfer_cut_in_the_editor_fills_along_its_arcs` (Shift+Delete, with and without a region fill), `doc::tests::a_chamfered_rectangles_rounded_fill_is_cut_at_every_point` (fill, region path and stroke agree for every loop order and segment direction of a chamfered rectangle). | | 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 | From 23792e8503a750c1260afe7d2db1384d5e972470 Mon Sep 17 00:00:00 2001 From: Markus Reimr Date: Wed, 4 Nov 2026 14:32:29 +0100 Subject: [PATCH 074/102] M10: translate German text-wrap controls and tooltips --- ROADMAP.md | 4 +++- crates/ui-egui/locales/de.toml | 6 ++++++ docs/localization-parity.md | 3 ++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 410705919..7ceeeaf67 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (six German translations for the text-wrap control (M10): Auto, balanced and pretty wrapping; catalog remains a draft; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -132,6 +132,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). ## Progress log +- **2026-11-04** · M10: the text layer's Wrap style control and its Balance/Pretty options and three explanatory tooltips now have German translations. These six UI strings previously fell back to English. German stays a draft; no full native review claimed. Grade and estimates unchanged. - **2026-10-30**: M8, #1125: damaged `trak` size-table offsets are checked instead of wrapping on 32-bit targets, and an incomplete normal track is dropped entirely, never returned in part. Font indexing makes its existing bounds explicit, preserving later faces and sparse name-table reads. Synthetic regression tests in `fontdb_tests.rs`. Numbers unchanged. - **2026-10-30** · Text style dedupe is O(spans) (M8, #1102): `shape_text` deduped spans into styles by a scan over the styles already collected — O(spans × styles), so a styled text's dedupe grew with the square of its runs (a synthetic 50k-run text with 100 alternating styles spent 7.7 ms in it). Now the last two styles again (spans run in blocks), then buckets keyed by a cheap fingerprint (family and style bytes, size bits with −0.0 folded, the enums, fill count and solid colours), each bucket resolved with the full equality: the result is the scan's, never worse than it, and O(spans) when names and sizes differ (the same synthetic text: 2.6 ms). The font-db write lock is untouched: `find()` loads faces, which needs the write. `layout_dedupe_tests`. Numbers unchanged. - **2026-10-29** · M10: correct nine German labels in `de.toml`: gradient stops use Verlaufsstopp, OpenType ss01–ss05 use Stilsatz, and the Home-screen preference names the Startbildschirm consistently in the UI and Actions palette. This is a partial terminology pass; German remains a draft awaiting a full native-speaker review and maintainer approval. Numbers unchanged. @@ -357,6 +358,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | six German translations for the text-wrap control (M10): Auto, balanced and pretty wrapping; catalog remains a draft. Six previously missing UI entries added to `de.toml`; command labels and menu wordings unchanged. Full native review is still pending; grade and estimates 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 | diff --git a/crates/ui-egui/locales/de.toml b/crates/ui-egui/locales/de.toml index 344e70912..765203109 100644 --- a/crates/ui-egui/locales/de.toml +++ b/crates/ui-egui/locales/de.toml @@ -147,6 +147,7 @@ status = "draft — needs native review" "Auto layout" = "Auto-Layout" "Auto rows" = "Automatische Zeilen" "Auto width" = "Automatische Breite" +"Auto: as many words as fit on each line" = "Auto: Jede Zeile wird so weit wie möglich gefüllt" "Back to the FigCraft server" = "Zurück zum FigCraft-Server" "Back to the font's value" = "Zurück zum Wert der Schrift" "Back" = "Zurück" @@ -160,6 +161,8 @@ status = "draft — needs native review" "Back to the values the font style implies" = "Zurück zu den Werten des Schriftschnitts" "Background" = "Hintergrund" "Background blur" = "Hintergrundunschärfe" +"Balance" = "Ausgeglichen" +"Balance: every line close to the same length" = "Ausgeglichen: Alle Zeilen sind möglichst gleich lang" "Basics" = "Grundlagen" "Before" = "Vorher" "Bend" = "Biegen" @@ -1021,6 +1024,8 @@ status = "draft — needs native review" "Post" = "Senden" "Preferences" = "Einstellungen" "Preferred" = "Bevorzugt" +"Pretty" = "Optimiert" +"Pretty: full lines, no one word alone on the last" = "Optimiert: Volle Zeilen ohne einzelnes Wort in der letzten Zeile" "Present" = "Präsentieren" "Present or preview" = "Präsentieren oder Vorschau" "Present this flow" = "Diesen Ablauf präsentieren" @@ -1555,6 +1560,7 @@ status = "draft — needs native review" "With the layers' export settings" = "Mit den Exporteinstellungen der Ebenen" "Wrap" = "Umbrechen" "Wrap in new section" = "In neuen Abschnitt einschließen" +"Wrap style" = "Umbruchstil" "Yellow" = "Gelb" "Yesterday" = "Gestern" "You" = "Sie" diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 541e7ab90..6a831bffc 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (six German translations for the text-wrap control (M10): Auto, balanced and pretty wrapping; catalog remains a draft; Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7) FigCraft's interface has a localization layer with an English catalog, a Russian catalog reviewed by a native speaker, and Spanish (with a Latin American overlay), French, German, Brazilian @@ -125,6 +125,7 @@ Hindi and Arabic. Traditional Chinese is not planned (no catalog; its users see | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | six German translations for the text-wrap control (M10): Auto, balanced and pretty wrapping; catalog remains a draft. Six previously missing UI entries added to `de.toml`; command labels and menu wordings unchanged. Full native review is still pending; grade and estimates unchanged | | 2026-10-30 | minor | Bosnian (`bs`, Bosanski) draft catalog: every UI string (1,906), command label (629) and menu wording (31), machine-drafted in Latin script with ijekavian forms and marked as a draft awaiting native review. Bosnian plurals: one for 1, 21, 31… (not 11), few for 2–4, 22–24… (not 12–14), other for the rest. Grade and hours unchanged (Bosnian is not one of the twelve key languages) | | 2026-10-29 | minor | German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft. Nine existing translations corrected; keys, placeholders, coverage, grade and estimates unchanged | | 2026-10-28 | minor | Arabic draft: 1,857 UI entries, 620 command labels and 31 menu wordings, with count-neutral plurals. AI-assisted, native review pending. Desktop uses the existing Arabic fallback and bidi; web requires an embedded Arabic face. No panel mirroring or parity-grade increase claimed | From 05d1b147fd0c70424365e09ec00ba6d24fb82e41 Mon Sep 17 00:00:00 2001 From: Markus Reimr Date: Wed, 4 Nov 2026 16:17:10 +0100 Subject: [PATCH 075/102] M10: synchronize measured German localization coverage --- ROADMAP.md | 13 +++++++++---- docs/localization-parity.md | 15 ++++++++++++--- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 7ceeeaf67..6e29e428f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (six German translations for the text-wrap control (M10): Auto, balanced and pretty wrapping; catalog remains a draft; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (German coverage re-measured at 2,592 / 2,647 entries (97.9%, 2026-11-04); six German translations for the text-wrap control (M10): Auto, balanced and pretty wrapping; catalog remains a draft; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -97,7 +97,7 @@ native speakers' reviews of the nine language drafts need people. ## Languages -| Language | Code | Strings | Status | +| Language | Code | Catalog entries | Status | |---|---|---|---| | English | en | 100% | full | | Simplified Chinese | zh-Hans | 95% | draft (needs native review) | @@ -108,11 +108,14 @@ native speakers' reviews of the nine language drafts need people. | Portuguese (Brazil) | pt-BR | 95% | draft (needs native review) | | Indonesian | id | 99% | draft (needs native review) | | Japanese | ja | 99% | draft (needs native review) | -| German | de | 96% | draft (needs native review) | +| German | de | 2,592 / 2,647 entries (97.9%, measured 2026-11-04) | draft (needs native review) | | Korean | ko | 95% | draft (needs native review) | | Vietnamese | vi | 100% | draft (needs native review) | -Percentages measured 2026-10-17 over 2,272 entries (strings added since a draft show English). Also shipped: Russian (`ru`, 99%, reviewed by VanTan), Swedish (`sv`, 99.6%, command labels since 2026-10-17; native review welcome), Turkish (`tr`, 99%), Czech (`cs`, 99%, draft) and Bosnian (`bs`, 100% on 2026-10-30, draft). Figma ships English, Japanese, Korean, French, German, Spanish and Portuguese +German coverage was re-measured on 2026-11-04 with `cargo xtask i18n-report`: 1,969 / 1,975 UI keys, +594 / 641 command labels and 29 / 31 menu wordings, or 2,592 / 2,647 entries (97.9%). The count measures +catalog entries, not native-speaker approval; the method is in [localization parity](docs/localization-parity.md#languages). +The older percentages use the 2026-10-17 measurement over 2,272 entries (strings added since a draft show English); rows with a later date supersede it. Also shipped: Russian (`ru`, 99%, reviewed by VanTan), Swedish (`sv`, 99.6%, command labels since 2026-10-17; native review welcome), Turkish (`tr`, 99%), Czech (`cs`, 99%, draft) and Bosnian (`bs`, 100% on 2026-10-30, draft). Figma ships English, Japanese, Korean, French, German, Spanish and Portuguese (Brazil); FigCraft has the localization layer, English and Spanish (Spain and Latin America), French, German, Brazilian Portuguese, Japanese, Korean, Simplified Chinese, Indonesian, Vietnamese and Arabic drafts (Preferences ▸ Language; Traditional Chinese has no catalog; CJK UI @@ -132,6 +135,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). ## Progress log +- **2026-11-04** · M10: re-measure German catalog coverage with `cargo xtask i18n-report` and synchronize both language rows at 2,592 / 2,647 entries (97.9%). Record the current key counts and counting method; distinguish the older dated measurements. German remains a draft; grade and estimates unchanged. - **2026-11-04** · M10: the text layer's Wrap style control and its Balance/Pretty options and three explanatory tooltips now have German translations. These six UI strings previously fell back to English. German stays a draft; no full native review claimed. Grade and estimates unchanged. - **2026-10-30**: M8, #1125: damaged `trak` size-table offsets are checked instead of wrapping on 32-bit targets, and an incomplete normal track is dropped entirely, never returned in part. Font indexing makes its existing bounds explicit, preserving later faces and sparse name-table reads. Synthetic regression tests in `fontdb_tests.rs`. Numbers unchanged. - **2026-10-30** · Text style dedupe is O(spans) (M8, #1102): `shape_text` deduped spans into styles by a scan over the styles already collected — O(spans × styles), so a styled text's dedupe grew with the square of its runs (a synthetic 50k-run text with 100 alternating styles spent 7.7 ms in it). Now the last two styles again (spans run in blocks), then buckets keyed by a cheap fingerprint (family and style bytes, size bits with −0.0 folded, the enums, fill count and solid colours), each bucket resolved with the full equality: the result is the scan's, never worse than it, and O(spans) when names and sizes differ (the same synthetic text: 2.6 ms). The font-db write lock is untouched: `find()` loads faces, which needs the write. `layout_dedupe_tests`. Numbers unchanged. @@ -358,6 +362,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | German coverage re-measured with `cargo xtask i18n-report`: 1,969 / 1,975 UI keys, 594 / 641 command labels and 29 / 31 menu wordings; both language rows now show 2,592 / 2,647 (97.9%). Missing: 6 UI keys, 47 command labels, 2 menu wordings. Older measurements are dated; native review, grade and estimates unchanged | | 2026-11-04 | minor | six German translations for the text-wrap control (M10): Auto, balanced and pretty wrapping; catalog remains a draft. Six previously missing UI entries added to `de.toml`; command labels and menu wordings unchanged. Full native review is still pending; grade and estimates 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 | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 6a831bffc..e4b720639 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (six German translations for the text-wrap control (M10): Auto, balanced and pretty wrapping; catalog remains a draft; Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (German coverage re-measured at 2,592 / 2,647 entries (97.9%, 2026-11-04); six German translations for the text-wrap control (M10): Auto, balanced and pretty wrapping; catalog remains a draft; Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7) FigCraft's interface has a localization layer with an English catalog, a Russian catalog reviewed by a native speaker, and Spanish (with a Latin American overlay), French, German, Brazilian @@ -85,7 +85,7 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v ## Languages -| Language | Code | UI strings translated | Dialogs / tooltips / help | Script support | Native review | Status | Hours to full | +| Language | Code | Translated catalog entries | Dialogs / tooltips / help | Script support | Native review | Status | Hours to full | |---|---|---|---|---|---|---|---| | English | en | 2,352 / 2,352 (100%, source) | yes | Latin | yes (source) | full | 0 | | Simplified Chinese (Mandarin) | zh-Hans | 2,216 / 2,352 (94.2%, draft) | yes | CJK text and IME in documents; UI text in an installed Chinese face, ahead of Japanese ones (web: the `FIGCRAFT_EMBED_CJK` build); no Traditional Chinese catalog (zh-TW, zh-HK read English) | no | draft | 1–2 (after native review) | @@ -96,11 +96,19 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v | Portuguese | pt-BR | 2,331 / 2,352 (99.1%, draft) | yes | Latin | no | draft | 1–2 (after native review) | | Indonesian | id | 2,292 / 2,352 (97.4%, draft) | yes | Latin | no | draft | 1–2 (after native review) | | Japanese | ja | 2,304 / 2,352 (98.0%, draft) | yes | CJK text and IME in documents; UI text in an installed Japanese face (web: the `FIGCRAFT_EMBED_CJK` build) | no | draft | 1–2 (after native review) | -| German | de | 2,226 / 2,352 (94.6%, draft) | yes | Latin; long words elide in narrow fields | no | draft | 1–2 (after native review) | +| German | de | 2,592 / 2,647 entries (97.9%, measured 2026-11-04) | yes | Latin; long words elide in narrow fields | no | draft | 1–2 (after native review) | | Korean | ko | 2,216 / 2,352 (94.2%, draft) | yes | Hangul text and IME in documents; UI text in an installed Korean face (web: the `FIGCRAFT_EMBED_CJK` build) | no | draft | 1–2 (after native review) | | Vietnamese | vi | 2,352 / 2,352 (100%, draft) | yes | Latin with stacked diacritics | no | draft | 1–2 (after native review) | | Thai | th | 1,791 / 1,791 UI strings, 589 of 598 command labels, 31 menu wordings (draft) | yes | Thai text in documents; UI text (and layer and page names in Thai, whatever the UI language) in an installed Thai face, desktop only; the web build leaves Thai out | no | draft | 1–2 (after native review) | +German was re-measured on **2026-11-04** with `cargo xtask i18n-report`: **1,969 / 1,975 UI keys**, +**594 / 641 command labels** and **29 / 31 menu wordings**, totaling **2,592 / 2,647 entries (97.9%)**. +The report confirms 6 UI keys, 47 command labels and 2 menu wordings are missing. The denominator uses +the report's key sets: English UI keys, the union of registered command ids and main-menu ids, +and menu labels worded differently from their command. A plural entry counts as one key, and a +present translation counts even when its wording matches English. This is catalog coverage; +German remains a draft awaiting full native-speaker review. The other rows retain their dated measurements. + Other languages (measured 2026-10-22): Russian (`ru`) 2,352 / 2,352 (100%), reviewed and approved by VanTan, one/few/many integer plurals; Swedish (`sv`) 2,314 / 2,352 (98.4%), its command labels and menu wordings added 2026-10-17 (#599), native review welcome; Turkish (`tr`) 2,291 / 2,352 (97.4%), whose header @@ -125,6 +133,7 @@ Hindi and Arabic. Traditional Chinese is not planned (no catalog; its users see | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | German coverage re-measured with `cargo xtask i18n-report`: 1,969 / 1,975 UI keys, 594 / 641 command labels and 29 / 31 menu wordings; both language rows now show 2,592 / 2,647 (97.9%). Missing: 6 UI keys, 47 command labels, 2 menu wordings. Older measurements are dated; native review, grade and estimates unchanged | | 2026-11-04 | minor | six German translations for the text-wrap control (M10): Auto, balanced and pretty wrapping; catalog remains a draft. Six previously missing UI entries added to `de.toml`; command labels and menu wordings unchanged. Full native review is still pending; grade and estimates unchanged | | 2026-10-30 | minor | Bosnian (`bs`, Bosanski) draft catalog: every UI string (1,906), command label (629) and menu wording (31), machine-drafted in Latin script with ijekavian forms and marked as a draft awaiting native review. Bosnian plurals: one for 1, 21, 31… (not 11), few for 2–4, 22–24… (not 12–14), other for the rest. Grade and hours unchanged (Bosnian is not one of the twelve key languages) | | 2026-10-29 | minor | German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft. Nine existing translations corrected; keys, placeholders, coverage, grade and estimates unchanged | From bae4a4e81d4e6e2ad2697e3e5356f4070e499ec3 Mon Sep 17 00:00:00 2001 From: Janiz-zzz <267742026+Janiz-zzz@users.noreply.github.com> Date: Tue, 3 Nov 2026 20:19:55 +0200 Subject: [PATCH 076/102] i18n(fi): translate the 43 labels Finnish lacks Text wrap style, auto layout resize shortcuts, Hide UI and Minimize the interface, interface size commands, library analytics periods and counts, Replace image, Extend collection and upload from computer. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/fi.toml | 43 ++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/crates/ui-egui/locales/fi.toml b/crates/ui-egui/locales/fi.toml index 0c74f9de7..1c21c2260 100644 --- a/crates/ui-egui/locales/fi.toml +++ b/crates/ui-egui/locales/fi.toml @@ -1952,6 +1952,39 @@ status = "draft — needs native review" "⌘ click" = "⌘ click" "⌘ scroll" = "⌘ scroll" "⌥ drag" = "⌥ drag" +"1 year" = "1 vuosi" +"30 days" = "30 päivää" +"90 days" = "90 päivää" +"Wrap style" = "Rivitystyyli" +"Balance" = "Tasattu" +"Pretty" = "Siisti" +"Auto: as many words as fit on each line" = "Automaattinen: jokaiselle riville niin monta sanaa kuin mahtuu" +"Balance: every line close to the same length" = "Tasattu: kaikki rivit lähes samanpituisia" +"Pretty: full lines, no one word alone on the last" = "Siisti: täydet rivit, viimeiselle riville ei jää yksittäistä sanaa" +"Set hug contents" = "Aseta Sovita sisältöön" +"Set fill container" = "Aseta Täytä säilö" +"Double-click an edge of an auto layout frame" = "Kaksoisnapsauta automaattisen asettelun kehyksen reunaa" +"⌥ double-click an edge of an auto layout child" = "⌥-kaksoisnapsauta automaattisen asettelun alikohteen reunaa" +"Alt+double-click an edge of an auto layout child" = "Alt+kaksoisnapsauta automaattisen asettelun alikohteen reunaa" +"Drop to use this image" = "Käytä tätä kuvaa pudottamalla" +"Expand the interface" = "Laajenna käyttöliittymä" +"Hide UI" = "Piilota käyttöliittymä" +"Past 30 days" = "Viimeiset 30 päivää" +"Past 90 days" = "Viimeiset 90 päivää" +"Past year" = "Viimeinen vuosi" +"Nothing counted yet" = "Mitään ei ole vielä laskettu" +"Rotate a degree (Shift: 15)" = "Kierrä asteen verran (Shift: 15)" +"⌥⌘ ← ↑ → ↓" = "⌥⌘ ← ↑ → ↓" +"Ctrl+Alt+← ↑ → ↓" = "Ctrl+Alt+← ↑ → ↓" +"Remove all auto layout" = "Poista kaikki automaattinen asettelu" +"This server doesn't count insertions" = "Tämä palvelin ei laske lisäyksiä" +"This server doesn't count styles and variables" = "Tämä palvelin ei laske tyylejä ja muuttujia" +"Upload from computer" = "Lataa tietokoneelta" +"The bars are hidden. {shortcut} shows them again" = "Palkit on piilotettu. {shortcut} näyttää ne uudelleen" +"{insertions} · {detachments}" = "{insertions} · {detachments}" +"{n} inserted" = { one = "{n} lisätty", other = "{n} lisätty" } +"{period}: {counts}" = "{period}: {counts}" +"{used} · {inserted}" = "{used} · {inserted}" [commands] "align.bottom" = "Tasaa alas" @@ -2585,6 +2618,16 @@ status = "draft — needs native review" "vector.fillRule" = "Aseta täyttösääntö" "vector.reverseLoop" = "Käännä silmukka" "widget.hover" = "Pienoisohjelman kohdistus" +"board.reshape" = "Muotoile yhdistin uudelleen" +"image.replace" = "Korvaa kuva" +"layout.removeAll" = "Poista kaikki automaattinen asettelu" +"pref.uiScaleDown" = "Pienempi käyttöliittymä" +"pref.uiScaleReset" = "Käyttöliittymän oletuskoko" +"pref.uiScaleUp" = "Suurempi käyttöliittymä" +"text.openLink" = "Avaa linkki" +"text.wrapStyle" = "Rivitystyyli" +"variable.extendCollection" = "Laajenna kokoelma" +"view.minimize" = "Pienennä käyttöliittymä" [menu] "bool.exclude" = "Jätä pois" From ff862dcf7ae54f084a5ad48b0c17072970b6e492 Mon Sep 17 00:00:00 2001 From: fluid-chey Date: Wed, 4 Nov 2026 11:38:48 -0700 Subject: [PATCH 077/102] M7: a click on a page opens it after a rename that changed nothing The pages list ignored whether the rename field was still open, so a rename cancelled with Escape or committed unchanged stayed set. Its idle field sat over the row's name, caught the next click and started editing, and the page didn't open. The row now ends the rename when the field lets go, as layer rows do. Rename page from the row's menu now takes the keyboard, as a double click does: it had relied on the idle field. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/layers_behaviour_tests.rs | 75 ++++++++++++++++++++ crates/ui-egui/src/panels/layers.rs | 8 ++- 2 files changed, 82 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/layers_behaviour_tests.rs b/crates/ui-egui/src/layers_behaviour_tests.rs index 7cf0bf235..16d8be95d 100644 --- a/crates/ui-egui/src/layers_behaviour_tests.rs +++ b/crates/ui-egui/src/layers_behaviour_tests.rs @@ -411,6 +411,81 @@ fn double_clicking_a_page_renames_it_with_the_focus_in_the_screen_reader_tree() assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); } +/// A press of `key` in the frame that's next, then a few frames to settle. +fn press_page_field_key(u: &mut Ui, key: egui::Key) { + u.frame(vec![Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]); + for _ in 0..5 { + u.frame(vec![]); + } +} + +/// Asserts a click on the name of page `page`, away from page `other`, opens it and starts no +/// rename: the pages list is back to plain rows however the last rename ended. +fn assert_clicking_page_opens_it(u: &mut Ui, page: NodeId, other: NodeId, row: Pos2) { + assert!(u.app.ui.rename_page.is_none(), "the rename is over"); + u.app.session.execute("page.select", &json!({"id": other})).unwrap(); + for _ in 0..30 { + u.frame(vec![Event::PointerMoved(row)]); + } + u.button(row, true); + u.button(row, false); + for _ in 0..5 { + u.frame(vec![]); + } + assert_eq!(u.app.session.page().unwrap(), page, "the click opens the page"); + assert!(!u.ctx.memory(|m| m.has_focus(Id::unique(("pagename", page)).with("te"))), "and doesn't edit its name"); +} + +/// Asserts a page's row is a plain row after a rename that was cancelled, committed unchanged or +/// committed with a new name: a click on its name opens the page rather than editing the name. +#[test] +fn a_finished_page_rename_leaves_a_row_that_a_click_opens() { + for (key, text) in [(egui::Key::Escape, None), (egui::Key::Enter, None), (egui::Key::Enter, Some("Renamed"))] { + let mut s = Session::new(); + let p1 = s.page().unwrap(); + let p2 = id(s.execute("page.add", &json!({})).unwrap()); + let mut u = Ui::new(s); + let r2 = page_row(&mut u, p2, p1); + u.ctx.enable_accesskit(); + double_click_checking_focus(&mut u, r2); + assert_eq!(u.app.ui.rename_page.as_ref().map(|r| r.0), Some(p2), "a double click renames the page"); + if let Some(text) = text { + u.frame(vec![Event::Text(text.into())]); + } + press_page_field_key(&mut u, key); + assert_clicking_page_opens_it(&mut u, p2, p1, r2); + } +} + +/// Asserts the row's Rename page puts the keyboard in the name, and a name typed there is kept. +#[test] +fn the_page_menus_rename_starts_with_the_keyboard_in_the_name() { + let mut s = Session::new(); + let p1 = s.page().unwrap(); + let p2 = id(s.execute("page.add", &json!({})).unwrap()); + let mut u = Ui::new(s); + let r2 = page_row(&mut u, p2, p1); + u.frame(vec![ + Event::PointerMoved(r2), + Event::PointerButton { pos: r2, button: egui::PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }, + ]); + u.frame(vec![Event::PointerButton { pos: r2, button: egui::PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }]); + let shapes: Vec = u.frame_output(vec![]).shapes.into_iter().map(|c| c.shape).collect(); + let item = crate::live_tests::text_center(&shapes, "Rename page"); + u.frame(vec![Event::PointerMoved(item)]); + u.button(item, true); + u.button(item, false); + for _ in 0..3 { + u.frame(vec![]); + } + assert_eq!(u.app.ui.rename_page.as_ref().map(|r| r.0), Some(p2), "the menu renames the page"); + assert!(u.ctx.memory(|m| m.has_focus(Id::unique(("pagename", p2)).with("te"))), "with the keyboard in its name"); + u.frame(vec![Event::Text("Renamed".into())]); + press_page_field_key(&mut u, egui::Key::Enter); + assert_eq!(u.app.session.doc().unwrap().node(p2).map(|n| n.name.clone()).as_deref(), Some("Renamed")); + assert_clicking_page_opens_it(&mut u, p2, p1, r2); +} + /// The y of the line between the pages and the layers, above the layers' row at `layer` (found by /// the resize cursor it shows when hovered). fn pages_edge_at(u: &mut Ui, layer: f32) -> f32 { diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 164ec7e4a..7a642a09d 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -293,8 +293,13 @@ fn pages(app: &mut FigApp, ui: &mut Ui) { let tr = Rect::from_min_max(pos2(r.min.x + 8.0, r.min.y + 4.0), pos2(r.max.x - 4.0, r.max.y - 4.0)); let start = ui.data_mut(|d| d.remove_temp::(page_rename_start_id())).unwrap_or(false); let font = if id == cur { semibold(11.0) } else { regular(11.0) }; - if let (Some(new), _) = crate::widgets::rename_field(ui, Id::unique(("pagename", id)), &name, tr, font, start) { + let (out, open) = crate::widgets::rename_field(ui, Id::unique(("pagename", id)), &name, tr, font, start); + if let Some(new) = out { rename_done = Some((id, new)); + } else if !open { + // Cancelled, or committed unchanged: the row goes back to its name, or the idle + // field would catch the next click and a click wouldn't open this page. + app.ui.rename_page = None; } } else if !divider { let font = if id == cur { semibold(11.0) } else { regular(11.0) }; @@ -315,6 +320,7 @@ fn pages(app: &mut FigApp, ui: &mut Ui) { if ui.button(tr("Rename page")).clicked() { if !crate::menus::dev_mode_refuses(app, "page.rename") { app.ui.rename_page = Some((id, name.clone())); + ui.data_mut(|d| d.insert_temp(page_rename_start_id(), true)); } ui.close(); } From cd77b017bde826d201c4d0f25cd8d2f7c28dd647 Mon Sep 17 00:00:00 2001 From: Andreas Haraminac Date: Wed, 4 Nov 2026 19:06:37 +0000 Subject: [PATCH 078/102] M6: correct architecture guide for existing .fig support --- docs/architecture.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 5c7300f82..18d7ac550 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # FigCraft architecture -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** minor (the `vectordrawable` crate, L4: Android Vector Drawable export; earlier: the shared hub in `collab-net` and the `figcraft-server` app) · **Target:** Figma Design +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (corrected the file I/O overview to include the existing best-effort `.fig` import and experimental export; earlier: the `vectordrawable` crate, L4: Android Vector Drawable export; the shared hub in `collab-net` and the `figcraft-server` app) · **Target:** Figma Design How FigCraft is built today. Engine first, a thin swappable UI, everything a command; a Figma-shaped data model (a scene graph of frames with auto layout, components and variables). ~108,800 lines of @@ -23,7 +23,7 @@ replaced. | L2 | `figcraft-plugin` | ~1.0k | Plugin manifest and the WebAssembly sandbox (wasmi, metered, memory cap, no file system, network or clock) | | L2 | `figcraft-pathops` | ~1.1k | Booleans (linesweeper), outline stroke with alignment, arrowheads | | L3 | `figcraft-render` | ~5.4k | Scene → pixels on tiny-skia (CPU): isolated layers for opacity/blend/effects, clips, masks, shadows, blurs (uniform, progressive, background), noise, texture, glass, text; banded in parallel; retained rendering of only what changed; levels of detail when zoomed out | -| L3 | `figcraft-format` | ~5.2k | Native `.figcraft` (zip of `document.json` + images; streamed JSON), local library files, versions, REST API file JSON import (`rest/`) | +| L3 | `figcraft-format` | ~5.2k | Native `.figcraft` (zip of `document.json` + images; streamed JSON), local library files, versions, REST API file JSON import (`rest/`), best-effort `.fig` import and experimental export (`fig` module) | | L4 | `figcraft-svg` | ~3.7k | SVG export and import (usvg) | | L4 | `figcraft-pdf` | ~2.3k | PDF export (krilla) with print options | | L4 | `figcraft-vectordrawable` | ~1.2k | Android Vector Drawable (XML) export: baked path data, gradients through `aapt:attr`, clip groups, compatibility modes and warnings | @@ -67,9 +67,11 @@ express an effect. `.figcraft` is the native format (atomic saves, autosave checkpoints; the desktop app keeps recovery copies of unsaved documents that reopen after a crash or a forced quit). Imports: REST API -file JSON with variables and images, SVG, raster images, clipboard -content. Exports: PNG, JPG, WebP, SVG, PDF, code. There is no `.fig` reader yet -([`file-format-parity.md`](file-format-parity.md)). +file JSON with variables and images, SVG, raster images, clipboard content and `.fig` files (best +effort). Exports: PNG, JPG, WebP, SVG, PDF, code and `.fig` (experimental). The `.fig` +[reader](../crates/format/src/fig.rs) and [writer](../crates/format/src/fig/export.rs) belong to +`figcraft-format`; fidelity limits and validation are documented in +[`file-format-parity.md`](file-format-parity.md). ## Robustness @@ -83,6 +85,7 @@ input. | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Corrected the file I/O overview and format-crate row: best-effort `.fig` import and experimental export already exist in `figcraft-format`. No capability or readiness change. | | 2026-10-18 | minor | Added `vectordrawable` (L4), the Android Vector Drawable (XML) writer | | 2026-10-11 | minor | `collab-net` hosts through one hub for the app's sessions and the standalone server; added the `figcraft-server` app | | 2026-10-10 | minor | Merged main after #101–#103: WASM plugins (plugins area 0% → 35% breadth, 20% ready; ecosystem 5% → 20%) and the multiplayer core without networking (multiplayer 5% → 15% breadth, 5% ready; collaboration 8% → 12%); menu breadth 97.5% → 98.5% (200/203); ready for real work ~46% → ~47%; full parity 420–790 h → 390–745 h; beta 210–380 h → 200–365 h. Fixed the stated weight sums (areas 1–16 sum to 94, total 113; percentages were already computed with those) | From f566f9611d4540a237a8efc98d93f850a56c7c8f Mon Sep 17 00:00:00 2001 From: fluid-chey Date: Wed, 4 Nov 2026 12:54:06 -0700 Subject: [PATCH 079/102] M9: a slow join in a busy room isn't dropped for other people's cursors A client taking in a large welcome holds one queue slot for the whole transfer, while everyone's presence fills the rest. Five people moving their cursors fill 1024 slots in about 7 s, and the joiner is dropped with the same result on every try. Presence now stays out of a queue that is half full: it is latest-wins, and the other half stays free for edits, which can't be left out. Co-Authored-By: Claude Opus 5.5 --- crates/collab-net/src/hub.rs | 3 ++ crates/collab-net/src/hub/barred_tests.rs | 2 ++ crates/collab-net/src/hub/conn.rs | 2 ++ crates/collab-net/src/hub/queue.rs | 18 +++++++++- crates/collab-net/src/hub/queue_tests.rs | 40 +++++++++++++++++++++-- 5 files changed, 62 insertions(+), 3 deletions(-) diff --git a/crates/collab-net/src/hub.rs b/crates/collab-net/src/hub.rs index b79eb1652..6fadf0946 100644 --- a/crates/collab-net/src/hub.rs +++ b/crates/collab-net/src/hub.rs @@ -737,6 +737,9 @@ impl Hub { continue; } let Some(&conn) = room.ids.get(&id) else { continue }; + if matches!(msg, ServerMsg::Presence { .. }) && self.conns.get(&conn).is_some_and(|c| !c.out.takes_presence()) { + continue; + } let Some(b) = bytes.get_or_insert_with(|| encode(&msg)).clone() else { continue }; if !deliver(&self.conns, conn, &b, &mut held, &mut stuck) { stuck.push(conn); diff --git a/crates/collab-net/src/hub/barred_tests.rs b/crates/collab-net/src/hub/barred_tests.rs index a88caf633..eeb293231 100644 --- a/crates/collab-net/src/hub/barred_tests.rs +++ b/crates/collab-net/src/hub/barred_tests.rs @@ -74,6 +74,8 @@ fn a_kicked_connection_with_a_full_queue_is_shut() { let out = Line { tx, queued: Arc::default(), + waiting: Arc::default(), + max_presence: 32, block: Arc::new(AtomicUsize::new(0)), all: Arc::new(AtomicUsize::new(0)), max: 1 << 20, diff --git a/crates/collab-net/src/hub/conn.rs b/crates/collab-net/src/hub/conn.rs index 1f365cbab..08b9c355e 100644 --- a/crates/collab-net/src/hub/conn.rs +++ b/crates/collab-net/src/hub/conn.rs @@ -235,6 +235,8 @@ fn serve(mut stream: TcpStream, conn: u64, hub: &Sender, limits: NetLimit let out = Line { tx, queued: Arc::default(), + waiting: Arc::default(), + max_presence: limits.queue.max(4) / 2, block: block.queued.clone(), all: shared.queued.clone(), max: limits.max_queued_bytes, diff --git a/crates/collab-net/src/hub/queue.rs b/crates/collab-net/src/hub/queue.rs index 1c6a5dfcf..3559b0f10 100644 --- a/crates/collab-net/src/hub/queue.rs +++ b/crates/collab-net/src/hub/queue.rs @@ -48,6 +48,7 @@ pub(crate) struct Charges { pub(super) struct Charge { n: usize, mine: Arc, + waiting: Arc, _all: Arc, _block: Option>, } @@ -55,6 +56,7 @@ pub(super) struct Charge { impl Drop for Charge { fn drop(&mut self) { self.mine.fetch_sub(self.n, Ordering::Relaxed); + self.waiting.fetch_sub(1, Ordering::Relaxed); } } @@ -76,6 +78,10 @@ pub(crate) enum Push { pub(crate) struct Line { pub(crate) tx: SyncSender, pub(crate) queued: Arc, + /// Messages waiting in the queue. + pub(crate) waiting: Arc, + /// With this many waiting, presence is left out (see [`Line::takes_presence`]). + pub(crate) max_presence: usize, pub(crate) block: Arc, pub(crate) all: Arc, pub(crate) max: usize, @@ -84,6 +90,15 @@ pub(crate) struct Line { } impl Line { + /// Whether presence goes in the queue now. A client still taking in a long message (the welcome + /// of a large file on a slow link) would otherwise have its queue filled by everyone's cursors + /// and be dropped, again on every try. Presence is latest-wins, so what's left out is made up + /// for by the next update, and this keeps room for what can't be: other people's edits. A client + /// that reads nothing at all still ends at the write timeout. + pub(crate) fn takes_presence(&self) -> bool { + self.waiting.load(Ordering::Relaxed) < self.max_presence + } + /// Queue `b`. One message always fits an empty queue (a welcome as large as the largest file /// gets out). `charges` is what the message counts against, shared by its recipients; /// `over_budget` lets it past the server's budget (the hub just dropped the biggest consumer @@ -118,7 +133,8 @@ impl Line { } }; self.queued.fetch_add(n, Ordering::Relaxed); - let charge = Charge { n, mine: self.queued.clone(), _all: all, _block: block }; + self.waiting.fetch_add(1, Ordering::Relaxed); + let charge = Charge { n, mine: self.queued.clone(), waiting: self.waiting.clone(), _all: all, _block: block }; self.tx.try_send(Out::Bytes(b.clone(), Some(charge))).map_err(|e| match e { TrySendError::Full(_) => Push::Full, TrySendError::Disconnected(_) => Push::Gone, diff --git a/crates/collab-net/src/hub/queue_tests.rs b/crates/collab-net/src/hub/queue_tests.rs index 13879bd1e..57447cc4a 100644 --- a/crates/collab-net/src/hub/queue_tests.rs +++ b/crates/collab-net/src/hub/queue_tests.rs @@ -1,7 +1,8 @@ //! The hub's send queues (no writers: nothing is ever sent, so what is queued stays queued): a //! broadcast counts once against the server's budget however many copies are queued, a block of //! addresses can't take more than its share, and when the server's budget is used up the -//! connection holding the most is shed, not the next client that needs a little. +//! connection holding the most is shed, not the next client that needs a little. Presence stays out +//! of a busy queue. use std::collections::HashMap; use std::net::{IpAddr, TcpListener, TcpStream}; @@ -16,7 +17,20 @@ use super::{BlockUse, Blocks, Charges, Conn, Kind, Line, Out, Push, deliver}; /// A line with its own queue counter, the given block counter and the server's. fn line(block: &Arc, all: &Arc, max_block: usize, max_all: usize) -> (Line, Receiver) { let (tx, rx) = sync_channel(64); - (Line { tx, queued: Arc::default(), block: block.clone(), all: all.clone(), max: 1 << 20, max_block, max_all }, rx) + ( + Line { + tx, + queued: Arc::default(), + waiting: Arc::default(), + max_presence: 32, + block: block.clone(), + all: all.clone(), + max: 1 << 20, + max_block, + max_all, + }, + rx, + ) } fn socket() -> TcpStream { @@ -120,3 +134,25 @@ fn blocks_nobody_uses_are_forgotten() { let _c = blocks.get("203.0.113.3".parse().unwrap()); assert_eq!(blocks.len(), 2, "203.0.113.1 went"); } + +#[test] +fn a_busy_queue_leaves_presence_out_and_keeps_room_for_edits() { + let (l, rx) = line(&Arc::default(), &Arc::default(), usize::MAX, usize::MAX); + let msg = Bytes::from_static(b"x"); + for _ in 0..32 { + assert!(l.takes_presence()); + l.push(&msg, &mut Charges::default(), false).unwrap(); + } + assert!(!l.takes_presence(), "half full"); + // Edits still fit in the half kept for them. + for _ in 0..32 { + l.push(&msg, &mut Charges::default(), false).unwrap(); + } + assert_eq!(l.push(&msg, &mut Charges::default(), false), Err(Push::Full), "a client that takes in nothing still ends"); + // It catches up: presence goes in again. + for _ in 0..33 { + drop(rx.recv().unwrap()); + } + assert!(l.takes_presence()); + assert_eq!(l.waiting.load(Ordering::Relaxed), 31); +} From f35af507ec1a7284cfd042ee2378de2bff8e9932 Mon Sep 17 00:00:00 2001 From: ashokram-si <347905169+ashokram-si@users.noreply.github.com> Date: Thu, 5 Nov 2026 13:04:17 +0530 Subject: [PATCH 080/102] M1, #1758: mouse buttons 4 and 5 pan the canvas like the middle button --- contributors/people.toml | 3 +++ crates/ui-egui/src/canvas/input.rs | 14 +++++++++--- crates/ui-egui/tests/it/canvas_pan_release.rs | 22 ++++++++++++++++--- docs/ui-parity.md | 5 +++-- 4 files changed, 36 insertions(+), 8 deletions(-) diff --git a/contributors/people.toml b/contributors/people.toml index c846d8725..56bbfe00c 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -101,3 +101,6 @@ sync_github_name = true [people.aleksei-suholita] real_name = "Oleksii Sukholita" + +[people.ashokram-si] +real_name = "Ashok Ram" diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 5aa054163..f252ac49b 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -25,6 +25,14 @@ impl HoverKey { } } +/// Whether a button that pans the canvas is held: the middle button, or a mouse's side buttons +/// (4 and 5), which the incumbent treats the same way (#1758). Space + primary pans too, handled +/// with the Space key. +fn pan_button_down(i: &egui::InputState) -> bool { + use egui::PointerButton::{Extra1, Extra2, Middle}; + [Middle, Extra1, Extra2].into_iter().any(|b| i.pointer.button_down(b)) +} + /// The pointer left the canvas (or something over it took the pointer): nothing is hovered there. fn left(app: &mut FigApp) { app.canvas.last_hover = None; @@ -180,7 +188,7 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo left(app); } // A pan whose button was released off the canvas is over. - if !ctx.input(|i| i.pointer.button_down(egui::PointerButton::Middle) || i.pointer.primary_down()) { + if !ctx.input(|i| pan_button_down(i) || i.pointer.primary_down()) { app.canvas.middle_pan = None; } return true; @@ -211,8 +219,8 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo if zoom_tool(app, ui, resp, pos, mods, editing_text || typing_elsewhere) { return true; } - // Middle-button / space panning. - let middle_down = ctx.input(|i| i.pointer.button_down(egui::PointerButton::Middle)); + // Middle-button (or side-button) / space panning. + let middle_down = ctx.input(pan_button_down); if (middle_down || (app.canvas.space_pan && ctx.input(|i| i.pointer.primary_down()))) && resp.hovered() || app.canvas.middle_pan.is_some() { if let Ok(ds) = app.session.ds_mut() { match app.canvas.middle_pan { diff --git a/crates/ui-egui/tests/it/canvas_pan_release.rs b/crates/ui-egui/tests/it/canvas_pan_release.rs index cd1a6e1cc..07b0643b8 100644 --- a/crates/ui-egui/tests/it/canvas_pan_release.rs +++ b/crates/ui-egui/tests/it/canvas_pan_release.rs @@ -1,5 +1,6 @@ -//! A canvas pan (middle button or Space + primary) ends when its button is released, even when the -//! release happens over a panel: returning to the canvas with no button held must not move the view. +//! A canvas pan (middle button, a side button, or Space + primary) ends when its button is +//! released, even when the release happens over a panel: returning to the canvas with no button held +//! must not move the view. use egui::{Event, Key, PointerButton, Pos2, RawInput, Rect, vec2}; use figcraft_engine::Session; @@ -45,6 +46,12 @@ fn space(pressed: bool) -> Event { } fn check(space_pan: bool, outside: bool) { + check_button(if space_pan { PointerButton::Primary } else { PointerButton::Middle }, space_pan, outside); +} + +/// A pan with button `b` (with Space held when `space_pan`) moves the view, ends when `b` is +/// released (`outside` the canvas or over it), and a new one moves it again. +fn check_button(b: PointerButton, space_pan: bool, outside: bool) { let mut u = Frames::new(); let rect = u.app.canvas.rect; let start = Pos2::new(rect.min.x + 200.0, rect.center().y); @@ -55,7 +62,6 @@ fn check(space_pan: bool, outside: bool) { if space_pan { u.frame(vec![space(true)]); } - let b = if space_pan { PointerButton::Primary } else { PointerButton::Middle }; let before = u.cx(); u.frame(vec![button(start, b, true)]); u.frame(vec![Event::PointerMoved(dragged)]); @@ -93,3 +99,13 @@ fn space_pan_released_over_panel_does_not_move_view_on_return() { fn middle_pan_released_inside_canvas_keeps_view() { check(false, false); } + +/// #1758: a mouse's side buttons (4 and 5) pan the canvas as the middle button does, and the pan +/// ends on release, over the canvas or off it. +#[test] +fn side_buttons_pan_like_the_middle_button() { + for b in [PointerButton::Extra1, PointerButton::Extra2] { + check_button(b, false, false); + check_button(b, false, true); + } +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index cc0fc9db8..1c97e8931 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (a mouse's side buttons (4 and 5) pan the canvas as the middle button does (#1758); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -81,7 +81,7 @@ interaction feel not yet compared. | Tool | Status | Notes | |---|---|---| -| Move, hand (Space), zoom (hold Z, Alt out, drag area) | done | | +| Move, hand (Space), zoom (hold Z, Alt out, drag area) | done | the middle mouse button and a mouse's side buttons (4 and 5) pan as Space does (#1758) | | Frame (presets panel, swap orientation), section, slice | done | | | Rectangle, ellipse (arc handles and Design panel arc fields), polygon, star, line, arrow; Shift/Alt | done | Alt draws lines from the centre too (`shapes_behaviour_tests`) | | Corner radius handles (inside each corner of a rectangle or frame, a polygon's or star's top point; Alt: one corner), star ratio handle; Count and Ratio fields | done | handles hide under 48 px on screen; no count handle on the canvas (the Count field instead); corner smoothing rounds rectangles and frames only | @@ -178,6 +178,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-05 | patch | M1, #1758: a mouse's side buttons (4 and 5) pan the canvas as the middle button does, the pan ending on release over the canvas or off it; the grab cursor shows while they're held. | | 2026-11-02 | patch | M8, #1875: a click with the Bend tool on a sharp point between two segments gives it handles along the line between its neighbours, a third of the way to each ("Click on a point or path where you want to add a curve", Edit vector layers); a click on a curved point still makes it sharp, a drag still sets the handles by hand, an endpoint is left alone. Between a handle's end and a point both within reach of the pointer, the nearer one on the page is hit (the handle on a tie), so a short path's point (its handles a few pixels long) can be clicked again. Before, only a drag curved a point, and a short one left two tiny handles in its direction. Tests: `vectoredit::tests::short_handles_leave_their_point_clickable`, `vectoredit::tests::a_bend_click_curves_a_sharp_point_between_its_neighbours`, `bend_tool_smooths_and_sharpens_points`. Numbers unchanged. | | 2026-11-02 | minor | M4, #1827: wrap style on a text layer (`WrapStyle`: Auto, Balance, Pretty): Balance re-breaks each paragraph at the narrowest width that keeps its line count (bisection over the greedy breaker, as browsers balance), Pretty narrows one of the last four lines just enough so the last line isn't one word; `text.wrapStyle`, `node.set wrapStyle` (`textWrap` too), inspect `wrapStyle`, Dev Mode CSS `text-wrap` (Tailwind `text-balance` / `text-pretty`), the Type settings control under Vertical trim. Per-paragraph settings, text-style support and the `.fig` import/export mapping stay open. Test: `text_behaviour_tests::balance_and_pretty_wrap_styles_break_lines_as_documented`. | | 2026-11-02 | patch | M4: Backspace or Delete at the start of a list item takes its marker and keeps its level ("Use Backspace or Delete at the beginning of a list item to delete the counter, but keep the same level of indentation", Create bulleted and numbered lists): a plain paragraph may now carry a list level, and the text layout starts it where that level's item text starts (the gutters stay even when no list is left). Backspace used to drop the level too, and Delete at an item's start deleted the next character. Tab on such a paragraph types a tab, as outside a list. Tests: `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests::a_plain_paragraph_at_a_list_level_starts_where_the_items_text_does` | From cd5c9aeb09408fcb7ce50590fb9ce39b59e4cbe5 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 5 Nov 2026 03:23:07 -0500 Subject: [PATCH 081/102] =?UTF-8?q?M4:=20a=20paragraph's=20base=20directio?= =?UTF-8?q?n=20can=20be=20forced:=20Text=20=E2=96=B8=20Text=20direction=20?= =?UTF-8?q?(#1830)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Direction came from the letters only; Add right-to-left text says controls override it per paragraph (Text > Text direction, Left to right or Right to left). `TextDirection` on `ParaList`, `Bidi::of` with a base level per paragraph, `text.direction` and the three menu commands (the edited paragraphs while editing), `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect `textDirection` / `lineDirections`, the CSS `direction`, and the `.fig` lines' `sourceDirectionality` in and out. Co-Authored-By: Claude Fable 5.1 --- ROADMAP.md | 1 + crates/doc/src/text.rs | 29 +++++-- crates/engine/src/automation/inspect.rs | 12 +++ crates/engine/src/catalog.rs | 7 +- crates/engine/src/cmd/props.rs | 8 +- crates/engine/src/cmd/text.rs | 31 ++++++- crates/engine/src/dev/codegen/css.rs | 7 ++ crates/engine/src/text_behaviour_tests.rs | 51 ++++++++++++ crates/engine/src/text_tail_tests.rs | 13 ++- crates/format/src/fig/export.rs | 4 +- crates/format/src/fig/export/shape.rs | 11 ++- crates/format/src/fig/map/text.rs | 12 +++ crates/format/src/fig/tests.rs | 3 + crates/format/src/fig/text_direction_tests.rs | 83 +++++++++++++++++++ crates/format/src/fig/text_list_tests.rs | 2 +- crates/format/src/rest/text.rs | 20 +++-- crates/text/src/behaviour_tests.rs | 2 +- crates/text/src/layout.rs | 46 +++++++--- crates/text/src/tail_tests.rs | 4 +- crates/text/src/tests.rs | 26 +++++- crates/ui-egui/locales/en.toml | 4 + crates/ui-egui/src/panels/typography.rs | 2 +- .../ui-egui/src/panels/typography/fields.rs | 30 ++++++- docs/localization-parity.md | 4 +- docs/ui-parity.md | 4 +- 25 files changed, 365 insertions(+), 51 deletions(-) create mode 100644 crates/format/src/fig/text_direction_tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 410705919..c5ca92f35 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -132,6 +132,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). ## Progress log +- **2026-11-05** · M4, #1830: a paragraph's base direction can be forced (Text ▸ Text direction: Auto, Left to right, Right to left) as Add right-to-left text says ("controls are available to override text direction per paragraph"). `ParaList::direction`, `text.direction {direction, ids?}` and the three menu commands (the edited paragraphs while editing, else the layer's), `node.set textDirection`, the Type settings control once a right-to-left script is in the text, `textDirection` / `lineDirections` in inspect, the CSS `direction`, and the `.fig` lines' `sourceDirectionality` in and out. Layout gives each paragraph its base level (`Bidi::of` per paragraph). Tests: `text_behaviour_tests::text_direction_is_forced_per_paragraph`, `fig::text_direction_tests`. - **2026-10-30**: M8, #1125: damaged `trak` size-table offsets are checked instead of wrapping on 32-bit targets, and an incomplete normal track is dropped entirely, never returned in part. Font indexing makes its existing bounds explicit, preserving later faces and sparse name-table reads. Synthetic regression tests in `fontdb_tests.rs`. Numbers unchanged. - **2026-10-30** · Text style dedupe is O(spans) (M8, #1102): `shape_text` deduped spans into styles by a scan over the styles already collected — O(spans × styles), so a styled text's dedupe grew with the square of its runs (a synthetic 50k-run text with 100 alternating styles spent 7.7 ms in it). Now the last two styles again (spans run in blocks), then buckets keyed by a cheap fingerprint (family and style bytes, size bits with −0.0 folded, the enums, fill count and solid colours), each bucket resolved with the full equality: the result is the scan's, never worse than it, and O(spans) when names and sizes differ (the same synthetic text: 2.6 ms). The font-db write lock is untouched: `find()` loads faces, which needs the write. `layout_dedupe_tests`. Numbers unchanged. - **2026-10-29** · M10: correct nine German labels in `de.toml`: gradient stops use Verlaufsstopp, OpenType ss01–ss05 use Stilsatz, and the Home-screen preference names the Startbildschirm consistently in the UI and Actions palette. This is a partial terminology pass; German remains a draft awaiting a full native-speaker review and maintainer approval. Numbers unchanged. diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index ba196edb3..0707f4201 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -259,10 +259,24 @@ pub enum ListStyle { Numbered, } +/// A paragraph's base direction: by its letters, or forced ("controls are available to override +/// text direction per paragraph", Add right-to-left text). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum TextDirection { + /// The first letter with a direction decides (Unicode rules P2 and P3). + #[default] + Auto, + /// Left to right, whatever the letters. + Ltr, + /// Right to left, whatever the letters. + Rtl, +} + /// Deepest list nesting (levels 0..=MAX_LIST_INDENT). pub const MAX_LIST_INDENT: u8 = 8; -/// One paragraph's list settings. +/// One paragraph's list settings and base direction. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(default)] pub struct ParaList { @@ -276,6 +290,9 @@ pub struct ParaList { /// (items that go on counting ignore it; other paragraphs are always 0). #[serde(skip_serializing_if = "crate::node::is_default")] pub start_offset: u32, + /// The paragraph's base direction (Text ▸ Text direction); `Auto` follows its letters. + #[serde(skip_serializing_if = "crate::node::is_default")] + pub direction: TextDirection, } /// Character style. In runs, every field is an override; `None` means "inherit the base". @@ -991,20 +1008,20 @@ mod case_tests { // Files written before start numbers load with none, and write the same bytes. let old = r#"{"list":"numbered","indent":1}"#; let pl: ParaList = serde_json::from_str(old).unwrap(); - assert_eq!(pl, ParaList { list: N, indent: 1, start_offset: 0 }); + assert_eq!(pl, ParaList { list: N, indent: 1, start_offset: 0, ..ParaList::default() }); assert_eq!(serde_json::to_string(&pl).unwrap(), old); // One numbered paragraph with a start keeps it (it doesn't fold into `list`). let mut t = TextData { characters: "Next".into(), ..Default::default() }; - t.set_para_lists(0, 0, |p| *p = ParaList { list: N, indent: 0, start_offset: 1 }); - assert_eq!(t.para_list(0), ParaList { list: N, indent: 0, start_offset: 1 }); + t.set_para_lists(0, 0, |p| *p = ParaList { list: N, indent: 0, start_offset: 1, ..ParaList::default() }); + assert_eq!(t.para_list(0), ParaList { list: N, indent: 0, start_offset: 1, ..ParaList::default() }); // Enter copies it to the new item; different starts don't make the list mixed. t.replace_range(4, 4, "\nMore"); assert_eq!(t.para_list(1).start_offset, 1); t.set_para_lists(5, 5, |p| p.start_offset = 0); assert!(t.common_para_list(0, t.char_count()).is_some_and(|p| p.list == N)); // Bullets have no number, so no start. - t.set_para_lists(0, 0, |p| *p = ParaList { list: B, indent: 1, start_offset: 4 }); - assert_eq!(t.para_list(0), ParaList { list: B, indent: 1, start_offset: 0 }); + t.set_para_lists(0, 0, |p| *p = ParaList { list: B, indent: 1, start_offset: 4, ..ParaList::default() }); + assert_eq!(t.para_list(0), ParaList { list: B, indent: 1, start_offset: 0, ..ParaList::default() }); // A plain paragraph has none. t.set_para_lists(0, 0, |p| p.list = P); assert_eq!(t.para_list(0), ParaList::default()); diff --git a/crates/engine/src/automation/inspect.rs b/crates/engine/src/automation/inspect.rs index 871dbea6f..324635071 100644 --- a/crates/engine/src/automation/inspect.rs +++ b/crates/engine/src/automation/inspect.rs @@ -53,6 +53,7 @@ pub const NODE_KEYS: &[&str] = &[ "layout", "leadingTrim", "letterSpacing", + "lineDirections", "lineHeight", "lineIndentations", "lineTypes", @@ -96,6 +97,7 @@ pub const NODE_KEYS: &[&str] = &[ "textDecorationSkipInk", "textDecorationStyle", "textDecorationThickness", + "textDirection", "textPath", "textStyleRanges", "type", @@ -432,6 +434,16 @@ fn text_props(t: &TextData, o: &mut serde_json::Map, options: &In insert_prop(o, options, "listStartOffsets", || t.paragraphs.iter().map(|p| json!(p.start_offset)).collect()); } } + // The paragraphs' base direction: one for the layer when they agree, else each one's (Auto + // throughout says nothing). + let dirs: Vec = t.paragraphs.iter().map(|p| p.direction).collect(); + if let Some(first) = dirs.first().copied().filter(|d| *d != figcraft_doc::TextDirection::Auto) + && dirs.iter().all(|d| *d == first) + { + insert_prop(o, options, "textDirection", || json!(first)); + } else if dirs.iter().any(|d| *d != figcraft_doc::TextDirection::Auto) { + insert_prop(o, options, "lineDirections", || dirs.iter().map(|d| json!(d)).collect()); + } if t.list_spacing != 0.0 { insert_prop(o, options, "listSpacing", || json!(t.list_spacing)); } diff --git a/crates/engine/src/catalog.rs b/crates/engine/src/catalog.rs index 62236b8e7..a8a18b38c 100644 --- a/crates/engine/src/catalog.rs +++ b/crates/engine/src/catalog.rs @@ -216,6 +216,11 @@ pub static MENU: &[MenuItem] = &[ m!("Text/Case", "Uppercase", "text.caseUpper"), m!("Text/Case", "Lowercase", "text.caseLower"), m!("Text/Case", "Title case", "text.caseTitle"), + // "Go to Text > Text direction. Select Left to right or Right to left." (Add right-to-left + // text); Auto, the way back to detection, is FigCraft's own (in `OWN`). + m!("Text/Text direction", "Auto", "text.directionAuto"), + m!("Text/Text direction", "Left to right", "text.directionLtr"), + m!("Text/Text direction", "Right to left", "text.directionRtl"), m!("Text", SEP, ""), m!("Text", "Missing fonts…", "text.missingFonts"), // Arrange @@ -292,7 +297,7 @@ pub fn items() -> impl Iterator { } /// Items of FigCraft's own that the parity count leaves out (as it does the `collab.` ones). -const OWN: [&str; 5] = ["file.newFromTemplate", "file.newBoard", "help.gettingStarted", "text.missingFonts", "image.crop"]; +const OWN: [&str; 6] = ["file.newFromTemplate", "file.newBoard", "help.gettingStarted", "text.missingFonts", "image.crop", "text.directionAuto"]; /// Coverage: (implemented, total, missing ids). `extra` lists ids implemented by the UI layer. pub fn parity(extra: &[&str]) -> (usize, usize, Vec<&'static str>) { diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index abd380cfc..de47105df 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -956,6 +956,12 @@ fn apply_text(cmd: &str, doc: &mut Document, id: NodeId, props: &Map { + let d: figcraft_doc::TextDirection = enum_of(v).ok_or_else(|| bad(cmd, "textDirection: auto|ltr|rtl"))?; + let t = text_mut(cmd, doc.get_mut(id)?)?; + let (start, end) = range_of(props, t.char_count()); + t.set_para_lists(start, end, |p| p.direction = d); + } "listSpacing" => text_mut(cmd, doc.get_mut(id)?)?.list_spacing = f64_of(v).filter(|s| s.is_finite()).unwrap_or(0.0).clamp(0.0, 10_000.0), "hangingPunctuation" | "hangingList" => { let on = v.as_bool().ok_or_else(|| bad(cmd, format!("`{k}` must be true or false")))?; @@ -1210,7 +1216,7 @@ pub fn override_group(k: &str) -> &'static str { "name" => "name", "characters" | "text" => "characters", "features" | "fontFeatures" | "openTypeFeatures" | "listStyle" | "indentation" | "listSpacing" | "maxLines" | "variationSettings" - | "hangingPunctuation" | "hangingList" | "wrapStyle" | "textWrap" => "textStyle", + | "hangingPunctuation" | "hangingList" | "wrapStyle" | "textWrap" | "textDirection" | "direction" => "textStyle", "cornerRadius" | "cornerSmoothing" | "topLeftRadius" | "topRightRadius" | "bottomRightRadius" | "bottomLeftRadius" => "corners", "width" | "height" | "w" | "h" => "size", "sizingH" | "sizingV" | "layoutSizingHorizontal" | "layoutSizingVertical" | "minWidth" | "maxWidth" | "minHeight" | "maxHeight" => "resizing", diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 7914f259e..290faf913 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -1,8 +1,8 @@ //! Text menu and text editing commands. use figcraft_doc::{ - LetterSpacing, LineHeight, ListStyle, NodeId, NodeKind, TextAlignH, TextAutoResize, TextCase, TextData, TextDecoration, TextPath, TextStyle, - VariableId, + LetterSpacing, LineHeight, ListStyle, NodeId, NodeKind, TextAlignH, TextAutoResize, TextCase, TextData, TextDecoration, TextDirection, TextPath, + TextStyle, VariableId, }; use serde_json::{Map, Value, json}; @@ -91,6 +91,13 @@ fn set_list(s: &mut Session, p: &Value, l: ListStyle, toggle: bool) -> Result Result { + para_range(s, p, |t, a, b| t.set_para_lists(a, b, |pl| pl.direction = d)) +} + /// Whether every targeted char has `pred` (to decide toggle direction). fn all_have(s: &Session, p: &Value, pred: impl Fn(&TextStyle) -> bool) -> bool { let Ok(doc) = s.doc() else { return false }; @@ -319,6 +326,26 @@ pub fn specs() -> Vec { para(s, p, |t| t.wrap_style = w) } ), + spec!( + "text.direction", + "Text direction", + "{direction: auto|ltr|rtl, ids?} the base direction of the paragraphs (while editing: the selected ones): auto goes by the first letter with a direction, ltr runs them left to right and rtl right to left whatever their letters (Text ▸ Text direction)", + true, + |s, p| { + let d: TextDirection = + get(p, "direction").and_then(super::props::enum_of).ok_or_else(|| bad("text.direction", "`direction`: auto|ltr|rtl"))?; + set_direction(s, p, d) + } + ), + spec!("text.directionAuto", "Text direction: auto", "{ids?} while editing: the selected paragraphs", true, |s, p| { + set_direction(s, p, TextDirection::Auto) + }), + spec!("text.directionLtr", "Text direction: left to right", "{ids?} while editing: the selected paragraphs", true, |s, p| { + set_direction(s, p, TextDirection::Ltr) + }), + spec!("text.directionRtl", "Text direction: right to left", "{ids?} while editing: the selected paragraphs", true, |s, p| { + set_direction(s, p, TextDirection::Rtl) + }), spec!("text.paragraphIndent", "Paragraph indent", "{indent (px), ids?}", true, |s, p| { let v = finite(req_num("text.paragraphIndent", p, "indent")?).clamp(0.0, 10_000.0); para(s, p, |t| t.paragraph_indent = v) diff --git a/crates/engine/src/dev/codegen/css.rs b/crates/engine/src/dev/codegen/css.rs index 2395c7873..c772367fd 100644 --- a/crates/engine/src/dev/codegen/css.rs +++ b/crates/engine/src/dev/codegen/css.rs @@ -307,6 +307,13 @@ fn text_decls(doc: &Document, n: &Node, tx: &figcraft_doc::TextData, t: &mut Tok figcraft_doc::WrapStyle::Balance => put("text-wrap", "balance".into()), figcraft_doc::WrapStyle::Pretty => put("text-wrap", "pretty".into()), } + // A base direction forced on every paragraph (CSS has one per element). + let dir = tx.paragraphs.first().map(|p| p.direction).filter(|d| tx.paragraphs.iter().all(|p| p.direction == *d)); + match dir { + Some(figcraft_doc::TextDirection::Ltr) => put("direction", "ltr".into()), + Some(figcraft_doc::TextDirection::Rtl) => put("direction", "rtl".into()), + _ => {} + } match s.case { TextCase::Original => {} TextCase::Upper => put("text-transform", "uppercase".into()), diff --git a/crates/engine/src/text_behaviour_tests.rs b/crates/engine/src/text_behaviour_tests.rs index 1e700c688..6db19a1cc 100644 --- a/crates/engine/src/text_behaviour_tests.rs +++ b/crates/engine/src/text_behaviour_tests.rs @@ -371,6 +371,57 @@ fn max_lines_on_auto_height_text_hugs_that_many_lines() { assert_eq!(resize_mode(&s, fixed), TextAutoResize::Truncate); } +#[test] +fn text_direction_is_forced_per_paragraph() { + // Add right-to-left text: "By default, Figma automatically handles text direction based on + // language detection. However, controls are available to override text direction per + // paragraph" ("Go to Text > Text direction. Select Left to right or Right to left."). + let font = test_mono_font(); + let mut s = Session::new(); + let t = text(&mut s, "abc def\nghi\njkl", json!({"fontFamily": font, "fontSize": 16, "lineHeight": 24})); + let rtl = |s: &Session| -> Vec { + let (l, _) = figcraft_text::layout_node(s.doc().unwrap().node(t).unwrap()).unwrap(); + l.lines.iter().map(|l| l.rtl).collect() + }; + let inspect = |s: &Session| crate::inspect::node_json(s.doc().unwrap(), t, 0); + assert_eq!(rtl(&s), [false, false, false], "Latin letters read left to right"); + assert!(inspect(&s).get("textDirection").is_none() && inspect(&s).get("lineDirections").is_none()); + // The layer's paragraphs at once, by the command or `node.set`; inspect reports the one + // direction they share, and Dev Mode's CSS has it. + s.execute("text.direction", &json!({"ids": [t], "direction": "rtl"})).unwrap(); + assert_eq!(rtl(&s), [true, true, true], "forced right to left whatever the letters"); + assert_eq!(inspect(&s)["textDirection"], json!("rtl")); + let css = |s: &mut Session| s.execute("inspect.code", &json!({"id": t})).unwrap()["code"].as_str().unwrap().to_string(); + assert!(css(&mut s).contains("direction: rtl;"), "{}", css(&mut s)); + s.execute("node.set", &json!({"id": t, "props": {"textDirection": "ltr"}})).unwrap(); + assert_eq!(rtl(&s), [false, false, false]); + assert_eq!(inspect(&s)["textDirection"], json!("ltr")); + assert!(css(&mut s).contains("direction: ltr;")); + s.execute("text.directionAuto", &json!({"ids": [t]})).unwrap(); + assert!(inspect(&s).get("textDirection").is_none(), "auto throughout says nothing"); + assert!(!css(&mut s).contains("direction:")); + // While editing, the caret's paragraph alone (the menu's Right to left); inspect lists each + // paragraph's direction when they differ, and the CSS stays quiet. + s.execute("text.edit.begin", &json!({"id": t, "caret": 9})).unwrap(); + s.execute("text.directionRtl", &json!({})).unwrap(); + s.execute("text.edit.end", &json!({})).unwrap(); + assert_eq!(rtl(&s), [false, true, false], "the second paragraph only"); + assert_eq!(inspect(&s)["lineDirections"], json!(["auto", "rtl", "auto"])); + assert!(!css(&mut s).contains("direction:")); + // Enter inside a forced paragraph keeps the direction for the new one, as list settings carry. + s.execute("text.edit.begin", &json!({"id": t, "caret": 10})).unwrap(); + s.execute("text.edit.insert", &json!({"text": "\n"})).unwrap(); + s.execute("text.edit.end", &json!({})).unwrap(); + assert_eq!(rtl(&s), [false, true, true, false]); + // A direction the document has words for; junk is refused. + s.execute("node.set", &json!({"id": t, "props": {"characters": "\u{05E9}\u{05DC}\u{05D5}\u{05DD} abc", "textDirection": "auto"}})).unwrap(); + assert_eq!(rtl(&s), [true], "Hebrew first: right to left by detection"); + s.execute("node.set", &json!({"id": t, "props": {"textDirection": "ltr"}})).unwrap(); + assert_eq!(rtl(&s), [false], "forced left to right"); + assert!(s.execute("node.set", &json!({"id": t, "props": {"textDirection": "sideways"}})).is_err()); + assert!(s.execute("text.direction", &json!({"ids": [t], "direction": "up"})).is_err()); +} + #[test] fn balance_and_pretty_wrap_styles_break_lines_as_documented() { // Explore text properties: "Auto: Figma fits as many words as possible on each line before diff --git a/crates/engine/src/text_tail_tests.rs b/crates/engine/src/text_tail_tests.rs index 8e399ba3a..ccd8328ff 100644 --- a/crates/engine/src/text_tail_tests.rs +++ b/crates/engine/src/text_tail_tests.rs @@ -64,7 +64,7 @@ fn a_list_with_a_start_number_toggles_off() { let mut s = Session::new(); let t = text(&mut s, "two\nthree\nfour"); if let figcraft_doc::NodeKind::Text(td) = &mut s.doc_mut().unwrap().get_mut(t).unwrap().kind { - let n = |start_offset| ParaList { list: N, indent: 0, start_offset }; + let n = |start_offset| ParaList { list: N, indent: 0, start_offset, ..ParaList::default() }; td.paragraphs = vec![n(1), n(0), n(0)]; } let j = crate::inspect::node_json(s.doc().unwrap(), t, 0); @@ -157,7 +157,8 @@ fn list_keys_at_list_items() { for (chars, before, caret, k, shift, after, want, why) in cases { let mut s = Session::new(); let t = text(&mut s, chars); - let ps: Vec = before.iter().map(|(list, indent)| ParaList { list: *list, indent: *indent, start_offset: 0 }).collect(); + let ps: Vec = + before.iter().map(|(list, indent)| ParaList { list: *list, indent: *indent, start_offset: 0, ..ParaList::default() }).collect(); if let figcraft_doc::NodeKind::Text(td) = &mut s.doc_mut().unwrap().get_mut(t).unwrap().kind { td.paragraphs = ps; } @@ -181,7 +182,11 @@ fn paragraph_lists_follow_edits() { // A paragraph's list stays with it as text is typed, pasted and deleted: new paragraphs copy // the one they split from; joined paragraphs keep the first one's. let mut t = TextData::new("ab\ncd\nef"); - t.paragraphs = vec![ParaList { list: B, indent: 1, start_offset: 0 }, ParaList::default(), ParaList { list: N, indent: 0, start_offset: 0 }]; + t.paragraphs = vec![ + ParaList { list: B, indent: 1, start_offset: 0, ..ParaList::default() }, + ParaList::default(), + ParaList { list: N, indent: 0, start_offset: 0, ..ParaList::default() }, + ]; let get = |t: &TextData| (0..t.paragraph_count()).map(|p| (t.para_list(p).list, t.para_list(p).indent)).collect::>(); t.replace_range(1, 1, "x\ny"); assert_eq!(get(&t), [(B, 1), (B, 1), (P, 0), (N, 0)], "a pasted newline: a new item like it"); @@ -196,7 +201,7 @@ fn paragraph_lists_follow_edits() { (seed >> 33) as usize % n.max(1) }; let mut t = TextData::new("a\nb\nc\nd"); - t.paragraphs = vec![ParaList { list: B, indent: 2, start_offset: 0 }; 4]; + t.paragraphs = vec![ParaList { list: B, indent: 2, start_offset: 0, ..ParaList::default() }; 4]; for _ in 0..500 { let n = t.char_count(); let (a, b) = (rnd(n + 2), rnd(n + 2)); diff --git a/crates/format/src/fig/export.rs b/crates/format/src/fig/export.rs index 9e2c4b364..d42679324 100644 --- a/crates/format/src/fig/export.rs +++ b/crates/format/src/fig/export.rs @@ -27,8 +27,8 @@ use figcraft_doc::proto::{ use figcraft_doc::{ AutoLayout, BoolOp, ContentAlign, CrossAlign, Document, EffectKind, ExportSize, GridAlign, GridKind, GridTrack, HConstraint, LayoutMode, LetterSpacing, LineHeight, ListStyle, MainAlign, MaskType, Node, NodeId, NodeKind, NoiseMode, PropDef, Sizing, StrokeAlign, StrokeCap, - StrokeJoin, StyleKind, TextAlignH, TextAlignV, TextAutoResize, TextCase, TextData, TextDecoration, TextStyle, VConstraint, VariableType, - VariableValue, VectorNetwork, WindingRule, + StrokeJoin, StyleKind, TextAlignH, TextAlignV, TextAutoResize, TextCase, TextData, TextDecoration, TextDirection, TextStyle, VConstraint, + VariableType, VariableValue, VectorNetwork, WindingRule, }; use serde_json::Value; use sha1::Digest; diff --git a/crates/format/src/fig/export/shape.rs b/crates/format/src/fig/export/shape.rs index e4e2cae6b..69228a0cc 100644 --- a/crates/format/src/fig/export/shape.rs +++ b/crates/format/src/fig/export/shape.rs @@ -1,8 +1,8 @@ use super::common::{style_fields, unsupported_decoration_look}; use super::{ Affine, BezPath, Bound, Exporter, Fields, Kv, ListStyle, MAX_CANVAS, MAX_CHARS, MAX_NETWORK, Node, NodeKind, Paint, StrokeAlign, StrokeCap, - StrokeJoin, TextAlignH, TextAlignV, TextAutoResize, TextData, TextStyle, VectorNetwork, WindingRule, arr, b, cap_name, e, finite, fl, int, - join_name, network, o, path_blob, s, u, xy, + StrokeJoin, TextAlignH, TextAlignV, TextAutoResize, TextData, TextDirection, TextStyle, VectorNetwork, WindingRule, arr, b, cap_name, e, finite, + fl, int, join_name, network, o, path_blob, s, u, xy, }; impl<'d> Exporter<'d> { @@ -128,11 +128,16 @@ impl<'d> Exporter<'d> { let listed = *l != ListStyle::None; let begins = first(i, l); let start = starts.get(i).copied().unwrap_or(0); + let direction = match td.para_list(i).direction { + TextDirection::Auto => "AUTO", + TextDirection::Ltr => "LTR", + TextDirection::Rtl => "RTL", + }; o(vec![ ("lineType", e(ty)), ("styleId", int(0)), ("indentationLevel", int(i64::from(listed))), - ("sourceDirectionality", e("AUTO")), + ("sourceDirectionality", e(direction)), ("listStartOffset", int(i64::from(start))), ("isFirstLineOfList", b(begins)), ]) diff --git a/crates/format/src/fig/map/text.rs b/crates/format/src/fig/map/text.rs index 13bed7440..0249b1086 100644 --- a/crates/format/src/fig/map/text.rs +++ b/crates/format/src/fig/map/text.rs @@ -130,6 +130,18 @@ impl<'a> Mapper<'a> { if lines.iter().any(|l| *l != "NONE") { o.insert("lineTypes".into(), json!(lines)); } + // A forced base direction per paragraph (`sourceDirectionality`; not a REST field). + let dirs: Vec<&str> = raw + .iter() + .map(|l| match l.get("sourceDirectionality").and_then(Kv::str) { + Some("LTR") => "LTR", + Some("RTL") => "RTL", + _ => "AUTO", + }) + .collect(); + if dirs.iter().any(|d| *d != "AUTO") { + o.insert("lineDirections".into(), json!(dirs)); + } // Where a numbered list starts counting, less one (not a REST field). let starts: Vec = raw.iter().map(|l| num(l, "listStartOffset").filter(|n| n.is_finite()).map_or(0, |n| n.clamp(0.0, f64::from(u32::MAX)) as u32)).collect(); diff --git a/crates/format/src/fig/tests.rs b/crates/format/src/fig/tests.rs index 2d4a1f7d6..8833727ee 100644 --- a/crates/format/src/fig/tests.rs +++ b/crates/format/src/fig/tests.rs @@ -1491,6 +1491,9 @@ mod image_filters; #[path = "text_list_tests.rs"] mod text_list; +#[path = "text_direction_tests.rs"] +mod text_direction; + /// `.fig` files in the folder `FIGCRAFT_FIG_SAMPLES` names (none when it's unset). pub(super) fn samples() -> Vec { let Some(dir) = std::env::var_os("FIGCRAFT_FIG_SAMPLES") else { return Vec::new() }; diff --git a/crates/format/src/fig/text_direction_tests.rs b/crates/format/src/fig/text_direction_tests.rs new file mode 100644 index 000000000..a3647946d --- /dev/null +++ b/crates/format/src/fig/text_direction_tests.rs @@ -0,0 +1,83 @@ +//! A paragraph's forced base direction (#1830): each text line's `sourceDirectionality` (AUTO, +//! LTR or RTL) comes in as the paragraph's direction and goes back out. Fixtures built in code with +//! the parent module's helpers. + +use figcraft_doc::{NodeKind, TextDirection}; + +use super::*; + +const DIRECTION_SCHEMA: &str = " +enum NodeType NONE DOCUMENT CANVAS TEXT +enum LineType PLAIN ORDERED_LIST UNORDERED_LIST +enum SourceDirectionality AUTO LTR RTL +struct GUID uint sessionID, uint localID +struct Vector float x, float y +struct Matrix float m00, float m01, float m02, float m10, float m11, float m12 +message ParentIndex GUID guid, string position +message TextLineData LineType lineType, int indentationLevel, SourceDirectionality sourceDirectionality, int listStartOffset, bool isFirstLineOfList +message TextData string characters, TextLineData[] lines +message NodeChange GUID guid, ParentIndex parentIndex, NodeType type, string name, Vector size, Matrix transform, float fontSize, TextData textData +message Message NodeChange[] nodeChanges +"; + +/// A plain line with a base direction. +fn line(direction: &'static str) -> Kv<'static> { + o(vec![ + ("lineType", e("PLAIN")), + ("indentationLevel", Kv::Int(0)), + ("sourceDirectionality", e(direction)), + ("listStartOffset", Kv::Int(0)), + ("isFirstLineOfList", Kv::Bool(false)), + ]) +} + +fn text_node(id: u64, name: &str, chars: &str, lines: Vec>) -> Kv<'static> { + let pos = ["!", "\"", "#", "$"][id as usize % 4]; + node( + id, + Some((1, pos)), + "TEXT", + name, + vec![ + ("size", xy(200.0, 60.0)), + ("transform", at(0.0, 0.0)), + ("fontSize", f(16.0)), + ("textData", o(vec![("characters", s(chars)), ("lines", arr(lines))])), + ], + ) +} + +fn directions(doc: &figcraft_doc::Document, name: &str) -> Vec { + let NodeKind::Text(t) = &named(doc, name).kind else { panic!("{name} is no text") }; + (0..t.paragraph_count()).map(|p| t.para_list(p).direction).collect() +} + +#[test] +fn a_lines_source_directionality_is_its_paragraphs_direction_both_ways() { + use TextDirection::{Auto as A, Ltr as L, Rtl as R}; + let nodes = vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page", vec![]), + text_node(2, "Detected", "abc\ndef", vec![line("AUTO"), line("AUTO")]), + text_node(3, "Forced", "abc\ndef\nghi", vec![line("RTL"), line("AUTO"), line("LTR")]), + ]; + let sc = Schema::parse(DIRECTION_SCHEMA).unwrap(); + let (doc, warnings) = import(&canvas(&sc, &o(vec![("nodeChanges", arr(nodes))])), "x").unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(directions(&doc, "Detected"), [A, A]); + let NodeKind::Text(t) = &named(&doc, "Detected").kind else { panic!() }; + assert!(t.paragraphs.is_empty(), "AUTO throughout keeps the paragraphs folded"); + assert_eq!(directions(&doc, "Forced"), [R, A, L]); + // Out again: every line says its direction, and a reader gets the same paragraphs back. + let (bytes, _) = super::super::export(&doc, None).unwrap(); + let a = Archive::open(&bytes).unwrap(); + let (schema, message) = decode_canvas(&a.canvas).unwrap(); + let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap(); + let text = msg.get("nodeChanges").unwrap().list().iter().find(|n| n.get("name").and_then(Kv::str) == Some("Forced")).unwrap(); + let lines = text.get("textData").and_then(|d| d.get("lines")).map(Kv::list).unwrap(); + let out: Vec<&str> = lines.iter().map(|l| l.get("sourceDirectionality").and_then(Kv::str).unwrap()).collect(); + assert_eq!(out, ["RTL", "AUTO", "LTR"]); + let (back, _) = import(&bytes, "x").unwrap(); + assert_eq!(directions(&back, "Forced"), [R, A, L]); + assert_eq!(directions(&back, "Detected"), [A, A]); +} diff --git a/crates/format/src/fig/text_list_tests.rs b/crates/format/src/fig/text_list_tests.rs index eca7b0dc5..a2d6702bc 100644 --- a/crates/format/src/fig/text_list_tests.rs +++ b/crates/format/src/fig/text_list_tests.rs @@ -75,7 +75,7 @@ fn the_export_writes_where_a_list_starts() { let page = doc.first_page().unwrap(); use ListStyle::{Bulleted as B, None as P, Numbered as N}; let mut td = figcraft_doc::TextData::new("two\nthree\nplain\nsix\ndot"); - let pl = |list, start_offset| ParaList { list, indent: 0, start_offset }; + let pl = |list, start_offset| ParaList { list, indent: 0, start_offset, ..ParaList::default() }; td.paragraphs = vec![pl(N, 1), pl(N, 0), pl(P, 0), pl(N, 5), pl(B, 4)]; doc.create(page, NodeKind::Text(td), "List", 0.0, 0.0, 200.0, 80.0).unwrap(); let (bytes, _) = super::super::export(&doc, None).unwrap(); diff --git a/crates/format/src/rest/text.rs b/crates/format/src/rest/text.rs index 83055dc10..ca5c51d15 100644 --- a/crates/format/src/rest/text.rs +++ b/crates/format/src/rest/text.rs @@ -5,7 +5,7 @@ use std::collections::BTreeMap; use figcraft_doc::{ DecorationLength, DecorationStyle, LetterSpacing, LineHeight, ListStyle, ParaList, StyleRun, TextAlignH, TextAlignV, TextAutoResize, TextCase, - TextData, TextDecoration, TextPath, TextStyle, + TextData, TextDecoration, TextDirection, TextPath, TextStyle, }; use serde_json::Value; @@ -256,23 +256,27 @@ fn runs(cx: &mut Ctx, v: &Value, td: &TextData) -> Vec { out } -/// Each paragraph's list type, nesting level and start number from `lineTypes`, -/// `lineIndentations` and (from `.fig` files) `listStartOffsets`. +/// Each paragraph's list type, nesting level, start number and base direction from `lineTypes`, +/// `lineIndentations` and (from `.fig` files) `listStartOffsets` and `lineDirections`. fn lists(v: &Value, td: &mut TextData) { let types = list(v, "lineTypes"); let indents = list(v, "lineIndentations"); let starts = list(v, "listStartOffsets"); - td.paragraphs = types - .iter() - .enumerate() - .map(|(i, t)| ParaList { - list: match t.as_str() { + let dirs = list(v, "lineDirections"); + td.paragraphs = (0..types.len().max(dirs.len())) + .map(|i| ParaList { + list: match types.get(i).and_then(Value::as_str) { Some("UNORDERED") => ListStyle::Bulleted, Some("ORDERED") => ListStyle::Numbered, _ => ListStyle::None, }, indent: indents.get(i).and_then(Value::as_f64).filter(|d| d.is_finite()).map_or(0, |d| d.clamp(0.0, 255.0) as u8), start_offset: starts.get(i).and_then(Value::as_f64).filter(|n| n.is_finite()).map_or(0, |n| n.clamp(0.0, f64::from(u32::MAX)) as u32), + direction: match dirs.get(i).and_then(Value::as_str) { + Some("LTR") => TextDirection::Ltr, + Some("RTL") => TextDirection::Rtl, + _ => TextDirection::Auto, + }, }) .collect(); // Clamp the levels and fold one style for all back into the layer's list style. diff --git a/crates/text/src/behaviour_tests.rs b/crates/text/src/behaviour_tests.rs index 439a81fcf..731e639d4 100644 --- a/crates/text/src/behaviour_tests.rs +++ b/crates/text/src/behaviour_tests.rs @@ -109,7 +109,7 @@ fn a_plain_paragraph_at_a_list_level_starts_where_the_items_text_does() { if face().is_none() { return; } - let level = |list: ListStyle, indent: u8| ParaList { list, indent, start_offset: 0 }; + let level = |list: ListStyle, indent: u8| ParaList { list, indent, start_offset: 0, ..ParaList::default() }; let mut t = text("a\nb\nc", TextAutoResize::WidthAndHeight); t.paragraphs = vec![level(ListStyle::Bulleted, 1), level(ListStyle::None, 1), level(ListStyle::None, 0)]; let l = layout(&t, None, None); diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index dd728916b..732e59ec7 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use figcraft_doc::{ DecorationLength, DecorationStyle, LeadingTrim, LetterSpacing, LineHeight, ListStyle, ParaList, TextAlignH, TextAutoResize, TextCase, TextData, - TextDecoration, TextStyle, WrapStyle, color::PaintKind, valid_feature_tag, + TextDecoration, TextDirection, TextStyle, WrapStyle, color::PaintKind, valid_feature_tag, }; use figcraft_geom::{Affine, BezPath, Rect}; use harfrust::{Direction, Feature, ShapeOptions, ShaperInstance, Tag, UnicodeBuffer, Variation}; @@ -272,21 +272,29 @@ pub(crate) struct Bidi { } impl Bidi { - /// None when the text has nothing right to left (the common case costs one scan). - pub(crate) fn of(text: &str) -> Option { - if !text.chars().any(is_rtl_char) { + /// None when the text has nothing right to left and no paragraph forces its direction (the + /// common case costs one scan). `forced`, by paragraph: `Some(true)` runs right to left and + /// `Some(false)` left to right whatever the letters, `None` goes by the first letter with a + /// direction (Text ▸ Text direction, #1830). + pub(crate) fn of(text: &str, forced: &[Option]) -> Option { + if forced.iter().all(Option::is_none) && !text.chars().any(is_rtl_char) { return None; } - let info = unicode_bidi::BidiInfo::new(text, None); - let mut paras = info.paragraphs.iter().peekable(); let n = text.chars().count(); let (mut levels, mut rtl_para) = (Vec::with_capacity(n), Vec::with_capacity(n)); - for (b, _) in text.char_indices() { - while paras.peek().is_some_and(|p| p.range.end <= b) { - paras.next(); + // Paragraph by paragraph (the algorithm starts over at each one), so each can be given its + // base level. + for (p, para) in text.split_inclusive('\n').enumerate() { + let base = forced.get(p).copied().flatten().map(|rtl| if rtl { unicode_bidi::Level::rtl() } else { unicode_bidi::Level::ltr() }); + let info = unicode_bidi::BidiInfo::new(para, base); + let mut paras = info.paragraphs.iter().peekable(); + for (b, _) in para.char_indices() { + while paras.peek().is_some_and(|q| q.range.end <= b) { + paras.next(); + } + levels.push(info.levels.get(b).map(|l| l.number()).unwrap_or(0)); + rtl_para.push(paras.peek().is_some_and(|q| q.level.is_rtl())); } - levels.push(info.levels.get(b).map(|l| l.number()).unwrap_or(0)); - rtl_para.push(paras.peek().is_some_and(|p| p.level.is_rtl())); } Some(Bidi { levels, rtl_para }) } @@ -479,8 +487,20 @@ fn shape_text(text: &TextData) -> ShapedText { .filter_map(|(k, on)| <[u8; 4]>::try_from(k.as_bytes()).ok().map(|t| Feature::new(Tag::new(&t), u32::from(*on), ..))) .collect(); - // Shape each span, split by paragraph, bidi run and fallback face. - let bidi = Bidi::of(&text.characters); + // Shape each span, split by paragraph, bidi run and fallback face. A paragraph's direction is + // its letters' unless forced (Text ▸ Text direction). + let forced: Vec> = if text.paragraphs.is_empty() { + Vec::new() + } else { + (0..text.paragraph_count()) + .map(|p| match text.para_list(p).direction { + TextDirection::Auto => None, + TextDirection::Ltr => Some(false), + TextDirection::Rtl => Some(true), + }) + .collect() + }; + let bidi = Bidi::of(&text.characters, &forced); let level_at = |i: usize| bidi.as_ref().and_then(|b| b.levels.get(i)).copied().unwrap_or(0); // A grapheme cluster (emoji sequence, letter with marks) is shaped with one face. let cluster_start = crate::breaks::grapheme_starts(&text.characters); diff --git a/crates/text/src/tail_tests.rs b/crates/text/src/tail_tests.rs index 805f744d8..035e1912a 100644 --- a/crates/text/src/tail_tests.rs +++ b/crates/text/src/tail_tests.rs @@ -43,11 +43,11 @@ fn starts(l: &TextLayout) -> Vec<(f64, Option)> { } fn pl(list: ListStyle, indent: u8) -> ParaList { - ParaList { list, indent, start_offset: 0 } + ParaList { list, indent, start_offset: 0, ..ParaList::default() } } fn from(list: ListStyle, indent: u8, start_offset: u32) -> ParaList { - ParaList { list, indent, start_offset } + ParaList { list, indent, start_offset, ..ParaList::default() } } #[test] diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 6d341419c..e38963855 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -406,14 +406,36 @@ fn bidi_visual_order_follows_levels() { assert_eq!(crate::layout::visual_order(&[0, 0, 0]), vec![0, 1, 2]); assert!(crate::layout::visual_order(&[]).is_empty()); // Plain left-to-right text skips the analysis. - assert!(crate::layout::Bidi::of("Hello, world 123").is_none()); - let b = crate::layout::Bidi::of("abc \u{5D0}\u{5D1}\u{5D2}\n\u{5D3} x").unwrap(); + assert!(crate::layout::Bidi::of("Hello, world 123", &[]).is_none()); + assert!(crate::layout::Bidi::of("Hello, world 123", &[None, None]).is_none()); + let b = crate::layout::Bidi::of("abc \u{5D0}\u{5D1}\u{5D2}\n\u{5D3} x", &[]).unwrap(); assert_eq!(b.levels.get(..4), Some(&[0, 0, 0, 0][..])); assert!(b.levels.get(4..7).unwrap().iter().all(|l| l % 2 == 1)); // Paragraph direction comes from each paragraph's first strong char. assert!(!b.rtl_para[0] && b.rtl_para[8]); } +/// A paragraph's forced base direction (Text ▸ Text direction, #1830): the base level is given, +/// the letters' own levels still follow the rules, and the other paragraphs keep theirs. +#[test] +fn forced_direction_sets_a_paragraphs_base_level() { + use crate::layout::Bidi; + // Latin letters forced right to left: an embedded left-to-right run (level 2) in a + // right-to-left paragraph; the next paragraph, unforced, stays left to right. + let b = Bidi::of("ab\ncd", &[Some(true), None]).unwrap(); + assert_eq!(b.rtl_para, [true, true, true, false, false]); + assert_eq!((b.levels.get(..2), b.levels.get(3..)), (Some(&[2, 2][..]), Some(&[0, 0][..]))); + // Hebrew forced left to right: a right-to-left run (level 1) in a left-to-right paragraph. + let b = Bidi::of("\u{5D0}\u{5D1}", &[Some(false)]).unwrap(); + assert_eq!(b.rtl_para, [false, false]); + assert_eq!(b.levels, [1, 1]); + // Forcing what the letters already say changes nothing; a paragraph past the forced list is + // detected. + let b = Bidi::of("\u{5D0}\n\u{5D1}", &[Some(true)]).unwrap(); + assert_eq!(b.rtl_para, [true, true, true]); + assert_eq!((b.levels.first(), b.levels.last()), (Some(&1), Some(&1))); +} + /// The x of the glyph for char `i`. fn glyph_x(l: &TextLayout, i: usize) -> f64 { l.glyphs.iter().find(|g| g.char_start == i && g.char_end > i).map(|g| g.x).unwrap() diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 11f0bb4ac..8b83d8c85 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -407,6 +407,10 @@ name = "English" "Decoration" = "Decoration" "Deep select" = "Deep select" "Wrap style" = "Wrap style" +"Text direction" = "Text direction" +"Auto: by the first letter with a direction" = "Auto: by the first letter with a direction" +"Left to right" = "Left to right" +"Right to left" = "Right to left" "Balance" = "Balance" "Pretty" = "Pretty" "Auto: as many words as fit on each line" = "Auto: as many words as fit on each line" diff --git a/crates/ui-egui/src/panels/typography.rs b/crates/ui-egui/src/panels/typography.rs index 0f41fd2e3..a3a5bd66a 100644 --- a/crates/ui-egui/src/panels/typography.rs +++ b/crates/ui-egui/src/panels/typography.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use egui::{Align2, Color32, CornerRadius, Id, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; use figcraft_doc::{ DecorationLength, Document, LeadingTrim, LetterSpacing, LineHeight, ListStyle, NodeId, NodeKind, TextAlignH, TextAlignV, TextAutoResize, - TextCase, TextData, TextDecoration, TextStyle, VariableType, trim_num, + TextCase, TextData, TextDecoration, TextDirection, TextStyle, VariableType, trim_num, }; use serde_json::{Value, json}; diff --git a/crates/ui-egui/src/panels/typography/fields.rs b/crates/ui-egui/src/panels/typography/fields.rs index 20b9d8e90..c290e9893 100644 --- a/crates/ui-egui/src/panels/typography/fields.rs +++ b/crates/ui-egui/src/panels/typography/fields.rs @@ -4,8 +4,9 @@ use super::picker::{font_picker, remember_family}; use super::spacing::{SpacingField, commit_spacing, parse_letter_spacing, parse_line_height, spacing_field, spacing_input}; use super::{ Arc, DecorationLength, Document, FEATURES, FIELD_H, FieldEdit, FigApp, Icon, Id, Lead, LeadingTrim, ListStyle, MIXED, NodeId, SIZES, Sense, TABS, - TextAlignH, TextAlignV, TextAutoResize, TextCase, TextData, TextDecoration, TextStyle, Tokens, Ui, Value, VariableType, common, field_row, icons, - json, live, menu_item, menu_popup, regular, row, semibold, text_style_params, tr, tr_noop, trf, trim_num, uniform, vec2, widgets, + TextAlignH, TextAlignV, TextAutoResize, TextCase, TextData, TextDecoration, TextDirection, TextStyle, Tokens, Ui, Value, VariableType, common, + field_row, icons, json, live, menu_item, menu_popup, regular, row, semibold, text_style_params, tr, tr_noop, trf, trim_num, uniform, vec2, + widgets, }; /// The font rows: family, style and size, line height and letter spacing. @@ -397,6 +398,31 @@ fn type_settings( let style = ["auto", "balance", "pretty"].get(i).copied().unwrap_or("auto"); app.set_props(ids, json!({"wrapStyle": style})); } + // The paragraphs' base direction, once a right-to-left script is in the text or a direction + // is forced ("controls are available to override text direction per paragraph", Add + // right-to-left text). While editing: the selected paragraphs. + let has_direction = + |t: &TextData| figcraft_text::display::has_rtl(&t.characters) || t.paragraphs.iter().any(|p| p.direction != TextDirection::Auto); + if ids.iter().any(|i| doc.node(*i).and_then(|n| n.kind.text()).is_some_and(has_direction)) { + caption(ui, tr("Text direction")); + let dir = common(doc, ids, |n| { + n.kind.text().and_then(|t| { + let (a, b) = range.filter(|r| r.0 == n.id).map_or((0, t.char_count()), |(_, a, b)| (a, b)); + let (p0, p1) = t.para_span(a, b); + let first = t.para_list(p0).direction; + (p0..=p1).all(|p| t.para_list(p).direction == first).then_some(first as usize) + }) + }) + .flatten(); + let items = [ + (tr("Auto"), tr_noop("Auto: by the first letter with a direction")), + ("→", tr_noop("Left to right")), + ("←", tr_noop("Right to left")), + ]; + if let Some(i) = text_seg(ui, "direction", &items, dir, w) { + app.run("text.direction", json!({"ids": ids, "direction": (["auto", "ltr", "rtl"].get(i).copied().unwrap_or("auto"))})); + } + } let resize = common(doc, ids, |n| n.kind.text().map(|t| t.auto_resize)).flatten(); // Auto-height text with a line limit truncates too. let truncating = common(doc, ids, |n| n.kind.text().map(TextData::truncates)).flatten(); diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 541e7ab90..ac8f1c3f9 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -57,7 +57,8 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v Portuguese take the singular for 0 as well; Japanese, Korean, Chinese and Vietnamese have one form; CLDR's "many" for millions in French, Spanish and Portuguese reads as the plural). - **Script support in documents:** Unicode bidi with Arabic shaping and mirrored brackets in text - layers; right-to-left list markers and indents; right-to-left names in the layers panel, tabs + layers; a paragraph's base direction forced with Text ▸ Text direction (#1830); right-to-left + list markers and indents; right-to-left names in the layers panel, tabs and canvas labels (visual order, joined Arabic); inline IME composition with the candidate window at the caret; system-font fallback for scripts the UI fonts lack. Devanagari shapes through harfrust. No vertical text (Figma has none either). @@ -125,6 +126,7 @@ Hindi and Arabic. Traditional Chinese is not planned (no catalog; its users see | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | Documents: a paragraph's base direction can be forced left to right or right to left (Text ▸ Text direction, `text.direction`, `node.set textDirection`, the Type settings control, the `.fig` lines' `sourceDirectionality`), as Add right-to-left text says (#1830); detection stays the default. Four new UI strings (English only; other catalogs fall back). | | 2026-10-30 | minor | Bosnian (`bs`, Bosanski) draft catalog: every UI string (1,906), command label (629) and menu wording (31), machine-drafted in Latin script with ijekavian forms and marked as a draft awaiting native review. Bosnian plurals: one for 1, 21, 31… (not 11), few for 2–4, 22–24… (not 12–14), other for the rest. Grade and hours unchanged (Bosnian is not one of the twelve key languages) | | 2026-10-29 | minor | German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft. Nine existing translations corrected; keys, placeholders, coverage, grade and estimates unchanged | | 2026-10-28 | minor | Arabic draft: 1,857 UI entries, 620 command labels and 31 menu wordings, with count-neutral plurals. AI-assisted, native review pending. Desktop uses the existing Arabic fallback and bidi; web requires an embedded Arabic face. No panel mirroring or parity-grade increase claimed | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index cc0fc9db8..5092a08f2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -91,6 +91,7 @@ interaction feel not yet compared. | Boolean groups: clicked where the result is, double-click or Cmd/Ctrl-click into operands, live results while dragging or editing points, per-operand operations | done | a group past the path operations' caps (250 000 segments, 2 million possible crossings, 4 million segments swept over a fold) draws without its result, with a warning, and Flatten refuses it (#1104) | | Text: point, auto height, fixed; caret, words, lines, IME | done | Backspace or Delete at the start of a list item takes its marker and keeps its level, the paragraph starting where the item's text did ("delete the counter, but keep the same level of indentation", Create bulleted and numbered lists; `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests`); max lines on auto-width text keep it auto width, hugging up to that many lines and growing with its longest line ("Text resizing is set to auto height or auto width", Explore text properties; `text_behaviour_tests::max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines`); Alt+Enter while editing opens the link at the caret, web and mail links only (`text.openLink`; "press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma; `text_link_tests`); the font picker previews a family on the canvas while hovered (no undo step; Escape restores, #653) and Up/Down step through it (#352); a selection highlight after a line break starts at that line's start and an empty last line shows its mark (#665); carets step over whole emoji and accented letters; colour emoji draw from their colour tables (#300); IME composition replayed in tests as macOS sends it, not yet checked on a Mac (#747); CJK words by script run (no dictionary); vertical trim in Type settings; no spell check | | Text: wrap style (Auto, Balance, Pretty) | done | per text layer (`wrapStyle` on `node.set`, `text.wrapStyle`, the Type settings control under Vertical trim, inspect, CSS `text-wrap: balance` or `pretty`): Auto breaks greedily; Balance narrows each paragraph as far as it goes without another line, so its lines come out close to the same length (what browsers do for `text-wrap: balance`); Pretty keeps lines full and, when the last line is one word, narrows one of the last four lines just enough to give a word to the lines after it (Explore text properties: "Auto: Figma fits as many words as possible on each line before wrapping to the next", "Balance: Figma distributes text as evenly as possible across every line, so each line is close to the same length", "Pretty: Figma keeps each line full, but adjusts the last four lines to avoid an orphan"). Saved line breaks from a file still win. Not yet included: per-paragraph settings, text-style support and the `.fig` import/export mapping (#1827). Test: `text_behaviour_tests::balance_and_pretty_wrap_styles_break_lines_as_documented` | +| Text: direction override (Text ▸ Text direction) | done | per paragraph (`ParaList::direction`: auto, ltr, rtl): Text ▸ Text direction ▸ Auto / Left to right / Right to left and `text.direction {direction, ids?}` set the edited paragraphs while editing, else every paragraph of the selected texts; `node.set textDirection` the layer's (or the chars `start`/`end` name); the Type settings control appears once a right-to-left script is in the text or a direction is forced; inspect reports `textDirection` when the paragraphs agree and `lineDirections` otherwise; Dev Mode's CSS writes `direction: ltr` or `rtl` when every paragraph is forced the same way; `.fig` import and export carry each line's `sourceDirectionality`. Layout gives the paragraph its base level, so a forced right-to-left paragraph of Latin letters starts at the right, mirrors its list gutter and indent and orders its runs right to left, and a forced left-to-right paragraph of Hebrew the other way ("By default, Figma automatically handles text direction based on language detection. However, controls are available to override text direction per paragraph", "Go to Text > Text direction. Select Left to right or Right to left", Add right-to-left text). Not included: a direction in text styles (the article names none). Tests: `text_behaviour_tests::text_direction_is_forced_per_paragraph`, `fig::text_direction_tests` | | Text: superscript and subscript | done | `sups` / `subs` use the font's own glyphs where it has the feature and every letter or digit of the run gets one; otherwise the standard glyphs are drawn shrunk and raised or lowered by the font's OS/2 superscript and subscript metrics (0.65 em at 0.35 em up or 0.14 em down without them), and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says ("Figma draws a synthesized version by using the font's standard version of the character, shrinking it, and positioning it accordingly"; mixed glyphs "all update to the synthesized form for consistency"), #1828; tests `text::tests::superscript_native_or_synthesised_and_never_mixed`, `text_behaviour_tests::superscript_and_subscript_are_synthesised_without_glyphs_for_them` | | Eyedropper (I) | done | picks the colour seen under the pointer (opaque) into the selection's fill and the recent colours, one undo step (`fx_behaviour_tests`); with Cmd/Ctrl+Shift held it makes a colour style or variable of it instead, as the reference app's eyedropper does: a Create from color window asks which, its name (the next free "Color n") and a variable's collection (the file's first, or a new one made with it in the same undo step), and leaves the selection's fills alone (`eyedropper_create_tests`, `sampled_color_tests`) | | Comment (C), Shift+C to show/hide | done | local only | @@ -178,6 +179,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | M4, #1830: a paragraph's base direction can be forced (`TextDirection`: Auto, Ltr, Rtl on `ParaList`): Text ▸ Text direction ▸ Auto / Left to right / Right to left (`text.directionAuto` / `Ltr` / `Rtl`) and `text.direction {direction, ids?}` set the edited paragraphs while editing, else the layer's; `node.set textDirection`; the Type settings control once a right-to-left script is in the text; inspect `textDirection` / `lineDirections`; CSS `direction`; `.fig` lines' `sourceDirectionality` in and out. Layout gives each paragraph its base level (`Bidi::of` runs the algorithm per paragraph, as it starts over at each). Before, direction came from the letters only ("controls are available to override text direction per paragraph", Add right-to-left text). Tests: `text_behaviour_tests::text_direction_is_forced_per_paragraph`, `fig::text_direction_tests::a_lines_source_directionality_is_its_paragraphs_direction_both_ways`. | | 2026-11-02 | patch | M8, #1875: a click with the Bend tool on a sharp point between two segments gives it handles along the line between its neighbours, a third of the way to each ("Click on a point or path where you want to add a curve", Edit vector layers); a click on a curved point still makes it sharp, a drag still sets the handles by hand, an endpoint is left alone. Between a handle's end and a point both within reach of the pointer, the nearer one on the page is hit (the handle on a tie), so a short path's point (its handles a few pixels long) can be clicked again. Before, only a drag curved a point, and a short one left two tiny handles in its direction. Tests: `vectoredit::tests::short_handles_leave_their_point_clickable`, `vectoredit::tests::a_bend_click_curves_a_sharp_point_between_its_neighbours`, `bend_tool_smooths_and_sharpens_points`. Numbers unchanged. | | 2026-11-02 | minor | M4, #1827: wrap style on a text layer (`WrapStyle`: Auto, Balance, Pretty): Balance re-breaks each paragraph at the narrowest width that keeps its line count (bisection over the greedy breaker, as browsers balance), Pretty narrows one of the last four lines just enough so the last line isn't one word; `text.wrapStyle`, `node.set wrapStyle` (`textWrap` too), inspect `wrapStyle`, Dev Mode CSS `text-wrap` (Tailwind `text-balance` / `text-pretty`), the Type settings control under Vertical trim. Per-paragraph settings, text-style support and the `.fig` import/export mapping stay open. Test: `text_behaviour_tests::balance_and_pretty_wrap_styles_break_lines_as_documented`. | | 2026-11-02 | patch | M4: Backspace or Delete at the start of a list item takes its marker and keeps its level ("Use Backspace or Delete at the beginning of a list item to delete the counter, but keep the same level of indentation", Create bulleted and numbered lists): a plain paragraph may now carry a list level, and the text layout starts it where that level's item text starts (the gutters stay even when no list is left). Backspace used to drop the level too, and Delete at an item's start deleted the next character. Tab on such a paragraph types a tab, as outside a list. Tests: `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests::a_plain_paragraph_at_a_list_level_starts_where_the_items_text_does` | From c16c3676c27fdf199fea1598c0f16228318af6d5 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 5 Nov 2026 03:46:28 -0500 Subject: [PATCH 082/102] M4: text direction: CSS keeps Left beside a forced rtl, paragraph arrays read to the paragraph count, the empty last paragraph keeps its direction (#1830) From review: `text-align: left` beside `direction: rtl` (Left is absolute on the canvas); the REST import reads the four parallel paragraph arrays up to the paragraph count, not the 256-entry list limit; `rtl_para` gets an entry for the position after the last char so an empty last paragraph keeps its forced direction; the localization status line. Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/dev/codegen/css.rs | 8 +++++++- crates/engine/src/text_behaviour_tests.rs | 7 +++++++ crates/format/src/rest/text.rs | 11 ++++++----- crates/text/src/layout.rs | 15 +++++++++++++-- crates/text/src/tests.rs | 12 +++++++++--- docs/localization-parity.md | 2 +- docs/ui-parity.md | 2 +- 7 files changed, 44 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/dev/codegen/css.rs b/crates/engine/src/dev/codegen/css.rs index c772367fd..d521674e9 100644 --- a/crates/engine/src/dev/codegen/css.rs +++ b/crates/engine/src/dev/codegen/css.rs @@ -311,7 +311,13 @@ fn text_decls(doc: &Document, n: &Node, tx: &figcraft_doc::TextData, t: &mut Tok let dir = tx.paragraphs.first().map(|p| p.direction).filter(|d| tx.paragraphs.iter().all(|p| p.direction == *d)); match dir { Some(figcraft_doc::TextDirection::Ltr) => put("direction", "ltr".into()), - Some(figcraft_doc::TextDirection::Rtl) => put("direction", "rtl".into()), + Some(figcraft_doc::TextDirection::Rtl) => { + put("direction", "rtl".into()); + // Left alignment is absolute on the canvas; `start` would be the right edge here. + if tx.align_h == TextAlignH::Left { + put("text-align", "left".into()); + } + } _ => {} } match s.case { diff --git a/crates/engine/src/text_behaviour_tests.rs b/crates/engine/src/text_behaviour_tests.rs index 6db19a1cc..025b3bc2b 100644 --- a/crates/engine/src/text_behaviour_tests.rs +++ b/crates/engine/src/text_behaviour_tests.rs @@ -393,6 +393,7 @@ fn text_direction_is_forced_per_paragraph() { assert_eq!(inspect(&s)["textDirection"], json!("rtl")); let css = |s: &mut Session| s.execute("inspect.code", &json!({"id": t})).unwrap()["code"].as_str().unwrap().to_string(); assert!(css(&mut s).contains("direction: rtl;"), "{}", css(&mut s)); + assert!(css(&mut s).contains("text-align: left;"), "Left stays the left edge, which `start` would not be: {}", css(&mut s)); s.execute("node.set", &json!({"id": t, "props": {"textDirection": "ltr"}})).unwrap(); assert_eq!(rtl(&s), [false, false, false]); assert_eq!(inspect(&s)["textDirection"], json!("ltr")); @@ -413,6 +414,12 @@ fn text_direction_is_forced_per_paragraph() { s.execute("text.edit.insert", &json!({"text": "\n"})).unwrap(); s.execute("text.edit.end", &json!({})).unwrap(); assert_eq!(rtl(&s), [false, true, true, false]); + // An empty last paragraph (after a final newline) keeps the direction forced on it. + s.execute("node.set", &json!({"id": t, "props": {"characters": "abc\n", "textDirection": "auto"}})).unwrap(); + s.execute("text.edit.begin", &json!({"id": t, "caret": 4})).unwrap(); + s.execute("text.directionRtl", &json!({})).unwrap(); + s.execute("text.edit.end", &json!({})).unwrap(); + assert_eq!(rtl(&s), [false, true], "the empty last line runs right to left"); // A direction the document has words for; junk is refused. s.execute("node.set", &json!({"id": t, "props": {"characters": "\u{05E9}\u{05DC}\u{05D5}\u{05DD} abc", "textDirection": "auto"}})).unwrap(); assert_eq!(rtl(&s), [true], "Hebrew first: right to left by detection"); diff --git a/crates/format/src/rest/text.rs b/crates/format/src/rest/text.rs index ca5c51d15..391fa4e1c 100644 --- a/crates/format/src/rest/text.rs +++ b/crates/format/src/rest/text.rs @@ -10,7 +10,7 @@ use figcraft_doc::{ use serde_json::Value; use super::Ctx; -use super::props::{flag, len, list, num, paints, text}; +use super::props::{flag, len, num, paints, text}; /// Most characters read from one text node. const MAX_CHARS: usize = 1 << 20; @@ -259,10 +259,11 @@ fn runs(cx: &mut Ctx, v: &Value, td: &TextData) -> Vec { /// Each paragraph's list type, nesting level, start number and base direction from `lineTypes`, /// `lineIndentations` and (from `.fig` files) `listStartOffsets` and `lineDirections`. fn lists(v: &Value, td: &mut TextData) { - let types = list(v, "lineTypes"); - let indents = list(v, "lineIndentations"); - let starts = list(v, "listStartOffsets"); - let dirs = list(v, "lineDirections"); + // One entry per paragraph: read up to the paragraph count (bounded by the text's size), not the + // general list limit, so a long text keeps every paragraph's settings. + let n = td.paragraph_count(); + let column = |k: &str| v.get(k).and_then(Value::as_array).map(|a| a.get(..a.len().min(n)).unwrap_or_default()).unwrap_or_default(); + let (types, indents, starts, dirs) = (column("lineTypes"), column("lineIndentations"), column("listStartOffsets"), column("lineDirections")); td.paragraphs = (0..types.len().max(dirs.len())) .map(|i| ParaList { list: match types.get(i).and_then(Value::as_str) { diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 732e59ec7..bbf498a96 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -265,7 +265,8 @@ impl Item { } } -/// Bidi embedding levels per char, and whether each char's paragraph runs right to left. +/// Bidi embedding levels per char, and whether each char's paragraph runs right to left; +/// `rtl_para` has one more entry, for the position after the last char (an empty last paragraph). pub(crate) struct Bidi { pub(crate) levels: Vec, pub(crate) rtl_para: Vec, @@ -296,6 +297,15 @@ impl Bidi { rtl_para.push(paras.peek().is_some_and(|q| q.level.is_rtl())); } } + // The position after the last char: in the last paragraph, or in the empty one after a + // final newline (its forced direction, else left to right), so an empty last line knows + // its direction too. + let after = if text.is_empty() || text.ends_with('\n') { + forced.get(text.matches('\n').count()).copied().flatten().unwrap_or(false) + } else { + rtl_para.last().copied().unwrap_or(false) + }; + rtl_para.push(after); Some(Bidi { levels, rtl_para }) } } @@ -1271,7 +1281,8 @@ pub fn layout(text: &TextData, box_width: Option, box_height: Option) // Letter spacing separates glyphs: none after the line's last visible one. let end_spacing = vis_end.checked_sub(1).filter(|i| *i >= *s).and_then(|i| items.get(i)).map_or(0.0, |it| it.spacing); let width: f64 = items.get(*s..vis_end).unwrap_or(&[]).iter().map(|it| it.adv).sum::() - end_spacing; - let first_char = items.get(*s).map(|it| it.char_start).unwrap_or(0); + // An empty last line has no item: the position after the last char is its paragraph's. + let first_char = items.get(*s).map_or(chars.len(), |it| it.char_start); let rtl_line = rtl_para_at(first_char); let line_indent = line_indent_of(*para, para_start_line, first_char); // Hanging punctuation at the line's edges (the visible text's first and last chars). diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index e38963855..0469a0cfc 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -423,17 +423,23 @@ fn forced_direction_sets_a_paragraphs_base_level() { // Latin letters forced right to left: an embedded left-to-right run (level 2) in a // right-to-left paragraph; the next paragraph, unforced, stays left to right. let b = Bidi::of("ab\ncd", &[Some(true), None]).unwrap(); - assert_eq!(b.rtl_para, [true, true, true, false, false]); + assert_eq!(b.rtl_para, [true, true, true, false, false, false], "and the position after the last char"); assert_eq!((b.levels.get(..2), b.levels.get(3..)), (Some(&[2, 2][..]), Some(&[0, 0][..]))); // Hebrew forced left to right: a right-to-left run (level 1) in a left-to-right paragraph. let b = Bidi::of("\u{5D0}\u{5D1}", &[Some(false)]).unwrap(); - assert_eq!(b.rtl_para, [false, false]); + assert_eq!(b.rtl_para, [false, false, false]); assert_eq!(b.levels, [1, 1]); // Forcing what the letters already say changes nothing; a paragraph past the forced list is // detected. let b = Bidi::of("\u{5D0}\n\u{5D1}", &[Some(true)]).unwrap(); - assert_eq!(b.rtl_para, [true, true, true]); + assert_eq!(b.rtl_para, [true, true, true, true]); assert_eq!((b.levels.first(), b.levels.last()), (Some(&1), Some(&1))); + // The empty paragraph after a final newline has its own direction: forced, else left to right. + let b = Bidi::of("ab\n", &[None, Some(true)]).unwrap(); + assert_eq!(b.rtl_para, [false, false, false, true]); + let b = Bidi::of("\u{5D0}\n", &[]).unwrap(); + assert_eq!(b.rtl_para, [true, true, false]); + assert_eq!(Bidi::of("", &[Some(true)]).map(|b| b.rtl_para), Some(vec![true])); } /// The x of the glyph for char `i`. diff --git a/docs/localization-parity.md b/docs/localization-parity.md index ac8f1c3f9..3a887c576 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (documents: a paragraph's base direction can be forced with Text ▸ Text direction, as Add right-to-left text says (#1830); Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7) FigCraft's interface has a localization layer with an English catalog, a Russian catalog reviewed by a native speaker, and Spanish (with a Latin American overlay), French, German, Brazilian diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 5092a08f2..d551c65d1 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -91,7 +91,7 @@ interaction feel not yet compared. | Boolean groups: clicked where the result is, double-click or Cmd/Ctrl-click into operands, live results while dragging or editing points, per-operand operations | done | a group past the path operations' caps (250 000 segments, 2 million possible crossings, 4 million segments swept over a fold) draws without its result, with a warning, and Flatten refuses it (#1104) | | Text: point, auto height, fixed; caret, words, lines, IME | done | Backspace or Delete at the start of a list item takes its marker and keeps its level, the paragraph starting where the item's text did ("delete the counter, but keep the same level of indentation", Create bulleted and numbered lists; `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests`); max lines on auto-width text keep it auto width, hugging up to that many lines and growing with its longest line ("Text resizing is set to auto height or auto width", Explore text properties; `text_behaviour_tests::max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines`); Alt+Enter while editing opens the link at the caret, web and mail links only (`text.openLink`; "press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma; `text_link_tests`); the font picker previews a family on the canvas while hovered (no undo step; Escape restores, #653) and Up/Down step through it (#352); a selection highlight after a line break starts at that line's start and an empty last line shows its mark (#665); carets step over whole emoji and accented letters; colour emoji draw from their colour tables (#300); IME composition replayed in tests as macOS sends it, not yet checked on a Mac (#747); CJK words by script run (no dictionary); vertical trim in Type settings; no spell check | | Text: wrap style (Auto, Balance, Pretty) | done | per text layer (`wrapStyle` on `node.set`, `text.wrapStyle`, the Type settings control under Vertical trim, inspect, CSS `text-wrap: balance` or `pretty`): Auto breaks greedily; Balance narrows each paragraph as far as it goes without another line, so its lines come out close to the same length (what browsers do for `text-wrap: balance`); Pretty keeps lines full and, when the last line is one word, narrows one of the last four lines just enough to give a word to the lines after it (Explore text properties: "Auto: Figma fits as many words as possible on each line before wrapping to the next", "Balance: Figma distributes text as evenly as possible across every line, so each line is close to the same length", "Pretty: Figma keeps each line full, but adjusts the last four lines to avoid an orphan"). Saved line breaks from a file still win. Not yet included: per-paragraph settings, text-style support and the `.fig` import/export mapping (#1827). Test: `text_behaviour_tests::balance_and_pretty_wrap_styles_break_lines_as_documented` | -| Text: direction override (Text ▸ Text direction) | done | per paragraph (`ParaList::direction`: auto, ltr, rtl): Text ▸ Text direction ▸ Auto / Left to right / Right to left and `text.direction {direction, ids?}` set the edited paragraphs while editing, else every paragraph of the selected texts; `node.set textDirection` the layer's (or the chars `start`/`end` name); the Type settings control appears once a right-to-left script is in the text or a direction is forced; inspect reports `textDirection` when the paragraphs agree and `lineDirections` otherwise; Dev Mode's CSS writes `direction: ltr` or `rtl` when every paragraph is forced the same way; `.fig` import and export carry each line's `sourceDirectionality`. Layout gives the paragraph its base level, so a forced right-to-left paragraph of Latin letters starts at the right, mirrors its list gutter and indent and orders its runs right to left, and a forced left-to-right paragraph of Hebrew the other way ("By default, Figma automatically handles text direction based on language detection. However, controls are available to override text direction per paragraph", "Go to Text > Text direction. Select Left to right or Right to left", Add right-to-left text). Not included: a direction in text styles (the article names none). Tests: `text_behaviour_tests::text_direction_is_forced_per_paragraph`, `fig::text_direction_tests` | +| Text: direction override (Text ▸ Text direction) | done | per paragraph (`ParaList::direction`: auto, ltr, rtl): Text ▸ Text direction ▸ Auto / Left to right / Right to left and `text.direction {direction, ids?}` set the edited paragraphs while editing, else every paragraph of the selected texts; `node.set textDirection` the layer's (or the chars `start`/`end` name); the Type settings control appears once a right-to-left script is in the text or a direction is forced; inspect reports `textDirection` when the paragraphs agree and `lineDirections` otherwise; Dev Mode's CSS writes `direction: ltr` or `rtl` when every paragraph is forced the same way (with `text-align: left` beside `rtl`, as Left is absolute on the canvas); `.fig` import and export carry each line's `sourceDirectionality`, read up to the paragraph count. Layout gives the paragraph its base level, so a forced right-to-left paragraph of Latin letters starts at the right, mirrors its list gutter and indent and orders its runs right to left, and a forced left-to-right paragraph of Hebrew the other way ("By default, Figma automatically handles text direction based on language detection. However, controls are available to override text direction per paragraph", "Go to Text > Text direction. Select Left to right or Right to left", Add right-to-left text). Not included: a direction in text styles (the article names none). Tests: `text_behaviour_tests::text_direction_is_forced_per_paragraph`, `fig::text_direction_tests` | | Text: superscript and subscript | done | `sups` / `subs` use the font's own glyphs where it has the feature and every letter or digit of the run gets one; otherwise the standard glyphs are drawn shrunk and raised or lowered by the font's OS/2 superscript and subscript metrics (0.65 em at 0.35 em up or 0.14 em down without them), and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says ("Figma draws a synthesized version by using the font's standard version of the character, shrinking it, and positioning it accordingly"; mixed glyphs "all update to the synthesized form for consistency"), #1828; tests `text::tests::superscript_native_or_synthesised_and_never_mixed`, `text_behaviour_tests::superscript_and_subscript_are_synthesised_without_glyphs_for_them` | | Eyedropper (I) | done | picks the colour seen under the pointer (opaque) into the selection's fill and the recent colours, one undo step (`fx_behaviour_tests`); with Cmd/Ctrl+Shift held it makes a colour style or variable of it instead, as the reference app's eyedropper does: a Create from color window asks which, its name (the next free "Color n") and a variable's collection (the file's first, or a new one made with it in the same undo step), and leaves the selection's fills alone (`eyedropper_create_tests`, `sampled_color_tests`) | | Comment (C), Shift+C to show/hide | done | local only | From facc2a2178afd83ebe78f6b5bb7ca6207cc6b373 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 5 Nov 2026 08:50:45 -0500 Subject: [PATCH 083/102] M10: the UI takes a system face for Ethiopic, the Indic scripts and the other scripts its fonts lack (#2014) A String variable's Amharic value drew as boxes in the panels: `bidi::script_fallbacks` sampled Hebrew and Arabic only. It now samples one letter of each of 18 scripts against the system families that draw them on Windows, macOS and Linux; `theme::system_fallbacks` takes the first installed one per script, once. Test: `bidi::tests::other_scripts_take_an_installed_system_face`; localization doc and ROADMAP updated. Co-Authored-By: Claude Fable 5.1 --- ROADMAP.md | 1 + crates/ui-egui/src/bidi.rs | 90 ++++++++++++++++++++++++++------ crates/ui-egui/src/bidi/tests.rs | 49 +++++++++++++++++ crates/ui-egui/src/theme.rs | 3 +- docs/localization-parity.md | 10 ++-- 5 files changed, 132 insertions(+), 21 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c2aa86c22..09803e5e4 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -132,6 +132,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). ## Progress log +- **2026-11-05** · M10, #2014: the UI takes a system face for Ethiopic, the Indic scripts, Sinhala, Thai, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic (`bidi::script_fallbacks`: one sample letter per script, the system's families for each), so a layer name or a String variable's Amharic value draws in the panels instead of boxes. Test: `bidi::tests::other_scripts_take_an_installed_system_face`. - **2026-10-30**: M8, #1125: damaged `trak` size-table offsets are checked instead of wrapping on 32-bit targets, and an incomplete normal track is dropped entirely, never returned in part. Font indexing makes its existing bounds explicit, preserving later faces and sparse name-table reads. Synthetic regression tests in `fontdb_tests.rs`. Numbers unchanged. - **2026-10-30** · Text style dedupe is O(spans) (M8, #1102): `shape_text` deduped spans into styles by a scan over the styles already collected — O(spans × styles), so a styled text's dedupe grew with the square of its runs (a synthetic 50k-run text with 100 alternating styles spent 7.7 ms in it). Now the last two styles again (spans run in blocks), then buckets keyed by a cheap fingerprint (family and style bytes, size bits with −0.0 folded, the enums, fill count and solid colours), each bucket resolved with the full equality: the result is the scan's, never worse than it, and O(spans) when names and sizes differ (the same synthetic text: 2.6 ms). The font-db write lock is untouched: `find()` loads faces, which needs the write. `layout_dedupe_tests`. Numbers unchanged. - **2026-10-29** · M10: correct nine German labels in `de.toml`: gradient stops use Verlaufsstopp, OpenType ss01–ss05 use Stilsatz, and the Home-screen preference names the Startbildschirm consistently in the UI and Actions palette. This is a partial terminology pass; German remains a draft awaiting a full native-speaker review and maintainer approval. Numbers unchanged. diff --git a/crates/ui-egui/src/bidi.rs b/crates/ui-egui/src/bidi.rs index dffd4955c..f448f1b53 100644 --- a/crates/ui-egui/src/bidi.rs +++ b/crates/ui-egui/src/bidi.rs @@ -48,25 +48,81 @@ pub fn single_line(ui: &mut Ui, id: Id, text: &mut String, font: FontId, width: .response } +/// One letter per script the UI's own fonts may lack: Hebrew, Arabic, Ethiopic, Devanagari, +/// Bengali, Gurmukhi, Gujarati, Tamil, Telugu, Kannada, Malayalam, Sinhala, Thai, Lao, Myanmar, +/// Khmer, Armenian and Georgian. egui's shaper selects the joined contextual forms itself. +pub(crate) const SCRIPT_SAMPLES: [char; 18] = [ + '\u{05D0}', '\u{0628}', '\u{1200}', '\u{0915}', '\u{0995}', '\u{0A15}', '\u{0A95}', '\u{0B95}', '\u{0C15}', '\u{0C95}', '\u{0D15}', '\u{0D9A}', + '\u{0E01}', '\u{0E81}', '\u{1000}', '\u{1780}', '\u{0531}', '\u{10D0}', +]; + +/// System families that draw those scripts, in order of preference: the first installed one that +/// has a script's letter is taken, so a family covering several scripts (Segoe UI, Nirmala UI, +/// Kohinoor, Noto Sans) joins once. Windows, macOS and the common Linux fonts for each script. +pub(crate) const SCRIPT_FAMILIES: [&str; 50] = [ + // Hebrew and Arabic. + "Segoe UI", + "Arial", + "Tahoma", + "Noto Sans Hebrew", + "Noto Sans Arabic", + "Arial Hebrew", + "Geeza Pro", + "Lucida Grande", + "DejaVu Sans", + "FreeSans", + "Noto Sans", + // Ethiopic (#2014). + "Ebrima", + "Nyala", + "Kefa", + "Noto Sans Ethiopic", + "Abyssinica SIL", + // The Indic scripts and Sinhala. + "Nirmala UI", + "Kohinoor Devanagari", + "Kohinoor Bangla", + "Kohinoor Gujarati", + "Kohinoor Telugu", + "Gurmukhi MN", + "Tamil Sangam MN", + "Kannada Sangam MN", + "Malayalam Sangam MN", + "Sinhala Sangam MN", + "Noto Sans Devanagari", + "Noto Sans Bengali", + "Noto Sans Gurmukhi", + "Noto Sans Gujarati", + "Noto Sans Tamil", + "Noto Sans Telugu", + "Noto Sans Kannada", + "Noto Sans Malayalam", + "Noto Sans Sinhala", + "Lohit Devanagari", + // Thai, Lao, Myanmar and Khmer. + "Leelawadee UI", + "Thonburi", + "Lao Sangam MN", + "Myanmar Text", + "Myanmar Sangam MN", + "Khmer Sangam MN", + "Noto Sans Thai", + "Noto Sans Lao", + "Noto Sans Myanmar", + "Noto Sans Khmer", + // Armenian and Georgian. + "Sylfaen", + "Mshtakan", + "Noto Sans Armenian", + "Noto Sans Georgian", +]; + /// Faces the UI adds for scripts its own fonts lack (desktop: from the system), as egui font data; -/// `taken` as for [`crate::theme::system_fallbacks`]. +/// `taken` as for [`crate::theme::system_fallbacks`]. Hebrew and Arabic names were covered first; +/// Ethiopic and the other scripts in [`SCRIPT_SAMPLES`] drew as boxes in the panels (a String +/// variable's Amharic value, #2014) until the system face for each was taken too. pub fn script_fallbacks(have: &dyn Fn(char) -> bool, taken: &mut Vec>) -> Vec<(String, egui::FontData)> { - // Hebrew and Arabic letters; egui's shaper selects the joined contextual forms itself. - const SAMPLES: [char; 2] = ['\u{05D0}', '\u{0628}']; - const FAMILIES: [&str; 11] = [ - "Segoe UI", - "Arial", - "Tahoma", - "Noto Sans Hebrew", - "Noto Sans Arabic", - "Arial Hebrew", - "Geeza Pro", - "Lucida Grande", - "DejaVu Sans", - "FreeSans", - "Noto Sans", - ]; - crate::theme::system_fallbacks(SAMPLES, &FAMILIES, have, taken) + crate::theme::system_fallbacks(SCRIPT_SAMPLES, &SCRIPT_FAMILIES, have, taken) } #[cfg(test)] diff --git a/crates/ui-egui/src/bidi/tests.rs b/crates/ui-egui/src/bidi/tests.rs index 22f59817b..9f42f4a18 100644 --- a/crates/ui-egui/src/bidi/tests.rs +++ b/crates/ui-egui/src/bidi/tests.rs @@ -310,3 +310,52 @@ fn clicks_place_the_logical_caret_by_what_is_shown() { run(vec![Event::Text("א".into())], &mut text, &mut rect); assert_eq!(text, "שלוםא"); } + +/// Scripts beyond Hebrew and Arabic (#2014): a String variable's Amharic value drew as boxes +/// because the UI took system faces for two scripts only. Now every script in `SCRIPT_SAMPLES` +/// with an installed face gets one, and the UI's fonts then have its glyphs. A machine without a +/// face for a script skips that script (CI has few fonts); a face the UI's own fonts cover is not +/// taken twice. +#[test] +fn other_scripts_take_an_installed_system_face() { + figcraft_text::scan_system_fonts(); + let installed = |c: char| figcraft_text::face_with_char(c, &crate::bidi::SCRIPT_FAMILIES).is_some(); + let mut taken = Vec::new(); + let added = crate::bidi::script_fallbacks(&|_| false, &mut taken); + let scripts = [('\u{1200}', "Ethiopic"), ('\u{0915}', "Devanagari"), ('\u{0B95}', "Tamil"), ('\u{1000}', "Myanmar"), ('\u{0531}', "Armenian")]; + let mut checked = 0; + for (c, script) in scripts { + if !installed(c) { + eprintln!("no {script} face on this system; skipping"); + continue; + } + let families: Vec<&str> = taken.iter().map(|f| f.family.as_str()).collect(); + assert!(taken.iter().any(|f| f.has_char(c)), "a face for {script} is taken: {families:?}"); + checked += 1; + } + // A face that several scripts share is added once, under its system key. + let keys: Vec<&str> = added.iter().map(|(k, _)| k.as_str()).collect(); + assert_eq!(keys.len(), taken.len(), "{keys:?}"); + assert!(keys.iter().all(|k| k.starts_with("system-")), "{keys:?}"); + let mut seen = keys.clone(); + seen.sort_unstable(); + seen.dedup(); + assert_eq!(seen.len(), keys.len(), "no face twice: {keys:?}"); + // Nothing is taken for a script the UI's own fonts draw. + assert!(crate::bidi::script_fallbacks(&|_| true, &mut Vec::new()).is_empty()); + if checked == 0 { + eprintln!("no face for any of the sampled scripts on this system; the UI font check was not run"); + return; + } + // Through the whole font setup: the UI draws the letters of every script it found a face for. + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx, true, 0); + ctx.run_ui(RawInput::default(), |_| {}).textures_delta.clear(); + ctx.fonts_mut(|f| { + for (c, script) in scripts { + if installed(c) { + assert!(f.has_glyph(®ular(11.0), c), "the UI fonts draw {script} ({c:?})"); + } + } + }); +} diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 200dd72bc..02167a45a 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -271,7 +271,8 @@ pub fn on_dark(ui: &mut egui::Ui, f: impl FnOnce(&mut egui::Ui) -> R) -> R { /// UI fonts: Inter and the Archivo wordmark (from the craft-fonts build input) when present; /// otherwise egui's defaults. With -/// `system`, also system faces for scripts those lack (Hebrew, joined Arabic) so names in them show, +/// `system`, also system faces for scripts those lack (Hebrew, joined Arabic, Ethiopic, the Indic +/// scripts and the others [`crate::bidi::script_fallbacks`] names) so names in them show, /// and faces for the CJK scripts in `cjk` ([`crate::cjk`]). /// /// The craft-fonts set embeds Noto Sans Arabic and Noto Sans Hebrew; with `system` off those diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 541e7ab90..7cfc36f7b 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** patch (the UI takes a system face for Ethiopic, the Indic scripts, Sinhala, Thai, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value no longer draws as boxes (#2014); Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7) FigCraft's interface has a localization layer with an English catalog, a Russian catalog reviewed by a native speaker, and Spanish (with a Latin American overlay), French, German, Brazilian @@ -59,8 +59,11 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v - **Script support in documents:** Unicode bidi with Arabic shaping and mirrored brackets in text layers; right-to-left list markers and indents; right-to-left names in the layers panel, tabs and canvas labels (visual order, joined Arabic); inline IME composition with the candidate window - at the caret; system-font fallback for scripts the UI fonts lack. Devanagari shapes through - harfrust. No vertical text (Figma has none either). + at the caret; system-font fallback for scripts the UI fonts lack: Hebrew and Arabic, and since + #2014 Ethiopic, the Indic scripts, Sinhala, Thai, Lao, Myanmar, Khmer, Armenian and Georgian, + so a layer name or a String variable's value in them draws in the panels when the system has a + face (`crates/ui-egui/src/bidi.rs`, `SCRIPT_SAMPLES` and `SCRIPT_FAMILIES`). Devanagari shapes + through harfrust. No vertical text (Figma has none either). - **Script support in the UI:** menus widen to their longest label; dropdowns, the two-column labels of the right panel and the home screen's cards keep a long translation on one line with an ellipsis and show it in full on hover (checked in German, the longest); no mirrored @@ -125,6 +128,7 @@ Hindi and Arabic. Traditional Chinese is not planned (no catalog; its users see | Date | Change | Summary | |---|---|---| +| 2026-11-05 | patch | #2014: the panels drew a String variable's Amharic value as boxes: the UI took a system face for Hebrew and Arabic only. `bidi::script_fallbacks` now samples one letter of each of 18 scripts (Ethiopic, the Indic scripts, Sinhala, Thai, Lao, Myanmar, Khmer, Armenian, Georgian as well) against the system's families for each (Windows, macOS, the common Linux fonts), the first installed one that draws the letter taken once. Test: `bidi::tests::other_scripts_take_an_installed_system_face` (skips scripts the machine has no face for). | | 2026-10-30 | minor | Bosnian (`bs`, Bosanski) draft catalog: every UI string (1,906), command label (629) and menu wording (31), machine-drafted in Latin script with ijekavian forms and marked as a draft awaiting native review. Bosnian plurals: one for 1, 21, 31… (not 11), few for 2–4, 22–24… (not 12–14), other for the rest. Grade and hours unchanged (Bosnian is not one of the twelve key languages) | | 2026-10-29 | minor | German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft. Nine existing translations corrected; keys, placeholders, coverage, grade and estimates unchanged | | 2026-10-28 | minor | Arabic draft: 1,857 UI entries, 620 command labels and 31 menu wordings, with count-neutral plurals. AI-assisted, native review pending. Desktop uses the existing Arabic fallback and bidi; web requires an embedded Arabic face. No panel mirroring or parity-grade increase claimed | From 2c92a169441b245bc0dcd1c565e6eb468fa1f09e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 5 Nov 2026 09:43:47 -0500 Subject: [PATCH 084/102] M10: UI script fallbacks leave Bengali and Thai to the CJK path; Hindi row and ROADMAP status (#2014) From review: crate::cjk picks the Bengali and Thai faces after this list in its own order, so the two scripts come out of SCRIPT_SAMPLES and their families out of SCRIPT_FAMILIES; the Hindi row says the desktop UI takes an installed Devanagari face; the ROADMAP status line and Localization row carry the change. Co-Authored-By: Claude Fable 5.1 --- ROADMAP.md | 6 +++--- crates/ui-egui/src/bidi.rs | 22 ++++++++++------------ docs/localization-parity.md | 17 +++++++++-------- 3 files changed, 22 insertions(+), 23 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 09803e5e4..8eb0d9301 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** patch (the desktop UI takes a system face for Ethiopic, the Indic scripts, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -63,7 +63,7 @@ native speakers' reviews of the nine language drafts need people. | Stability | 55% (damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, #1125) | 20–40 | [gaps](docs/gaps.md) | | Performance | 60% | 30–60 | [hardware-parity](docs/hardware-parity.md) | | Hardware | 60% | 10–21 | [hardware-parity](docs/hardware-parity.md) | -| Localization | 39% (layer; English; Russian and Turkish reviewed by native speakers; Spanish with a Latin American overlay, French, German, Brazilian Portuguese, Japanese, Korean, Simplified Chinese, Indonesian and Czech drafts; CJK UI fonts); Arabic draft: 2,508 entries, native review and panel mirroring pending | 29–51 | [localization-parity](docs/localization-parity.md) | +| Localization | 39% (layer; English; Russian and Turkish reviewed by native speakers; Spanish with a Latin American overlay, French, German, Brazilian Portuguese, Japanese, Korean, Simplified Chinese, Indonesian and Czech drafts; CJK UI fonts; the desktop UI takes a system face for Ethiopic, the Indic scripts, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian, #2014); Arabic draft: 2,508 entries, native review and panel mirroring pending | 29–51 | [localization-parity](docs/localization-parity.md) | | Platforms | 75% | 10–20 | [hardware-parity](docs/hardware-parity.md) | | Ecosystem / plugins | 40% (own WASM plugins with panels, settings and widgets that take clicks, text and a property menu; a self-hosted plugin directory) | 6–22 | [gaps](docs/gaps.md) | | AI features | 0% | 30–60 | [gaps](docs/gaps.md) | @@ -132,7 +132,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). ## Progress log -- **2026-11-05** · M10, #2014: the UI takes a system face for Ethiopic, the Indic scripts, Sinhala, Thai, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic (`bidi::script_fallbacks`: one sample letter per script, the system's families for each), so a layer name or a String variable's Amharic value draws in the panels instead of boxes. Test: `bidi::tests::other_scripts_take_an_installed_system_face`. +- **2026-11-05** · M10, #2014: the desktop UI takes a system face for Ethiopic, the Indic scripts, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic (`bidi::script_fallbacks`: one sample letter per script, the system's families for each; Bengali and Thai keep `crate::cjk`'s choice), so a layer name or a String variable's Amharic value draws in the panels instead of boxes. Test: `bidi::tests::other_scripts_take_an_installed_system_face`. - **2026-10-30**: M8, #1125: damaged `trak` size-table offsets are checked instead of wrapping on 32-bit targets, and an incomplete normal track is dropped entirely, never returned in part. Font indexing makes its existing bounds explicit, preserving later faces and sparse name-table reads. Synthetic regression tests in `fontdb_tests.rs`. Numbers unchanged. - **2026-10-30** · Text style dedupe is O(spans) (M8, #1102): `shape_text` deduped spans into styles by a scan over the styles already collected — O(spans × styles), so a styled text's dedupe grew with the square of its runs (a synthetic 50k-run text with 100 alternating styles spent 7.7 ms in it). Now the last two styles again (spans run in blocks), then buckets keyed by a cheap fingerprint (family and style bytes, size bits with −0.0 folded, the enums, fill count and solid colours), each bucket resolved with the full equality: the result is the scan's, never worse than it, and O(spans) when names and sizes differ (the same synthetic text: 2.6 ms). The font-db write lock is untouched: `find()` loads faces, which needs the write. `layout_dedupe_tests`. Numbers unchanged. - **2026-10-29** · M10: correct nine German labels in `de.toml`: gradient stops use Verlaufsstopp, OpenType ss01–ss05 use Stilsatz, and the Home-screen preference names the Startbildschirm consistently in the UI and Actions palette. This is a partial terminology pass; German remains a draft awaiting a full native-speaker review and maintainer approval. Numbers unchanged. diff --git a/crates/ui-egui/src/bidi.rs b/crates/ui-egui/src/bidi.rs index f448f1b53..b430686c3 100644 --- a/crates/ui-egui/src/bidi.rs +++ b/crates/ui-egui/src/bidi.rs @@ -49,17 +49,18 @@ pub fn single_line(ui: &mut Ui, id: Id, text: &mut String, font: FontId, width: } /// One letter per script the UI's own fonts may lack: Hebrew, Arabic, Ethiopic, Devanagari, -/// Bengali, Gurmukhi, Gujarati, Tamil, Telugu, Kannada, Malayalam, Sinhala, Thai, Lao, Myanmar, -/// Khmer, Armenian and Georgian. egui's shaper selects the joined contextual forms itself. -pub(crate) const SCRIPT_SAMPLES: [char; 18] = [ - '\u{05D0}', '\u{0628}', '\u{1200}', '\u{0915}', '\u{0995}', '\u{0A15}', '\u{0A95}', '\u{0B95}', '\u{0C15}', '\u{0C95}', '\u{0D15}', '\u{0D9A}', - '\u{0E01}', '\u{0E81}', '\u{1000}', '\u{1780}', '\u{0531}', '\u{10D0}', +/// Gurmukhi, Gujarati, Tamil, Telugu, Kannada, Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian +/// and Georgian. egui's shaper selects the joined contextual forms itself. Bengali and Thai are +/// not here: [`crate::cjk`] picks their faces, in its own order of preference, after this list. +pub(crate) const SCRIPT_SAMPLES: [char; 16] = [ + '\u{05D0}', '\u{0628}', '\u{1200}', '\u{0915}', '\u{0A15}', '\u{0A95}', '\u{0B95}', '\u{0C15}', '\u{0C95}', '\u{0D15}', '\u{0D9A}', '\u{0E81}', + '\u{1000}', '\u{1780}', '\u{0531}', '\u{10D0}', ]; /// System families that draw those scripts, in order of preference: the first installed one that /// has a script's letter is taken, so a family covering several scripts (Segoe UI, Nirmala UI, /// Kohinoor, Noto Sans) joins once. Windows, macOS and the common Linux fonts for each script. -pub(crate) const SCRIPT_FAMILIES: [&str; 50] = [ +pub(crate) const SCRIPT_FAMILIES: [&str; 46] = [ // Hebrew and Arabic. "Segoe UI", "Arial", @@ -81,7 +82,6 @@ pub(crate) const SCRIPT_FAMILIES: [&str; 50] = [ // The Indic scripts and Sinhala. "Nirmala UI", "Kohinoor Devanagari", - "Kohinoor Bangla", "Kohinoor Gujarati", "Kohinoor Telugu", "Gurmukhi MN", @@ -90,7 +90,6 @@ pub(crate) const SCRIPT_FAMILIES: [&str; 50] = [ "Malayalam Sangam MN", "Sinhala Sangam MN", "Noto Sans Devanagari", - "Noto Sans Bengali", "Noto Sans Gurmukhi", "Noto Sans Gujarati", "Noto Sans Tamil", @@ -99,14 +98,12 @@ pub(crate) const SCRIPT_FAMILIES: [&str; 50] = [ "Noto Sans Malayalam", "Noto Sans Sinhala", "Lohit Devanagari", - // Thai, Lao, Myanmar and Khmer. + // Lao, Myanmar and Khmer. "Leelawadee UI", - "Thonburi", "Lao Sangam MN", "Myanmar Text", "Myanmar Sangam MN", "Khmer Sangam MN", - "Noto Sans Thai", "Noto Sans Lao", "Noto Sans Myanmar", "Noto Sans Khmer", @@ -120,7 +117,8 @@ pub(crate) const SCRIPT_FAMILIES: [&str; 50] = [ /// Faces the UI adds for scripts its own fonts lack (desktop: from the system), as egui font data; /// `taken` as for [`crate::theme::system_fallbacks`]. Hebrew and Arabic names were covered first; /// Ethiopic and the other scripts in [`SCRIPT_SAMPLES`] drew as boxes in the panels (a String -/// variable's Amharic value, #2014) until the system face for each was taken too. +/// variable's Amharic value, #2014) until the system face for each was taken too. Bengali and +/// Thai keep [`crate::cjk`]'s choice, made after this list. pub fn script_fallbacks(have: &dyn Fn(char) -> bool, taken: &mut Vec>) -> Vec<(String, egui::FontData)> { crate::theme::system_fallbacks(SCRIPT_SAMPLES, &SCRIPT_FAMILIES, have, taken) } diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 7cfc36f7b..a9e4ef94c 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** patch (the UI takes a system face for Ethiopic, the Indic scripts, Sinhala, Thai, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value no longer draws as boxes (#2014); Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** patch (the desktop UI takes a system face for Ethiopic, the Indic scripts, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value no longer draws as boxes (#2014); Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7) FigCraft's interface has a localization layer with an English catalog, a Russian catalog reviewed by a native speaker, and Spanish (with a Latin American overlay), French, German, Brazilian @@ -59,11 +59,12 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v - **Script support in documents:** Unicode bidi with Arabic shaping and mirrored brackets in text layers; right-to-left list markers and indents; right-to-left names in the layers panel, tabs and canvas labels (visual order, joined Arabic); inline IME composition with the candidate window - at the caret; system-font fallback for scripts the UI fonts lack: Hebrew and Arabic, and since - #2014 Ethiopic, the Indic scripts, Sinhala, Thai, Lao, Myanmar, Khmer, Armenian and Georgian, - so a layer name or a String variable's value in them draws in the panels when the system has a - face (`crates/ui-egui/src/bidi.rs`, `SCRIPT_SAMPLES` and `SCRIPT_FAMILIES`). Devanagari shapes - through harfrust. No vertical text (Figma has none either). + at the caret; system-font fallback for scripts the UI fonts lack: Hebrew and Arabic, Bengali + and Thai (with the CJK faces), and since #2014 Ethiopic, the other Indic scripts, Sinhala, Lao, + Myanmar, Khmer, Armenian and Georgian, so a layer name or a String variable's value in them + draws in the panels when the system has a face (`crates/ui-egui/src/bidi.rs`, `SCRIPT_SAMPLES` + and `SCRIPT_FAMILIES`). Devanagari shapes through harfrust. No vertical text (Figma has none + either). - **Script support in the UI:** menus widen to their longest label; dropdowns, the two-column labels of the right panel and the home screen's cards keep a long translation on one line with an ellipsis and show it in full on hover (checked in German, the longest); no mirrored @@ -93,7 +94,7 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v | English | en | 2,352 / 2,352 (100%, source) | yes | Latin | yes (source) | full | 0 | | Simplified Chinese (Mandarin) | zh-Hans | 2,216 / 2,352 (94.2%, draft) | yes | CJK text and IME in documents; UI text in an installed Chinese face, ahead of Japanese ones (web: the `FIGCRAFT_EMBED_CJK` build); no Traditional Chinese catalog (zh-TW, zh-HK read English) | no | draft | 1–2 (after native review) | | Spanish | es, es-419 | 2,352 / 2,352 (100%, draft); es-419 overlays 104 Latin American wordings (draft) | yes | Latin | no | draft | 0–1 (after native review) | -| Hindi | hi | 0 (0%) | no | Devanagari shaping works in documents; UI font fallback to check | no | none | 4–7 | +| Hindi | hi | 0 (0%) | no | Devanagari shaping works in documents; the desktop UI takes an installed Devanagari face (Nirmala UI, Kohinoor Devanagari, Noto Sans Devanagari, Lohit) for names and values (#2014); no UI catalog | no | none | 4–7 | | Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web not offered (font budget excludes Arabic); panels do not mirror | no | draft | review + panel mirroring (not re-estimated) | | French | fr | 2,328 / 2,352 (99.0%, draft) | yes | Latin | no | draft | 1–2 (after native review) | | Portuguese | pt-BR | 2,331 / 2,352 (99.1%, draft) | yes | Latin | no | draft | 1–2 (after native review) | @@ -128,7 +129,7 @@ Hindi and Arabic. Traditional Chinese is not planned (no catalog; its users see | Date | Change | Summary | |---|---|---| -| 2026-11-05 | patch | #2014: the panels drew a String variable's Amharic value as boxes: the UI took a system face for Hebrew and Arabic only. `bidi::script_fallbacks` now samples one letter of each of 18 scripts (Ethiopic, the Indic scripts, Sinhala, Thai, Lao, Myanmar, Khmer, Armenian, Georgian as well) against the system's families for each (Windows, macOS, the common Linux fonts), the first installed one that draws the letter taken once. Test: `bidi::tests::other_scripts_take_an_installed_system_face` (skips scripts the machine has no face for). | +| 2026-11-05 | patch | #2014: the panels drew a String variable's Amharic value as boxes: the UI took a system face for Hebrew and Arabic only. `bidi::script_fallbacks` now samples one letter of each of 16 scripts (Ethiopic, the Indic scripts other than Bengali, Sinhala, Lao, Myanmar, Khmer, Armenian, Georgian as well; Bengali and Thai keep `crate::cjk`'s faces) against the system's families for each (Windows, macOS, the common Linux fonts), the first installed one that draws the letter taken once. Desktop only: the web build has no system fonts. Test: `bidi::tests::other_scripts_take_an_installed_system_face` (skips scripts the machine has no face for). | | 2026-10-30 | minor | Bosnian (`bs`, Bosanski) draft catalog: every UI string (1,906), command label (629) and menu wording (31), machine-drafted in Latin script with ijekavian forms and marked as a draft awaiting native review. Bosnian plurals: one for 1, 21, 31… (not 11), few for 2–4, 22–24… (not 12–14), other for the rest. Grade and hours unchanged (Bosnian is not one of the twelve key languages) | | 2026-10-29 | minor | German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft. Nine existing translations corrected; keys, placeholders, coverage, grade and estimates unchanged | | 2026-10-28 | minor | Arabic draft: 1,857 UI entries, 620 command labels and 31 menu wordings, with count-neutral plurals. AI-assisted, native review pending. Desktop uses the existing Arabic fallback and bidi; web requires an embedded Arabic face. No panel mirroring or parity-grade increase claimed | From a63f0d7937264e7fe9d2d0cb0e653b2fcf0eeccf Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 5 Nov 2026 10:41:00 -0500 Subject: [PATCH 085/102] Docs: name the Indic scripts the UI fallback covers (#2014) From review: "the Indic scripts" promised more than the sample list holds. The localization doc, the ROADMAP and the families comment now say Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam. Co-Authored-By: Claude Fable 5.1 --- ROADMAP.md | 6 +++--- crates/ui-egui/src/bidi.rs | 2 +- docs/localization-parity.md | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 8eb0d9301..90f37710a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** patch (the desktop UI takes a system face for Ethiopic, the Indic scripts, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** patch (the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -63,7 +63,7 @@ native speakers' reviews of the nine language drafts need people. | Stability | 55% (damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, #1125) | 20–40 | [gaps](docs/gaps.md) | | Performance | 60% | 30–60 | [hardware-parity](docs/hardware-parity.md) | | Hardware | 60% | 10–21 | [hardware-parity](docs/hardware-parity.md) | -| Localization | 39% (layer; English; Russian and Turkish reviewed by native speakers; Spanish with a Latin American overlay, French, German, Brazilian Portuguese, Japanese, Korean, Simplified Chinese, Indonesian and Czech drafts; CJK UI fonts; the desktop UI takes a system face for Ethiopic, the Indic scripts, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian, #2014); Arabic draft: 2,508 entries, native review and panel mirroring pending | 29–51 | [localization-parity](docs/localization-parity.md) | +| Localization | 39% (layer; English; Russian and Turkish reviewed by native speakers; Spanish with a Latin American overlay, French, German, Brazilian Portuguese, Japanese, Korean, Simplified Chinese, Indonesian and Czech drafts; CJK UI fonts; the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian, #2014); Arabic draft: 2,508 entries, native review and panel mirroring pending | 29–51 | [localization-parity](docs/localization-parity.md) | | Platforms | 75% | 10–20 | [hardware-parity](docs/hardware-parity.md) | | Ecosystem / plugins | 40% (own WASM plugins with panels, settings and widgets that take clicks, text and a property menu; a self-hosted plugin directory) | 6–22 | [gaps](docs/gaps.md) | | AI features | 0% | 30–60 | [gaps](docs/gaps.md) | @@ -132,7 +132,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). ## Progress log -- **2026-11-05** · M10, #2014: the desktop UI takes a system face for Ethiopic, the Indic scripts, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic (`bidi::script_fallbacks`: one sample letter per script, the system's families for each; Bengali and Thai keep `crate::cjk`'s choice), so a layer name or a String variable's Amharic value draws in the panels instead of boxes. Test: `bidi::tests::other_scripts_take_an_installed_system_face`. +- **2026-11-05** · M10, #2014: the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic (`bidi::script_fallbacks`: one sample letter per script, the system's families for each; Bengali and Thai keep `crate::cjk`'s choice), so a layer name or a String variable's Amharic value draws in the panels instead of boxes. Test: `bidi::tests::other_scripts_take_an_installed_system_face`. - **2026-10-30**: M8, #1125: damaged `trak` size-table offsets are checked instead of wrapping on 32-bit targets, and an incomplete normal track is dropped entirely, never returned in part. Font indexing makes its existing bounds explicit, preserving later faces and sparse name-table reads. Synthetic regression tests in `fontdb_tests.rs`. Numbers unchanged. - **2026-10-30** · Text style dedupe is O(spans) (M8, #1102): `shape_text` deduped spans into styles by a scan over the styles already collected — O(spans × styles), so a styled text's dedupe grew with the square of its runs (a synthetic 50k-run text with 100 alternating styles spent 7.7 ms in it). Now the last two styles again (spans run in blocks), then buckets keyed by a cheap fingerprint (family and style bytes, size bits with −0.0 folded, the enums, fill count and solid colours), each bucket resolved with the full equality: the result is the scan's, never worse than it, and O(spans) when names and sizes differ (the same synthetic text: 2.6 ms). The font-db write lock is untouched: `find()` loads faces, which needs the write. `layout_dedupe_tests`. Numbers unchanged. - **2026-10-29** · M10: correct nine German labels in `de.toml`: gradient stops use Verlaufsstopp, OpenType ss01–ss05 use Stilsatz, and the Home-screen preference names the Startbildschirm consistently in the UI and Actions palette. This is a partial terminology pass; German remains a draft awaiting a full native-speaker review and maintainer approval. Numbers unchanged. diff --git a/crates/ui-egui/src/bidi.rs b/crates/ui-egui/src/bidi.rs index b430686c3..54529e0e0 100644 --- a/crates/ui-egui/src/bidi.rs +++ b/crates/ui-egui/src/bidi.rs @@ -79,7 +79,7 @@ pub(crate) const SCRIPT_FAMILIES: [&str; 46] = [ "Kefa", "Noto Sans Ethiopic", "Abyssinica SIL", - // The Indic scripts and Sinhala. + // Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada, Malayalam and Sinhala. "Nirmala UI", "Kohinoor Devanagari", "Kohinoor Gujarati", diff --git a/docs/localization-parity.md b/docs/localization-parity.md index a9e4ef94c..b93a40b18 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** patch (the desktop UI takes a system face for Ethiopic, the Indic scripts, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value no longer draws as boxes (#2014); Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** patch (the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value no longer draws as boxes (#2014); Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7) FigCraft's interface has a localization layer with an English catalog, a Russian catalog reviewed by a native speaker, and Spanish (with a Latin American overlay), French, German, Brazilian @@ -60,8 +60,8 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v layers; right-to-left list markers and indents; right-to-left names in the layers panel, tabs and canvas labels (visual order, joined Arabic); inline IME composition with the candidate window at the caret; system-font fallback for scripts the UI fonts lack: Hebrew and Arabic, Bengali - and Thai (with the CJK faces), and since #2014 Ethiopic, the other Indic scripts, Sinhala, Lao, - Myanmar, Khmer, Armenian and Georgian, so a layer name or a String variable's value in them + and Thai (with the CJK faces), and since #2014 Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and + Georgian, so a layer name or a String variable's value in them draws in the panels when the system has a face (`crates/ui-egui/src/bidi.rs`, `SCRIPT_SAMPLES` and `SCRIPT_FAMILIES`). Devanagari shapes through harfrust. No vertical text (Figma has none either). @@ -129,7 +129,7 @@ Hindi and Arabic. Traditional Chinese is not planned (no catalog; its users see | Date | Change | Summary | |---|---|---| -| 2026-11-05 | patch | #2014: the panels drew a String variable's Amharic value as boxes: the UI took a system face for Hebrew and Arabic only. `bidi::script_fallbacks` now samples one letter of each of 16 scripts (Ethiopic, the Indic scripts other than Bengali, Sinhala, Lao, Myanmar, Khmer, Armenian, Georgian as well; Bengali and Thai keep `crate::cjk`'s faces) against the system's families for each (Windows, macOS, the common Linux fonts), the first installed one that draws the letter taken once. Desktop only: the web build has no system fonts. Test: `bidi::tests::other_scripts_take_an_installed_system_face` (skips scripts the machine has no face for). | +| 2026-11-05 | patch | #2014: the panels drew a String variable's Amharic value as boxes: the UI took a system face for Hebrew and Arabic only. `bidi::script_fallbacks` now samples one letter of each of 16 scripts (Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as well as Hebrew and Arabic; Bengali and Thai keep `crate::cjk`'s faces) against the system's families for each (Windows, macOS, the common Linux fonts), the first installed one that draws the letter taken once. Desktop only: the web build has no system fonts. Test: `bidi::tests::other_scripts_take_an_installed_system_face` (skips scripts the machine has no face for). | | 2026-10-30 | minor | Bosnian (`bs`, Bosanski) draft catalog: every UI string (1,906), command label (629) and menu wording (31), machine-drafted in Latin script with ijekavian forms and marked as a draft awaiting native review. Bosnian plurals: one for 1, 21, 31… (not 11), few for 2–4, 22–24… (not 12–14), other for the rest. Grade and hours unchanged (Bosnian is not one of the twelve key languages) | | 2026-10-29 | minor | German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft. Nine existing translations corrected; keys, placeholders, coverage, grade and estimates unchanged | | 2026-10-28 | minor | Arabic draft: 1,857 UI entries, 620 command labels and 31 menu wordings, with count-neutral plurals. AI-assisted, native review pending. Desktop uses the existing Arabic fallback and bidi; web requires an embedded Arabic face. No panel mirroring or parity-grade increase claimed | From 4fcb95eeabf7e860ba4013bbd1a5436b21ebe973 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 5 Nov 2026 15:54:11 -0500 Subject: [PATCH 086/102] M3: the Local variables window selects several variables with Shift and Cmd/Ctrl, and acts on them at once (#2002) The window keeps a selection of variable ids: a click selects one row, Shift+click the range from the anchor through the rows shown, Cmd/Ctrl+click toggles a row, and Escape or a click on the empty space clears it. Selected rows use the sidebar's selected-row colour. Right-clicking a row that is part of a selection of several offers Delete, Move to group and Scope for all of them, each sent as one command.batch so it is one undo step. Rename and value edits stay single-row. Co-Authored-By: Claude Fable 5.1 --- ROADMAP.md | 3 +- crates/ui-egui/locales/en.toml | 6 + crates/ui-egui/src/dialogs/variables_panel.rs | 132 +++++++++++- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/variables_select_tests.rs | 194 ++++++++++++++++++ docs/components-parity.md | 5 +- 6 files changed, 338 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/variables_select_tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index c2aa86c22..c6328cedf 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on all of them in one undo step (#2002); web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -132,6 +132,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). ## Progress log +- **2026-11-05** · M3, #2002: the Local variables window selects several variables with a click, Shift+click (range) and Cmd/Ctrl+click (toggle), cleared by Escape or a click on the empty space; delete, move to a group and scope act on the whole selection as one undo step (`command.batch`). Rename and value edits stay single-row. - **2026-10-30**: M8, #1125: damaged `trak` size-table offsets are checked instead of wrapping on 32-bit targets, and an incomplete normal track is dropped entirely, never returned in part. Font indexing makes its existing bounds explicit, preserving later faces and sparse name-table reads. Synthetic regression tests in `fontdb_tests.rs`. Numbers unchanged. - **2026-10-30** · Text style dedupe is O(spans) (M8, #1102): `shape_text` deduped spans into styles by a scan over the styles already collected — O(spans × styles), so a styled text's dedupe grew with the square of its runs (a synthetic 50k-run text with 100 alternating styles spent 7.7 ms in it). Now the last two styles again (spans run in blocks), then buckets keyed by a cheap fingerprint (family and style bytes, size bits with −0.0 folded, the enums, fill count and solid colours), each bucket resolved with the full equality: the result is the scan's, never worse than it, and O(spans) when names and sizes differ (the same synthetic text: 2.6 ms). The font-db write lock is untouched: `find()` loads faces, which needs the write. `layout_dedupe_tests`. Numbers unchanged. - **2026-10-29** · M10: correct nine German labels in `de.toml`: gradient stops use Verlaufsstopp, OpenType ss01–ss05 use Stilsatz, and the Home-screen preference names the Startbildschirm consistently in the UI and Actions palette. This is a partial terminology pass; German remains a draft awaiting a full native-speaker review and maintainer approval. Numbers unchanged. diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 11f0bb4ac..0c93684d1 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -406,6 +406,12 @@ name = "English" "Decoration style" = "Decoration style" "Decoration" = "Decoration" "Deep select" = "Deep select" +"Delete {n} variables" = { one = "Delete {n} variable", other = "Delete {n} variables" } +"Move out of any group" = "Move out of any group" +"Move to group {group}" = "Move to group {group}" +"Scope: all supported properties" = "Scope: all supported properties" +"Scope: hidden from pickers" = "Scope: hidden from pickers" +"Scope: only {scope}" = "Scope: only {scope}" "Wrap style" = "Wrap style" "Balance" = "Balance" "Pretty" = "Pretty" diff --git a/crates/ui-egui/src/dialogs/variables_panel.rs b/crates/ui-egui/src/dialogs/variables_panel.rs index 9a1011a42..4ffcf77d3 100644 --- a/crates/ui-egui/src/dialogs/variables_panel.rs +++ b/crates/ui-egui/src/dialogs/variables_panel.rs @@ -53,6 +53,107 @@ pub struct Editor { details: Option, /// The group the table shows ("space" or "color/brand"); None = every variable. group: Option, + /// The selected variables' ids (this file's), kept to the rows the table shows. + pub(crate) selected: Vec, + /// The row a Shift+click extends from. + pub(crate) anchor: Option, + /// The variable ids the table shows now, in row order (the range a Shift+click covers). + pub(crate) order: Vec, +} + +/// A click on row `id`: plain selects only it, Shift extends from the anchor to it through the +/// rows shown (added to the selection with Cmd/Ctrl), Cmd/Ctrl (or Shift without an anchor) toggles it. +pub(crate) fn select_clicked(st: &mut Editor, id: &str, m: egui::Modifiers) { + let pos = |x: &str| st.order.iter().position(|o| o == x); + let anchor = st.anchor.as_deref().filter(|a| st.selected.iter().any(|s| s == a)).and_then(pos); + if m.shift + && let (Some(ai), Some(bi)) = (anchor, pos(id)) + { + let (lo, hi) = (ai.min(bi), ai.max(bi)); + let mut s: Vec = if m.command { st.selected.clone() } else { vec![] }; + for x in st.order.get(lo..=hi).unwrap_or_default() { + if !s.contains(x) { + s.push(x.clone()); + } + } + st.selected = s; + } else if m.shift || m.command { + match st.selected.iter().position(|x| x == id) { + Some(i) => { + st.selected.remove(i); + } + None => st.selected.push(id.to_string()), + } + st.anchor = Some(id.to_string()); + } else { + st.selected = vec![id.to_string()]; + st.anchor = Some(id.to_string()); + } +} + +/// The variables a row's menu acts on: the whole selection when the row is part of a selection of +/// several (in table order, leaving out inherited ones, which are changed in their own collection), +/// else None. +fn bulk_ids<'a>(view: &View<'a>, st: &Editor, v: &Variable) -> Option> { + if !view.editable() || st.selected.len() < 2 || !st.selected.contains(&v.id) { + return None; + } + let list: Vec<&Variable> = + st.order.iter().filter(|id| st.selected.contains(id)).filter_map(|id| view.vars.get_by_id(id)).filter(|x| x.extends.is_none()).collect(); + (list.len() > 1).then_some(list) +} + +/// Run one `variable.*` command per variable as a single undo step. +fn bulk_run(app: &mut FigApp, label: &str, vars: &[&Variable], step: impl Fn(&Variable) -> Option<(&'static str, Value)>) { + let steps: Vec = vars.iter().filter_map(|v| step(v)).map(|(command, params)| json!({"command": command, "params": params})).collect(); + if !steps.is_empty() { + app.run("command.batch", json!({"label": label, "commands": steps})); + } +} + +/// The context menu of a row that is part of a selection of several: delete, move to a group and +/// scope act on all of them. +fn bulk_menu(app: &mut FigApp, ui: &mut Ui, coll_groups: &[String], vars: &[&Variable]) { + let n = vars.len(); + if menu_item(ui, &trn("Delete {n} variables", n, &[]), "") { + bulk_run(app, "Delete variables", vars, |v| Some(("variable.delete", json!({"variable": v.id})))); + ui.close(); + } + let moves = std::iter::once(None).chain(coll_groups.iter().map(|g| Some(g.as_str()))); + for g in moves { + let label = g.map_or_else(|| tr("Move out of any group").to_string(), |g| trf("Move to group {group}", &[("group", &g)])); + if menu_item(ui, &label, "") { + bulk_run(app, "Move variables", vars, |v| { + let short = v.name.rsplit('/').next().unwrap_or(&v.name); + let name = g.map_or_else(|| short.to_string(), |g| format!("{g}/{short}")); + (name != v.name).then(|| ("variable.update", json!({"variable": v.id, "name": name}))) + }); + ui.close(); + } + } + let mut scopes: Vec<(&'static str, &'static str)> = Vec::new(); + for v in vars { + for s in scopes_for(v.kind) { + if !scopes.contains(s) { + scopes.push(*s); + } + } + } + let set = |app: &mut FigApp, label: &str, value: Option<&'static str>, ui: &mut Ui| { + if menu_item(ui, label, "") { + bulk_run(app, "Change scope", vars, |v| match value { + None => Some(("variable.update", json!({"variable": v.id, "scopes": Value::Null}))), + Some("") => Some(("variable.update", json!({"variable": v.id, "scopes": []}))), + Some(s) => scopes_for(v.kind).iter().any(|(id, _)| *id == s).then(|| ("variable.update", json!({"variable": v.id, "scopes": [s]}))), + }); + ui.close(); + } + }; + set(app, tr("Scope: all supported properties"), None, ui); + set(app, tr("Scope: hidden from pickers"), Some(""), ui); + for (id, label) in scopes { + set(app, &trf("Scope: only {scope}", &[("scope", &tr(label))]), Some(id), ui); + } } impl Editor { @@ -575,6 +676,17 @@ fn table(app: &mut FigApp, ui: &mut Ui, view: &View, st: &mut Editor) { let mut list: Vec<&Variable> = view.in_collection(&coll.id).filter(|v| in_group(v) && (q.is_empty() || v.name.to_lowercase().contains(&q))).collect(); list.sort_by(|a, b| group_of(&a.name).cmp(group_of(&b.name))); + st.order = list.iter().map(|v| v.id.clone()).collect(); + let order = st.order.clone(); + st.selected.retain(|id| order.contains(id)); + // Escape clears the selection (unless a field has the keyboard). + if !st.selected.is_empty() + && st.rename.is_none() + && !ui.ctx().egui_wants_keyboard_input() + && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) + { + st.selected.clear(); + } let width = (NAME_W + coll.modes.len() as f32 * MODE_W + 40.0).max(ui.available_width()); egui::ScrollArea::both().id_salt("vars_table").auto_shrink([false, false]).show(ui, |ui| { ui.spacing_mut().item_spacing = vec2(0.0, 0.0); @@ -597,6 +709,11 @@ fn table(app: &mut FigApp, ui: &mut Ui, view: &View, st: &mut Editor) { } if view.editable() { create_row(app, ui, view, coll, st); + // A click on the empty space below the rows clears the selection. + let (_, empty) = ui.allocate_exact_size(vec2(width, ui.available_height().max(24.0)), Sense::click()); + if empty.clicked() { + st.selected.clear(); + } } }); } @@ -686,7 +803,10 @@ fn var_row(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, v: &Va let t = Tokens::get(ui.ctx()); let editable = view.editable(); let (r, resp) = ui.allocate_exact_size(vec2(width, ROW_H), Sense::click()); - if resp.hovered() || (editable && st.details.as_deref() == Some(v.id.as_str())) { + let selected = editable && st.selected.contains(&v.id); + if selected { + ui.painter().rect_filled(r, CornerRadius::ZERO, t.selected_row); + } else if resp.hovered() || (editable && st.details.as_deref() == Some(v.id.as_str())) { ui.painter().rect_filled(r, CornerRadius::ZERO, t.hover); } kind_glyph(ui, view.vars, v, coll, Rect::from_center_size(pos2(r.min.x + 24.0, r.center().y), vec2(14.0, 14.0))); @@ -709,10 +829,20 @@ fn var_row(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, v: &Va value_cell(app, ui, view, v, coll, &m.id, cell); } if editable { + if resp.clicked() { + let m = ui.input(|i| i.modifiers); + select_clicked(st, &v.id, m); + } if !inherited && resp.double_clicked() && ui.input(|i| i.pointer.interact_pos()).is_some_and(|p| p.x < name_r.max.x) { start_rename(st, target.clone()); } + let bulk = bulk_ids(view, st, v); + let coll_groups = groups(view.in_collection(&coll.id).map(|x| x.name.as_str())); crate::right::context_popup(&resp).show(|ui| { + if let Some(vars) = &bulk { + bulk_menu(app, ui, &coll_groups, vars); + return; + } if menu_item(ui, tr("Edit variable"), "") { st.details = Some(v.id.clone()); ui.close(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a7397cee4..fccdc6146 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -257,6 +257,8 @@ mod variables_export_ui_tests; #[cfg(test)] mod variables_rename_tests; #[cfg(test)] +mod variables_select_tests; +#[cfg(test)] mod variants_discovery_tests; #[cfg(test)] mod vector_keys_tests; diff --git a/crates/ui-egui/src/variables_select_tests.rs b/crates/ui-egui/src/variables_select_tests.rs new file mode 100644 index 000000000..55062db96 --- /dev/null +++ b/crates/ui-egui/src/variables_select_tests.rs @@ -0,0 +1,194 @@ +//! Selecting several variables in the Local variables window (#2002): a click selects one row, +//! Shift+click the range from the anchor, Ctrl/Cmd+click toggles a row, Escape and a click on the +//! empty space clear; delete, move to a group and scope then act on the whole selection in one +//! undo step. + +use egui::{Event, Key, Modifiers, PointerButton, Pos2}; +use figcraft_engine::Session; +use serde_json::json; + +use crate::layers_drag_tests::Ui; +use crate::live_tests::{flat, has_text, text_center}; + +const NAMES: [&str; 5] = ["alpha", "bravo", "charlie", "delta", "echo"]; + +/// The window open on a collection of five number variables. +fn window() -> Ui { + let mut s = Session::new(); + s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap(); + for n in NAMES { + s.execute("variable.create", &json!({"collection": "Theme", "name": n, "type": "number", "value": 1})).unwrap(); + } + let mut u = Ui::new(s); + u.app.ui.variables = Some(Default::default()); + for _ in 0..10 { + u.frame(vec![]); + } + u +} + +fn row(u: &mut Ui, name: &str) -> Pos2 { + let shapes = flat(&u.frame_output(vec![]).shapes); + // The name column, left of the value cells. + let p = text_center(&shapes, name); + Pos2::new(p.x, p.y) +} + +fn click(u: &mut Ui, p: Pos2, button: PointerButton, m: Modifiers) { + u.frame_with(vec![Event::PointerMoved(p)], m); + for pressed in [true, false] { + u.frame_with(vec![Event::PointerButton { pos: p, button, pressed, modifiers: m }], m); + } + for _ in 0..5 { + u.frame(vec![]); + } +} + +fn click_row(u: &mut Ui, name: &str, m: Modifiers) { + let p = row(u, name); + click(u, p, PointerButton::Primary, m); +} + +fn selected(u: &Ui) -> Vec { + let st = u.app.ui.variables.as_ref().unwrap(); + let doc = u.app.session.doc().unwrap(); + let mut names: Vec = st.selected.iter().filter_map(|id| doc.variables.get_by_id(id)).map(|v| v.name.clone()).collect(); + names.sort(); + names +} + +fn names(u: &Ui) -> Vec { + u.app.session.doc().unwrap().variables.variables.iter().map(|v| v.name.clone()).collect() +} + +const SHIFT: Modifiers = Modifiers { shift: true, ..Modifiers::NONE }; +const CTRL: Modifiers = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + +#[test] +fn a_click_selects_one_variable_and_replaces_the_selection() { + let mut u = window(); + click_row(&mut u, "bravo", Modifiers::NONE); + assert_eq!(selected(&u), ["bravo"]); + click_row(&mut u, "delta", Modifiers::NONE); + assert_eq!(selected(&u), ["delta"]); +} + +#[test] +fn shift_click_selects_the_range_from_the_anchor() { + let mut u = window(); + click_row(&mut u, "bravo", Modifiers::NONE); + click_row(&mut u, "delta", SHIFT); + assert_eq!(selected(&u), ["bravo", "charlie", "delta"]); + // A range upward from the same anchor. + click_row(&mut u, "alpha", SHIFT); + assert_eq!(selected(&u), ["alpha", "bravo"]); +} + +#[test] +fn ctrl_click_toggles_one_variable() { + let mut u = window(); + click_row(&mut u, "alpha", Modifiers::NONE); + click_row(&mut u, "charlie", CTRL); + assert_eq!(selected(&u), ["alpha", "charlie"]); + click_row(&mut u, "alpha", CTRL); + assert_eq!(selected(&u), ["charlie"]); +} + +#[test] +fn escape_clears_the_selection() { + let mut u = window(); + click_row(&mut u, "alpha", Modifiers::NONE); + click_row(&mut u, "bravo", SHIFT); + assert_eq!(selected(&u).len(), 2); + for pressed in [true, false] { + u.frame(vec![Event::Key { key: Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }]); + } + assert!(selected(&u).is_empty()); +} + +#[test] +fn selected_rows_are_painted_with_the_selected_row_colour() { + let mut u = window(); + let colour = crate::theme::Tokens::get(&u.ctx).selected_row; + let count = |u: &mut Ui| flat(&u.frame_output(vec![]).shapes).iter().filter(|s| matches!(s, egui::Shape::Rect(r) if r.fill == colour)).count(); + let none = count(&mut u); + click_row(&mut u, "alpha", Modifiers::NONE); + let one = count(&mut u); + click_row(&mut u, "charlie", SHIFT); + let three = count(&mut u); + assert!(one > none, "the selected row is highlighted"); + assert_eq!(three - one, 2, "two more rows highlighted by the range"); +} + +/// Select bravo..delta, then right-click delta. +fn select_three_and_open_menu(u: &mut Ui) -> Vec { + click_row(u, "bravo", Modifiers::NONE); + click_row(u, "delta", SHIFT); + assert_eq!(selected(u), ["bravo", "charlie", "delta"]); + let p = row(u, "delta"); + click(u, p, PointerButton::Secondary, Modifiers::NONE); + flat(&u.frame_output(vec![]).shapes) +} + +#[test] +fn bulk_delete_removes_exactly_the_selected_variables_in_one_undo_step() { + let mut u = window(); + let menu = select_three_and_open_menu(&mut u); + assert!(has_text(&menu, "Delete 3 variables")); + let before = u.app.session.undo_labels(100).len(); + click(&mut u, text_center(&menu, "Delete 3 variables"), PointerButton::Primary, Modifiers::NONE); + assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); + assert_eq!(names(&u), ["alpha", "echo"]); + assert_eq!(u.app.session.undo_labels(100).len(), before + 1, "one undo step"); + u.app.session.undo().unwrap(); + assert_eq!(names(&u), NAMES); +} + +#[test] +fn bulk_move_to_a_group_renames_every_selected_variable_in_one_step() { + let mut u = window(); + u.app.session.execute("variable.create", &json!({"collection": "Theme", "name": "space/zero", "type": "number", "value": 0})).unwrap(); + let menu = select_three_and_open_menu(&mut u); + let before = u.app.session.undo_labels(100).len(); + click(&mut u, text_center(&menu, "Move to group space"), PointerButton::Primary, Modifiers::NONE); + assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); + let mut now = names(&u); + now.sort(); + assert_eq!(now, ["alpha", "echo", "space/bravo", "space/charlie", "space/delta", "space/zero"]); + assert_eq!(u.app.session.undo_labels(100).len(), before + 1, "one undo step"); + u.app.session.undo().unwrap(); + assert!(names(&u).contains(&"bravo".to_string()) && names(&u).contains(&"delta".to_string())); +} + +#[test] +fn bulk_scope_change_reaches_every_selected_variable_in_one_step() { + let mut u = window(); + let menu = select_three_and_open_menu(&mut u); + let before = u.app.session.undo_labels(100).len(); + click(&mut u, text_center(&menu, "Scope: only Corner radius"), PointerButton::Primary, Modifiers::NONE); + assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); + let scoped: Vec = u + .app + .session + .doc() + .unwrap() + .variables + .variables + .iter() + .filter(|v| v.scopes.as_deref() == Some(&["CORNER_RADIUS".to_string()][..])) + .map(|v| v.name.clone()) + .collect(); + assert_eq!(scoped, ["bravo", "charlie", "delta"]); + assert_eq!(u.app.session.undo_labels(100).len(), before + 1, "one undo step"); +} + +#[test] +fn a_row_outside_the_selection_keeps_the_single_variable_menu() { + let mut u = window(); + click_row(&mut u, "alpha", Modifiers::NONE); + click_row(&mut u, "bravo", SHIFT); + let p = row(&mut u, "echo"); + click(&mut u, p, PointerButton::Secondary, Modifiers::NONE); + let menu = flat(&u.frame_output(vec![]).shapes); + assert!(has_text(&menu, "Delete variable") && !has_text(&menu, "Delete 2 variables")); +} diff --git a/docs/components-parity.md b/docs/components-parity.md index 0e3248248..20df6baf7 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -1,6 +1,6 @@ # Components, variants, styles and variables parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on all of them in one undo step (#2002); Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) Design systems are why teams adopt Figma. **Components: breadth ~96%, ready ~72%. Styles and variables: breadth ~95%, ready ~76% (estimated).** QA'd with a synthetic design system of ~300 @@ -63,7 +63,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Editing a style updates its layers; detach and delete keep values; editing a styled property unlinks that style | done | an edited fill/stroke/effect/grid list or text chars unlink; applying a style replaces variables bound to what it sets; text styles on text layers only | | Organising styles: folders by `/` names, order, duplicate, rename folder, Local styles list | done | `style.move` (into a folder renames), `style.duplicate` (right below), `style.renameFolder`; the page's Local styles list by type and folder (drag to reorder, right-click) | | Variables inside styles (paint, effect, grid and text styles; each user resolves them in its own modes) | done | `style.bind`, `style_vars_tests`; the editor binds paint colours, shadow colours, blur radii, grid sizes and a text style's font, font style, size, line height and letter spacing, the rest through the command | -| Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only | +| Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once | | Modes: add, duplicate, rename, delete, set as default / reorder | done | layers on Auto follow a new default; explicit modes stay | | Deleting a bound variable or its collection | done | layers keep their last value and are unbound; aliases to it take its values and colour calculations reading it keep the colour they show | | Code syntax per platform (Web, iOS, Android) | done | generated CSS uses the Web name, SwiftUI the iOS one and Compose the Android one (a variable without one keeps its value there); in the variables JSON; ArkUI and Flutter have no platform of their own and write values | @@ -78,6 +78,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | M3, #2002: the Local variables window selects several variables, as the Layers panel selects layers. A click selects one row, Shift+click the range from the anchor through the rows shown, Cmd/Ctrl+click toggles a row, Escape or a click on the empty space below the rows clears; selected rows use the sidebar's selected-row colour. Right-clicking a row that is part of a selection of several offers Delete, Move to group and Scope (all supported properties, hidden from pickers, or only one scope) for the whole selection, each sent as one `command.batch`, so one undo step; no engine command changed. Renaming and value edits stay single-row. Tests: `variables_select_tests` (headless UI). Grade unchanged | | 2026-11-01 | patch | M3: Delete on a layer inside an instance hides it (an override) instead of being refused ("You can't delete a layer or object from an instance. If you try, Figma will only toggle the layer's visibility instead of removing it", Guide to auto layout); `edit.delete` reports those ids under `hidden`, the structure and the main component stay as they were, one undo step; deleting the instance itself still removes it. Found by a documentation audit of the auto layout page. Test: `components_behaviour_tests::deleting_a_layer_inside_an_instance_hides_it_instead` (the refusal row for it is gone from `what_instances_cannot_override_is_refused`). Numbers unchanged | | 2026-10-31 | minor | M3, gap 10: library analytics cover styles and variables. A file reports how many of its layers use each of a library's styles and variables, and Show usage (`library.usage`) lists them beside the components, by a Type choice, with their layers and files. Layers inside instances count for their component. Insertions, detachments and modes aren't counted for them yet. Numbers unchanged. Tests: `library_assets_tests`. | | 2026-10-31 | minor | M6: as the help center describes code syntax, Dev Mode's SwiftUI and Compose code now writes a bound variable's iOS or Android code syntax in place of its value, as CSS already wrote the Web one: fills, strokes and their weight, sizes, corner radius, gaps, padding, opacity, the font family and size and the characters. A variable with no code syntax for the platform keeps the value, since a name made up here wouldn't exist in the code it lands in. ArkUI and Flutter have no code syntax platform and are unchanged. Test: `variables_behaviour_tests::swiftui_and_compose_name_variables_by_their_code_syntax`. Numbers unchanged. Grade unchanged | From a3e96bbb479ea529f5ca5c5c71805e058d1e2a9a Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 5 Nov 2026 17:06:55 -0500 Subject: [PATCH 087/102] docs: ui-parity status line dated 2026-11-05 with its history row Co-Authored-By: Claude Fable 5.1 --- docs/ui-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8d4e7d8cb..0f0e92272 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: From 0d1801db937678756d09b2f2e72990e47b7fcb3e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 5 Nov 2026 17:21:18 -0500 Subject: [PATCH 088/102] text styles: applying one to the whole layer reaches a trailing empty paragraph take_paragraph_style went through para_span, which leaves out the empty paragraph after a final newline, so its list style stayed as it was and the layer did not fold back to one list. The whole-layer path now addresses every paragraph by index; para_span's selection semantics are unchanged. Co-Authored-By: Claude Fable 5.1 --- crates/doc/src/text.rs | 2246 ++++++++++++++++++++-------------------- 1 file changed, 1137 insertions(+), 1109 deletions(-) diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index d674adb6d..f4d087589 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -1,1109 +1,1137 @@ -//! Text node data: characters plus a base style and styled runs. - -use figcraft_color::{Color, Paint}; -use serde::{Deserialize, Serialize}; - -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "unit", content = "value", rename_all = "camelCase")] -#[derive(Default)] -pub enum LineHeight { - #[default] - Auto, - Pixels(f64), - Percent(f64), -} - -impl LineHeight { - /// Resolved line height in px for `font_size` (`auto` uses the font's natural ratio). - pub fn resolve(self, font_size: f64, natural_ratio: f64) -> f64 { - match self { - LineHeight::Auto => font_size * natural_ratio, - LineHeight::Pixels(v) => v.max(0.0), - LineHeight::Percent(p) => font_size * p.max(0.0) / 100.0, - } - } - pub fn label(self) -> String { - match self { - LineHeight::Auto => "Auto".into(), - LineHeight::Pixels(v) => trim_num(v), - LineHeight::Percent(p) => format!("{}%", trim_num(p)), - } - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "unit", content = "value", rename_all = "camelCase")] -pub enum LetterSpacing { - Pixels(f64), - Percent(f64), -} - -impl Default for LetterSpacing { - fn default() -> Self { - LetterSpacing::Percent(0.0) - } -} - -impl LetterSpacing { - pub fn resolve(self, font_size: f64) -> f64 { - match self { - LetterSpacing::Pixels(v) => v, - LetterSpacing::Percent(p) => font_size * p / 100.0, - } - } - pub fn label(self) -> String { - match self { - LetterSpacing::Pixels(v) => trim_num(v), - LetterSpacing::Percent(p) => format!("{}%", trim_num(p)), - } - } -} - -pub fn trim_num(v: f64) -> String { - if v.abs() >= 9.0e18 { - return format!("{v}"); - } - let r = (v * 100.0).round() / 100.0; - if r.fract().abs() < 1e-9 { format!("{}", r as i64) } else { format!("{r}") } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum TextDecoration { - #[default] - None, - Underline, - Strikethrough, -} - -/// How an underline or strikethrough is drawn. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum DecorationStyle { - #[default] - Solid, - Dotted, - Wavy, -} - -/// A decoration length: `Auto` (the font's own value), pixels, or a percentage of the font size. -pub type DecorationLength = LineHeight; - -/// How a decoration line looks; the default is the font's own solid line in the text's colour. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Default)] -#[serde(default)] -pub struct DecorationLook { - pub style: DecorationStyle, - pub thickness: DecorationLength, - /// Underlines: from the baseline down to the line's top edge (negative: above the baseline). - pub offset: DecorationLength, - /// Underlines break where descenders cross them. - pub skip_ink: bool, - /// The line's own colour (None: the text's fills). - pub color: Option, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum TextCase { - #[default] - Original, - Upper, - Lower, - Title, - SmallCaps, -} - -impl TextCase { - pub fn apply(self, s: &str) -> String { - self.apply_after(s, None) - } - - /// Apply the case to `s`, which follows `prev` in the text (so title case only capitalises - /// the first letter of each word even when a word spans several styled runs). An apostrophe - /// as `prev` is taken to continue a word. - pub fn apply_after(self, s: &str, prev: Option) -> String { - self.apply_impl(s, prev, prev.is_some_and(is_word_char)) - } - - /// Like [`apply_after`](Self::apply_after), also given the char `before` `prev`: an apostrophe - /// only continues a word when a letter or digit precedes it. - pub fn apply_between(self, s: &str, before: Option, prev: Option) -> String { - let continues = prev.is_some_and(|c| is_word_char(c) && (c.is_alphanumeric() || before.is_some_and(char::is_alphanumeric))); - self.apply_impl(s, prev, continues) - } - - /// `in_word` says whether `prev` continues a word (rather than a new word starting here). - fn apply_impl(self, s: &str, prev: Option, in_word: bool) -> String { - match self { - TextCase::Original | TextCase::SmallCaps => s.to_string(), - TextCase::Upper => s.to_uppercase(), - TextCase::Lower => s.to_lowercase(), - TextCase::Title => { - let mut out = String::with_capacity(s.len()); - let mut start = !in_word; - let mut last = prev; - for ch in s.chars() { - if start && ch.is_alphanumeric() { - out.extend(ch.to_uppercase()); - start = false; - } else { - out.push(ch); - // An apostrophe only continues a word right after a letter or digit. - let opening_apostrophe = - matches!(ch, '\'' | '\u{2019}') && !last.is_some_and(|c| c.is_alphanumeric() || is_combining_mark(c)); - // A combining mark attaches to the char before it and never changes word state. - if !is_combining_mark(ch) { - start = !is_word_char(ch) || opening_apostrophe; - } - } - last = Some(ch); - } - out - } - } - } - - /// Whether the char at a position preceded by `prev` starts a word (for title case). - pub fn starts_word(prev: Option) -> bool { - prev.is_none_or(|c| !is_word_char(c)) - } -} - -/// Letters, digits, combining marks and apostrophes continue a word (so "don't" stays "Don't" -/// and decomposed accents stay inside their word). -fn is_word_char(c: char) -> bool { - c.is_alphanumeric() || is_combining_mark(c) || matches!(c, '\'' | '\u{2019}') -} - -/// Combining marks such as the U+0301 accent in decomposed text: non-alphanumeric chars that -/// extend the grapheme of the char before them. -fn is_combining_mark(c: char) -> bool { - use unicode_segmentation::UnicodeSegmentation; - if c.is_ascii() || c.is_alphanumeric() { - return false; - } - let mut buf = [0u8; 8]; - buf[0] = b'a'; - let end = 1 + c.encode_utf8(&mut buf[1..]).len(); - std::str::from_utf8(&buf[..end]).is_ok_and(|s| s.graphemes(true).count() == 1) -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum TextAlignH { - #[default] - Left, - Center, - Right, - Justified, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum TextAlignV { - #[default] - Top, - Middle, - Bottom, -} - -/// How a text box resizes as its content changes. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum TextAutoResize { - /// Auto width: one line per paragraph, box grows both ways. - #[default] - WidthAndHeight, - /// Fixed width, height grows. - Height, - /// Fixed size. - None, - /// Fixed size, truncate with an ellipsis. - Truncate, -} - -/// Vertical trim: what bounds a text box vertically. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum LeadingTrim { - /// The full line height of the first and last lines. - #[default] - None, - /// From the first line's cap height to the last line's baseline. - CapHeight, -} - -/// Where lines break when text wraps to more than one line ("Wrap style controls where lines -/// break when text wraps to more than one line", Explore text properties). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum WrapStyle { - /// "Figma fits as many words as possible on each line before wrapping to the next." - #[default] - Auto, - /// "Figma distributes text as evenly as possible across every line, so each line is close to - /// the same length." - Balance, - /// "Figma keeps each line full, but adjusts the last four lines to avoid an orphan -- a single - /// word stranded alone on the last line." - Pretty, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum ListStyle { - #[default] - None, - Bulleted, - Numbered, -} - -/// Deepest list nesting (levels 0..=MAX_LIST_INDENT). -pub const MAX_LIST_INDENT: u8 = 8; - -/// One paragraph's list settings. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(default)] -pub struct ParaList { - pub list: ListStyle, - /// Nesting level (0 = outermost). A plain paragraph is 0, except one that left its list by - /// Backspace or Delete at its start ([`TextData::unlist_keeping_levels`]): it keeps the level - /// it had and starts where that level's item text does ("delete the counter, but keep the - /// same level of indentation"). - pub indent: u8, - /// A numbered list that starts counting at this paragraph counts from `start_offset + 1` - /// (items that go on counting ignore it; other paragraphs are always 0). - #[serde(skip_serializing_if = "crate::node::is_default")] - pub start_offset: u32, -} - -/// Character style. In runs, every field is an override; `None` means "inherit the base". -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct TextStyle { - pub font_family: String, - /// The style name, e.g. "Regular", "Bold", "Semi Bold Italic". - pub font_style: String, - pub font_size: f64, - pub line_height: LineHeight, - pub letter_spacing: LetterSpacing, - pub decoration: TextDecoration, - /// How the decoration looks (None: the default look; boxed to keep styles small). - #[serde(skip_serializing_if = "Option::is_none")] - pub decoration_look: Option>, - pub case: TextCase, - /// Run fills (None = node fills). - pub fills: Option>, - /// Hyperlink. - pub link: Option, - /// Variable font axis values in user space, keyed by 4-char OpenType axis tag (e.g. `wght`: - /// 550, `wdth`: 85). Empty = what the style name implies; axes the face lacks are ignored. - #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")] - pub variations: std::collections::BTreeMap, - /// The text style (shared style id) these chars are linked to. A layer's chars can link to - /// different styles; editing what a style sets unlinks the chars edited. - #[serde(skip_serializing_if = "Option::is_none")] - pub style_id: Option, -} - -/// What a text style sets at the paragraph and layer level, beside its character style -/// ([`TextStyle`]): paragraph spacing and indent, the list style and the OpenType features -/// ("Supported in text styles": "Paragraph spacing and indentation", "Lists", "OpenType -/// features", Create and apply text styles). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] -#[serde(default)] -pub struct ParagraphStyle { - #[serde(skip_serializing_if = "crate::node::is_default")] - pub paragraph_spacing: f64, - #[serde(skip_serializing_if = "crate::node::is_default")] - pub paragraph_indent: f64, - #[serde(skip_serializing_if = "crate::node::is_default")] - pub list: ListStyle, - #[serde(skip_serializing_if = "crate::node::is_default")] - pub features: std::collections::BTreeMap, -} - -/// The font new text starts in. A build can name another (`FIGCRAFT_DEFAULT_FONT="Noto Sans Thai"`, -/// for a distribution whose users mostly write a script Inter lacks); empty means Inter. -pub const DEFAULT_FONT: &str = match option_env!("FIGCRAFT_DEFAULT_FONT") { - Some(family) if !family.is_empty() => family, - _ => "Inter", -}; - -impl Default for TextStyle { - fn default() -> Self { - Self { - font_family: DEFAULT_FONT.into(), - font_style: "Regular".into(), - font_size: 12.0, - line_height: LineHeight::Auto, - letter_spacing: LetterSpacing::default(), - decoration: TextDecoration::None, - decoration_look: None, - case: TextCase::Original, - fills: None, - link: None, - variations: std::collections::BTreeMap::new(), - style_id: None, - } - } -} - -/// Axes a style name implies (weight, italic, slant): picking a named style clears their custom values. -pub const STYLE_AXES: [&str; 3] = ["wght", "ital", "slnt"]; - -impl TextStyle { - /// Numeric weight: a custom `wght` axis value, else the one implied by the style name. - pub fn weight(&self) -> u16 { - match self.variations.get("wght") { - Some(w) if w.is_finite() => w.round().clamp(1.0, 1000.0) as u16, - _ => style_weight(&self.font_style), - } - } - pub fn italic(&self) -> bool { - self.font_style.to_ascii_lowercase().contains("italic") - || self.variations.get("ital").is_some_and(|v| *v >= 0.5) - || self.variations.get("slnt").is_some_and(|v| *v != 0.0) - } - - /// Take what text style `def` sets (font, size, line height, letter spacing, decoration, case - /// and axis values) and link to it as `id`; fills and hyperlinks stay. - pub fn take_text_style(&mut self, def: &TextStyle, id: &str) { - *self = TextStyle { fills: self.fills.take(), link: self.link.take(), style_id: Some(id.to_string()), ..def.clone() }; - } - - /// Whether these chars show what text style `def` sets. - pub fn shows_text_style(&self, def: &TextStyle) -> bool { - self.font_family == def.font_family - && self.font_style == def.font_style - && self.font_size == def.font_size - && self.line_height == def.line_height - && self.letter_spacing == def.letter_spacing - && self.decoration == def.decoration - && self.decoration_look == def.decoration_look - && self.case == def.case - && self.variations == def.variations - } - - /// This style as a text style's definition (linked to nothing). - pub fn as_text_style(&self) -> TextStyle { - TextStyle { style_id: None, link: None, ..self.clone() } - } - - /// How the decoration looks. - pub fn look(&self) -> DecorationLook { - self.decoration_look.as_deref().copied().unwrap_or_default() - } - - /// Change how the decoration looks (the default look is stored as None). - pub fn set_look(&mut self, f: impl FnOnce(&mut DecorationLook)) { - let mut look = self.look(); - f(&mut look); - self.decoration_look = (look != DecorationLook::default()).then(|| Box::new(look)); - } - - /// Switch to the named style, dropping custom values of the axes the name implies. - pub fn set_font_style(&mut self, name: impl Into) { - self.font_style = name.into(); - for tag in STYLE_AXES { - self.variations.remove(tag); - } - } -} - -/// Weight from a style name ("Semi Bold Italic" → 600). -pub fn style_weight(style: &str) -> u16 { - let s = style.to_ascii_lowercase().replace([' ', '-'], ""); - // A weight number ("600", "600 Italic"), as some apps name styles. - let digits: String = s.chars().take_while(char::is_ascii_digit).collect(); - if let Ok(n) = digits.parse::() - && (1..=1000).contains(&n) - { - return n; - } - let table: [(&str, u16); 10] = [ - ("thin", 100), - ("extralight", 200), - ("ultralight", 200), - ("light", 300), - ("medium", 500), - ("semibold", 600), - ("demibold", 600), - ("extrabold", 800), - ("ultrabold", 800), - ("black", 900), - ]; - for (k, w) in table { - if s.contains(k) { - return w; - } - } - if s.contains("bold") { - return 700; - } - if s.contains("heavy") { - return 900; - } - 400 -} - -/// A styled range of characters (char indices, end exclusive). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct StyleRun { - pub start: usize, - pub end: usize, - pub style: TextStyle, -} - -/// Text node content. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] -#[serde(default)] -pub struct TextData { - pub characters: String, - pub style: TextStyle, - /// Ranges whose style differs from `style`; full styles (already merged), non-overlapping, sorted. - #[serde(skip_serializing_if = "crate::node::is_default")] - pub runs: Vec, - #[serde(skip_serializing_if = "crate::node::is_default")] - pub auto_resize: TextAutoResize, - #[serde(skip_serializing_if = "crate::node::is_default")] - pub align_h: TextAlignH, - #[serde(skip_serializing_if = "crate::node::is_default")] - pub align_v: TextAlignV, - #[serde(skip_serializing_if = "crate::node::is_default")] - pub paragraph_spacing: f64, - #[serde(skip_serializing_if = "crate::node::is_default")] - pub paragraph_indent: f64, - /// The list style of paragraphs `paragraphs` doesn't cover (all of them when it's empty). - #[serde(skip_serializing_if = "crate::node::is_default")] - pub list: ListStyle, - /// Per-paragraph list settings, by paragraph index; empty when every paragraph is `list` at - /// level 0. Kept in step with the characters by [`TextData::replace_range`]. - #[serde(skip_serializing_if = "Vec::is_empty")] - pub paragraphs: Vec, - /// Space between two items of a list (px), in place of the paragraph spacing. - #[serde(skip_serializing_if = "crate::node::is_default")] - pub list_spacing: f64, - /// Opening and closing punctuation at a line's aligned edge sits outside the box. - #[serde(skip_serializing_if = "crate::node::is_default")] - pub hanging_punctuation: bool, - /// List bullets and numbers sit outside the box; item text lines up with plain paragraphs. - #[serde(skip_serializing_if = "crate::node::is_default")] - pub hanging_list: bool, - /// Vertical trim (`capHeight`: the box runs from the first line's cap height to the last - /// line's baseline). - #[serde(skip_serializing_if = "crate::node::is_default")] - pub leading_trim: LeadingTrim, - /// Max lines when truncating, or before an auto-height text ends in an ellipsis (0 = as many - /// as fit). - #[serde(skip_serializing_if = "crate::node::is_default")] - pub max_lines: u32, - /// Where lines break when the text wraps: greedily (Auto), as evenly as the words allow - /// (Balance), or full with no one word alone on the last line (Pretty). - #[serde(skip_serializing_if = "crate::node::is_default")] - pub wrap_style: WrapStyle, - /// OpenType feature toggles (e.g. "liga": false). - #[serde(skip_serializing_if = "crate::node::is_default")] - pub features: std::collections::BTreeMap, - /// The path the text follows (text on a path); `None`: lines in the box. Boxed to keep text - /// data small. - #[serde(skip_serializing_if = "Option::is_none")] - pub path: Option>, - /// Where the file this text came from wrapped its lines (an imported `.fig`'s saved layout). - /// Layout follows them only while the box width and everything that moves a line break are - /// as they were saved, so an edit that could change the wrap drops them. - #[serde(skip_serializing_if = "Option::is_none")] - pub saved_breaks: Option>, -} - -/// Line breaks a file saved with a text: the chars that start a wrapped line (not those after a -/// hard break), for the box width and the content ([`TextData::layout_key`]) they were made for. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] -#[serde(default)] -pub struct SavedBreaks { - pub starts: Vec, - pub width: f64, - pub for_text: u64, -} - -/// Text on a path: the baseline follows `d`. The text starts at `start` (aligned there by the -/// horizontal alignment: left starts, centre centres, right ends at it); glyphs past an open -/// path's ends are hidden, a closed path wraps them around. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] -#[serde(default)] -pub struct TextPath { - /// SVG path data in the layer's own space. - pub d: String, - /// Where the text starts along the path, 0..1 by length. - pub start: f64, - /// On the other side of the path, running the other way. - #[serde(skip_serializing_if = "std::ops::Not::not")] - pub flip: bool, -} - -impl TextPath { - /// A text path following `path` (layer space). - pub fn new(path: &figcraft_geom::BezPath) -> Self { - Self { d: path.to_svg(), start: 0.0, flip: false } - } - - /// The path (empty when `d` doesn't parse). - pub fn path(&self) -> figcraft_geom::BezPath { - figcraft_geom::BezPath::from_svg(&self.d).unwrap_or_default() - } - - /// The start offset clamped into 0..1 (NaN: 0). - pub fn start(&self) -> f64 { - if self.start.is_finite() { self.start.clamp(0.0, 1.0) } else { 0.0 } - } - - /// Scale the path by `sx`, `sy` (the layer was resized). - pub fn scale(&mut self, sx: f64, sy: f64) { - if sx.is_finite() && sy.is_finite() { - let mut p = self.path(); - p.apply_affine(figcraft_geom::Affine::scale_non_uniform(sx, sy)); - self.d = p.to_svg(); - } - } -} - -/// Whether `tag` is a valid OpenType feature tag (four printable ASCII chars). -pub fn valid_feature_tag(tag: &str) -> bool { - tag.len() == 4 && tag.bytes().all(|b| (0x20..0x7f).contains(&b)) -} - -/// Whether `tag` is a valid OpenType variation axis tag (same shape as a feature tag). -pub fn valid_axis_tag(tag: &str) -> bool { - valid_feature_tag(tag) -} - -impl TextData { - pub fn new(characters: impl Into) -> Self { - Self { characters: characters.into(), ..Default::default() } - } - - /// A stable hash of what decides where lines break: everything but paints, links, style links, - /// decorations, vertical settings and the saved breaks themselves (FNV-1a over the JSON, so it - /// stays the same across builds and can be saved). - pub fn layout_key(&self) -> u64 { - let clear = |s: &mut TextStyle| { - (s.fills, s.link, s.style_id, s.decoration, s.decoration_look) = (None, None, None, TextDecoration::None, None); - }; - let mut t = TextData { - align_v: TextAlignV::default(), - paragraph_spacing: 0.0, - list_spacing: 0.0, - leading_trim: LeadingTrim::default(), - max_lines: 0, - saved_breaks: None, - ..self.clone() - }; - clear(&mut t.style); - t.runs.iter_mut().for_each(|r| clear(&mut r.style)); - t.normalize(); - serde_json::to_vec(&t).unwrap_or_default().iter().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) - } - - /// Keep `starts` (chars that start a wrapped line) as this text's saved line breaks in a box - /// `width` wide. - pub fn save_breaks(&mut self, starts: Vec, width: f64) { - self.saved_breaks = Some(Box::new(SavedBreaks { starts, width, for_text: self.layout_key() })); - } - - /// The saved line starts (empty: no wrapped line) while they still hold: the same box width and - /// layout content, and starts increasing inside the text. - pub fn saved_breaks_for(&self, width: f64) -> Option<&[usize]> { - let b = self.saved_breaks.as_deref()?; - let inside = b.starts.first().is_none_or(|s| *s > 0) && b.starts.last().is_none_or(|s| *s < self.char_count()); - let same_box = (b.width - width).abs() <= 1e-6 * width.abs().max(1.0); - (inside && same_box && b.starts.is_sorted_by(|a, b| a < b) && b.for_text == self.layout_key()).then_some(b.starts.as_slice()) - } - - /// How far text on a path paints past its path's box (glyphs stand on the path, lines after - /// the first run beside it): about one and a half of the largest size per line; 0 off a path. - pub fn path_reach(&self) -> f64 { - if self.path.is_none() { - return 0.0; - } - let lines = self.characters.lines().count().clamp(1, 10_000) as f64; - self.max_size() * 1.5 * lines - } - - /// How far vertically trimmed text paints past its box (descenders below the last baseline, - /// accents above the first cap height): half the largest size; 0 untrimmed. - pub fn trim_reach(&self) -> f64 { - if self.leading_trim == LeadingTrim::None { 0.0 } else { self.max_size() * 0.5 } - } - - /// The largest font size used (capped like layout caps it). - fn max_size(&self) -> f64 { - self.spans().iter().map(|(_, _, s)| s.font_size).filter(|v| v.is_finite()).fold(0.0, f64::max).min(5000.0) - } - - pub fn char_count(&self) -> usize { - self.characters.chars().count() - } - - /// Whether text that runs out of room ends in an ellipsis: a truncating box, or auto height - /// or auto width with a line limit (the box hugs up to `max_lines` lines: "Max lines is - /// available only if truncate text is enabled, and: Text resizing is set to auto height or - /// auto width"). - pub fn truncates(&self) -> bool { - match self.auto_resize { - TextAutoResize::Truncate => true, - TextAutoResize::Height | TextAutoResize::WidthAndHeight => self.max_lines > 0, - TextAutoResize::None => false, - } - } - - /// The resize mode once the box is given an explicit `width` and/or `height`: an explicit - /// height fixes the box, an explicit width turns auto width into auto height, and truncating - /// text keeps truncating. - pub fn fix_size(&mut self, width: bool, height: bool) { - self.auto_resize = match self.auto_resize { - _ if height && self.truncates() => TextAutoResize::Truncate, - _ if height => TextAutoResize::None, - TextAutoResize::WidthAndHeight if width => TextAutoResize::Height, - mode => mode, - }; - } - - /// The style at char index `i`. - pub fn style_at(&self, i: usize) -> &TextStyle { - self.runs.iter().find(|r| r.start <= i && i < r.end).map(|r| &r.style).unwrap_or(&self.style) - } - - /// Spans of uniform style covering the whole text: (start, end, style). - pub fn spans(&self) -> Vec<(usize, usize, &TextStyle)> { - let n = self.char_count(); - let mut out = Vec::new(); - let mut pos = 0; - let mut runs: Vec<&StyleRun> = self.runs.iter().filter(|r| r.start < r.end && r.start < n).collect(); - runs.sort_by_key(|r| r.start); - for r in runs { - let start = r.start.max(pos); - let end = r.end.min(n); - if start >= end { - continue; - } - if start > pos { - out.push((pos, start, &self.style)); - } - out.push((start, end, &r.style)); - pos = end; - } - if pos < n || out.is_empty() { - out.push((pos, n, &self.style)); - } - out - } - - /// Apply `f` to the style of chars `start..end` (all text when the range is the whole text or - /// empty text), splitting runs as needed and merging equal neighbours. - pub fn restyle(&mut self, start: usize, end: usize, f: impl Fn(&mut TextStyle)) { - let n = self.char_count(); - let (start, end) = (start.min(n), end.min(n)); - if n == 0 || (start == 0 && end >= n) { - f(&mut self.style); - for r in &mut self.runs { - f(&mut r.style); - } - self.normalize(); - return; - } - if start >= end { - return; - } - // Expand to per-char styles, modify, re-compress. - let mut per: Vec = (0..n).map(|i| self.style_at(i).clone()).collect(); - for s in per.iter_mut().take(end).skip(start) { - f(s); - } - self.runs.clear(); - let mut i = 0; - while i < n { - let Some(s) = per.get(i) else { break }; - let mut j = i + 1; - while per.get(j).is_some_and(|t| t == s) { - j += 1; - } - if *s != self.style { - self.runs.push(StyleRun { start: i, end: j, style: s.clone() }); - } - i = j; - } - } - - /// Drop empty/out-of-range runs and runs equal to the base style, and merge touching equal runs. - pub fn normalize(&mut self) { - let n = self.char_count(); - let base = self.style.clone(); - self.runs.retain(|r| r.start < r.end && r.start < n && r.style != base); - for r in &mut self.runs { - r.end = r.end.min(n); - } - self.runs.sort_by_key(|r| r.start); - let mut merged: Vec = Vec::with_capacity(self.runs.len()); - for mut r in std::mem::take(&mut self.runs) { - // Runs never overlap: a later run starts where the previous one ends at the earliest. - if let Some(prev) = merged.last() { - r.start = r.start.max(prev.end); - if r.start >= r.end { - continue; - } - } - match merged.last_mut() { - Some(prev) if prev.end == r.start && prev.style == r.style => prev.end = r.end, - _ => merged.push(r), - } - } - self.runs = merged; - } - - /// Replace chars `start..end` with `text`, shifting runs (inserted text takes the style at `start`). - pub fn replace_range(&mut self, start: usize, end: usize, text: &str) { - let n = self.char_count(); - let (start, end) = (start.min(n), end.min(n).max(start.min(n))); - let byte = |i: usize| self.characters.char_indices().nth(i).map(|(b, _)| b).unwrap_or(self.characters.len()); - let (bs, be) = (byte(start), byte(end)); - if !self.paragraphs.is_empty() { - // Paragraphs merged by removed newlines take the first one's list; new ones copy it. - let p = self.para_of(start); - let removed = self.characters.get(bs..be).unwrap_or("").matches('\n').count(); - let added = text.matches('\n').count(); - self.fill_paragraphs(); - let at = self.para_list(p); - let tail = (p + 1).min(self.paragraphs.len()); - self.paragraphs.drain(tail..(p + 1 + removed).min(self.paragraphs.len())); - self.paragraphs.splice(tail..tail, std::iter::repeat_n(at, added)); - } - let mut s = String::with_capacity(self.characters.len() + text.len()); - s.push_str(self.characters.get(..bs).unwrap_or("")); - s.push_str(text); - s.push_str(self.characters.get(be..).unwrap_or("")); - self.characters = s; - let inserted = text.chars().count(); - let removed = end - start; - for r in &mut self.runs { - let shift = |p: usize| -> usize { - if p <= start { - p - } else if p >= end { - // Runs of a file that reach past the text (nothing clamps them on load) - // would otherwise overflow here; `normalize` below drops what is left. - p.saturating_sub(removed).saturating_add(inserted) - } else { - start + inserted - } - }; - // A run touching the insertion point at its end grows with the typed text. - let new_start = shift(r.start); - let new_end = if r.end == start && r.start < start { start + inserted } else { shift(r.end) }; - r.start = new_start; - r.end = new_end; - } - self.normalize(); - } - - pub fn paragraph_count(&self) -> usize { - self.characters.matches('\n').count() + 1 - } - - /// The paragraph char index `i` is in. - pub fn para_of(&self, i: usize) -> usize { - self.characters.chars().take(i).filter(|c| *c == '\n').count() - } - - /// Paragraph `p`'s list settings. - pub fn para_list(&self, p: usize) -> ParaList { - self.paragraphs.get(p).copied().unwrap_or(ParaList { list: self.list, ..ParaList::default() }) - } - - /// Spell out every paragraph's list settings in `paragraphs` (and drop extra entries). - fn fill_paragraphs(&mut self) { - let n = self.paragraph_count(); - let fill = ParaList { list: self.list, ..ParaList::default() }; - self.paragraphs.resize(n, fill); - } - - /// The paragraphs chars `start..end` touch (a caret: its paragraph; a selection ending just - /// after a newline leaves the next paragraph out). - pub fn para_span(&self, start: usize, end: usize) -> (usize, usize) { - let (s, e) = (start.min(end), start.max(end)); - let (a, b) = (self.para_of(s), self.para_of(e)); - let ends_at_start = e > s && b > a && self.characters.chars().nth(e - 1) == Some('\n'); - (a, if ends_at_start { b - 1 } else { b }) - } - - /// Apply `f` to the list settings of the paragraphs chars `start..end` touch (plain - /// paragraphs stay at level 0, only numbered ones keep a start, levels stop at - /// [`MAX_LIST_INDENT`]); one style for all with no nesting or start folds back into `list`. - pub fn set_para_lists(&mut self, start: usize, end: usize, f: impl Fn(&mut ParaList)) { - self.set_para_lists_with(start, end, false, f); - } - - /// Take the list items among the paragraphs chars `start..end` touch out of their list at the - /// level they had, as Backspace or Delete at an item's start does: "delete the counter, but - /// keep the same level of indentation" (Create bulleted and numbered lists). - pub fn unlist_keeping_levels(&mut self, start: usize, end: usize) { - self.set_para_lists_with(start, end, true, |pl| pl.list = ListStyle::None); - } - - fn set_para_lists_with(&mut self, start: usize, end: usize, keep_levels: bool, f: impl Fn(&mut ParaList)) { - let (a, b) = self.para_span(start, end); - self.fill_paragraphs(); - for pl in self.paragraphs.get_mut(a..=b).unwrap_or(&mut []) { - f(pl); - if pl.list == ListStyle::None && !keep_levels { - pl.indent = 0; - } - if pl.list != ListStyle::Numbered { - pl.start_offset = 0; - } - pl.indent = pl.indent.min(MAX_LIST_INDENT); - } - if let Some(first) = self.paragraphs.first().copied() - && first == (ParaList { list: first.list, ..ParaList::default() }) - && self.paragraphs.iter().all(|p| *p == first) - { - self.list = first.list; - self.paragraphs.clear(); - } - } - - /// The list style and level shared by the paragraphs chars `start..end` touch (the first - /// one's settings), or None when they differ. Start numbers don't count. - pub fn common_para_list(&self, start: usize, end: usize) -> Option { - let (a, b) = self.para_span(start, end); - let first = self.para_list(a); - (a..=b).all(|p| self.para_list(p).list == first.list && self.para_list(p).indent == first.indent).then_some(first) - } - - /// What a text style made from this text sets at the paragraph and layer level: the paragraph - /// spacing and indent, the list style (the one every paragraph shares; the base one when they - /// differ) and the OpenType features. - pub fn paragraph_style(&self) -> ParagraphStyle { - let list = match self.paragraphs.first() { - Some(first) if self.paragraphs.iter().all(|p| p.list == first.list) => first.list, - _ => self.list, - }; - ParagraphStyle { paragraph_spacing: self.paragraph_spacing, paragraph_indent: self.paragraph_indent, list, features: self.features.clone() } - } - - /// Take what text style `ps` sets at the paragraph and layer level: the spacing, indent and - /// features on the layer, the list style on every paragraph. - pub fn take_paragraph_style(&mut self, ps: &ParagraphStyle) { - let len = self.char_count(); - self.take_paragraph_style_in(0, len, ps); - } - - /// As [`take_paragraph_style`](Self::take_paragraph_style), with the list style going to the - /// paragraphs chars `start..end` touch only; the spacing, indent and features are the - /// layer's, as in Figma. - pub fn take_paragraph_style_in(&mut self, start: usize, end: usize, ps: &ParagraphStyle) { - self.paragraph_spacing = ps.paragraph_spacing; - self.paragraph_indent = ps.paragraph_indent; - self.features.clone_from(&ps.features); - self.set_para_lists(start, end, |pl| pl.list = ps.list); - } - - /// Follow text style `id`'s paragraph-level definition wherever chars link to it. - pub fn update_paragraph_style(&mut self, id: &str, ps: &ParagraphStyle) { - let linked: Vec<(usize, usize)> = - self.spans().into_iter().filter(|(_, _, s)| s.style_id.as_deref() == Some(id)).map(|(a, b, _)| (a, b)).collect(); - for (a, b) in linked { - self.take_paragraph_style_in(a, b, ps); - } - } - - /// Whether chars `start..end` show what text style `ps` sets at the paragraph and layer - /// level: the layer's spacing, indent and features, and their paragraphs' list style. - pub fn shows_paragraph_style_in(&self, start: usize, end: usize, ps: &ParagraphStyle) -> bool { - self.paragraph_spacing == ps.paragraph_spacing - && self.paragraph_indent == ps.paragraph_indent - && self.features == ps.features - && self.common_para_list(start, end).is_some_and(|pl| pl.list == ps.list) - } - - /// Whether the whole text shows what text style `ps` sets at the paragraph and layer level. - pub fn shows_paragraph_style(&self, ps: &ParagraphStyle) -> bool { - self.shows_paragraph_style_in(0, self.char_count(), ps) - } - - /// Link chars `start..end` (all of them when the range is empty or the whole text) to text - /// style `id`, defined as `def`. - pub fn link_text_style(&mut self, start: usize, end: usize, def: &TextStyle, id: &str) { - let (start, end) = if start == end { (0, self.char_count()) } else { (start, end) }; - self.restyle(start, end, |s| s.take_text_style(def, id)); - } - - /// Unlink chars `start..end` (all when empty or whole) from their text styles; values stay. - pub fn unlink_text_style(&mut self, start: usize, end: usize) { - let (start, end) = if start == end { (0, self.char_count()) } else { (start, end) }; - self.restyle(start, end, |s| s.style_id = None); - } - - /// The text style every char is linked to: `Some(None)` when none is, None when they differ. - pub fn text_style_link(&self) -> Option> { - let mut spans = self.spans().into_iter().map(|(_, _, s)| s.style_id.as_deref()); - let first = spans.next()?; - spans.all(|s| s == first).then_some(first) - } - - /// Apply `f` to every distinct style (the base and each run) and merge runs that became equal. - pub(crate) fn each_style(&mut self, mut f: impl FnMut(&mut TextStyle)) { - f(&mut self.style); - for r in &mut self.runs { - f(&mut r.style); - } - self.normalize(); - } - - /// Whether any char links to text style `id`. - pub fn links_text_style(&self, id: &str) -> bool { - std::iter::once(&self.style).chain(self.runs.iter().map(|r| &r.style)).any(|s| s.style_id.as_deref() == Some(id)) - } - - /// Follow text style `id`'s new definition wherever chars link to it. - pub fn update_text_style(&mut self, id: &str, def: &TextStyle) { - self.each_style(|s| { - if s.style_id.as_deref() == Some(id) { - s.take_text_style(def, id); - } - }); - } - - /// Point text style links elsewhere: `f(id)` gives the new id, None unlinks (values stay). - pub fn map_text_styles(&mut self, f: impl Fn(&str) -> Option) { - self.each_style(|s| s.style_id = s.style_id.as_deref().and_then(&f)); - } - - /// Unlink chars whose style is gone (`def` gives None) or that no longer show it (edited since). - pub fn check_text_styles<'a>(&mut self, def: impl Fn(&str) -> Option<&'a TextStyle>) { - self.each_style(|s| { - if s.style_id.as_deref().is_some_and(|id| !def(id).is_some_and(|d| s.shows_text_style(d))) { - s.style_id = None; - } - }); - } - - /// Whether every char shares one style (the panel shows "Mixed" otherwise). - pub fn is_uniform(&self) -> bool { - self.runs.is_empty() - } -} - -#[cfg(test)] -mod case_tests { - use super::*; - - #[test] - fn trim_num_prints_huge_whole_numbers() { - assert_eq!(trim_num(1e19), "10000000000000000000"); - assert_eq!(trim_num(-1e19), "-10000000000000000000"); - assert_eq!(trim_num(12.0), "12"); - let v = 12345678901234567890.0_f64; - assert_eq!(trim_num(v).parse::().unwrap(), v); - } - - #[test] - fn title_case_respects_context() { - assert_eq!(TextCase::Title.apply("hello wORLD don't 3d x-ray"), "Hello WORLD Don't 3d X-Ray"); - // Continuing a word from a previous run: no capital. - assert_eq!(TextCase::Title.apply_after("lo world", Some('l')), "lo World"); - assert_eq!(TextCase::Title.apply_after("lo", Some(' ')), "Lo"); - assert_eq!(TextCase::Upper.apply_after("ß", Some('a')), "SS"); - assert!(valid_feature_tag("liga") && valid_feature_tag("ss01")); - assert!(!valid_feature_tag("lig") && !valid_feature_tag("ligatures") && !valid_feature_tag("li\u{e9}")); - } - - #[test] - fn new_text_starts_in_the_builds_default_font() { - // Inter, unless the build names another with `FIGCRAFT_DEFAULT_FONT` (empty means Inter). - let named = option_env!("FIGCRAFT_DEFAULT_FONT").filter(|f| !f.is_empty()); - assert_eq!(DEFAULT_FONT, named.unwrap_or("Inter")); - let st = TextStyle::default(); - assert_eq!(st.font_family, DEFAULT_FONT); - // The family is always written, so a saved file keeps it in a build with another default. - let saved = serde_json::to_value(&st).unwrap(); - assert_eq!(saved["font_family"], DEFAULT_FONT); - } - - #[test] - fn variations_are_backward_compatible_and_imply_weight() { - // Files written before variable fonts load with no custom axes, and stay byte-identical. - let old = r#"{"font_family":"Inter","font_style":"Bold","font_size":12.0}"#; - let st: TextStyle = serde_json::from_str(old).unwrap(); - assert!(st.variations.is_empty()); - assert!(!serde_json::to_string(&st).unwrap().contains("variations")); - let mut st = TextStyle { font_style: "Regular".into(), ..Default::default() }; - st.variations.insert("wght".into(), 640.0); - st.variations.insert("wdth".into(), 80.0); - assert_eq!(st.weight(), 640); - assert!(!st.italic()); - st.variations.insert("slnt".into(), -8.0); - assert!(st.italic()); - let round: TextStyle = serde_json::from_str(&serde_json::to_string(&st).unwrap()).unwrap(); - assert_eq!(round, st); - // Picking a named style drops the axes its name implies, keeps the others. - st.set_font_style("Bold"); - assert_eq!(st.weight(), 700); - assert_eq!(st.variations.keys().collect::>(), ["wdth"]); - assert!(valid_axis_tag("wght") && !valid_axis_tag("weight")); - } - - #[test] - fn list_starts_load_from_old_files_and_follow_edits() { - use ListStyle::{Bulleted as B, None as P, Numbered as N}; - // Files written before start numbers load with none, and write the same bytes. - let old = r#"{"list":"numbered","indent":1}"#; - let pl: ParaList = serde_json::from_str(old).unwrap(); - assert_eq!(pl, ParaList { list: N, indent: 1, start_offset: 0 }); - assert_eq!(serde_json::to_string(&pl).unwrap(), old); - // One numbered paragraph with a start keeps it (it doesn't fold into `list`). - let mut t = TextData { characters: "Next".into(), ..Default::default() }; - t.set_para_lists(0, 0, |p| *p = ParaList { list: N, indent: 0, start_offset: 1 }); - assert_eq!(t.para_list(0), ParaList { list: N, indent: 0, start_offset: 1 }); - // Enter copies it to the new item; different starts don't make the list mixed. - t.replace_range(4, 4, "\nMore"); - assert_eq!(t.para_list(1).start_offset, 1); - t.set_para_lists(5, 5, |p| p.start_offset = 0); - assert!(t.common_para_list(0, t.char_count()).is_some_and(|p| p.list == N)); - // Bullets have no number, so no start. - t.set_para_lists(0, 0, |p| *p = ParaList { list: B, indent: 1, start_offset: 4 }); - assert_eq!(t.para_list(0), ParaList { list: B, indent: 1, start_offset: 0 }); - // A plain paragraph has none. - t.set_para_lists(0, 0, |p| p.list = P); - assert_eq!(t.para_list(0), ParaList::default()); - } -} - -#[cfg(test)] -mod title_case_tests { - use super::TextCase; - - #[test] - fn title_case_after_opening_apostrophe() { - assert_eq!(TextCase::Title.apply("'hello world'"), "'Hello World'"); - assert_eq!(TextCase::Title.apply("say 'hi'"), "Say 'Hi'"); - assert_eq!(TextCase::Title.apply("don't"), "Don't"); - assert_eq!(TextCase::Title.apply("\u{2019}hello"), "\u{2019}Hello"); - } - - #[test] - fn title_case_between_runs_sees_char_before_apostrophe() { - assert_eq!(TextCase::Title.apply_after("t", Some('\'')), "t"); - assert_eq!(TextCase::Title.apply_between("hello", None, Some('\'')), "Hello"); - assert_eq!(TextCase::Title.apply_between("t", Some('n'), Some('\'')), "t"); - assert_eq!(TextCase::Title.apply_between("t", Some(' '), Some('\u{2019}')), "T"); - } - - #[test] - fn title_case_combining_marks_do_not_break_words() { - assert_eq!(TextCase::Title.apply("re\u{301}sume\u{301}"), "Re\u{301}sume\u{301}"); - assert_eq!(TextCase::Title.apply("re\u{301}sume\u{301} bon"), "Re\u{301}sume\u{301} Bon"); - assert_eq!(TextCase::Title.apply("a \u{301}b"), "A \u{301}B"); - assert_eq!(TextCase::Title.apply("cafe\u{301}'s"), "Cafe\u{301}'s"); - } -} +//! Text node data: characters plus a base style and styled runs. + +use figcraft_color::{Color, Paint}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "unit", content = "value", rename_all = "camelCase")] +#[derive(Default)] +pub enum LineHeight { + #[default] + Auto, + Pixels(f64), + Percent(f64), +} + +impl LineHeight { + /// Resolved line height in px for `font_size` (`auto` uses the font's natural ratio). + pub fn resolve(self, font_size: f64, natural_ratio: f64) -> f64 { + match self { + LineHeight::Auto => font_size * natural_ratio, + LineHeight::Pixels(v) => v.max(0.0), + LineHeight::Percent(p) => font_size * p.max(0.0) / 100.0, + } + } + pub fn label(self) -> String { + match self { + LineHeight::Auto => "Auto".into(), + LineHeight::Pixels(v) => trim_num(v), + LineHeight::Percent(p) => format!("{}%", trim_num(p)), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "unit", content = "value", rename_all = "camelCase")] +pub enum LetterSpacing { + Pixels(f64), + Percent(f64), +} + +impl Default for LetterSpacing { + fn default() -> Self { + LetterSpacing::Percent(0.0) + } +} + +impl LetterSpacing { + pub fn resolve(self, font_size: f64) -> f64 { + match self { + LetterSpacing::Pixels(v) => v, + LetterSpacing::Percent(p) => font_size * p / 100.0, + } + } + pub fn label(self) -> String { + match self { + LetterSpacing::Pixels(v) => trim_num(v), + LetterSpacing::Percent(p) => format!("{}%", trim_num(p)), + } + } +} + +pub fn trim_num(v: f64) -> String { + if v.abs() >= 9.0e18 { + return format!("{v}"); + } + let r = (v * 100.0).round() / 100.0; + if r.fract().abs() < 1e-9 { format!("{}", r as i64) } else { format!("{r}") } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum TextDecoration { + #[default] + None, + Underline, + Strikethrough, +} + +/// How an underline or strikethrough is drawn. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum DecorationStyle { + #[default] + Solid, + Dotted, + Wavy, +} + +/// A decoration length: `Auto` (the font's own value), pixels, or a percentage of the font size. +pub type DecorationLength = LineHeight; + +/// How a decoration line looks; the default is the font's own solid line in the text's colour. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct DecorationLook { + pub style: DecorationStyle, + pub thickness: DecorationLength, + /// Underlines: from the baseline down to the line's top edge (negative: above the baseline). + pub offset: DecorationLength, + /// Underlines break where descenders cross them. + pub skip_ink: bool, + /// The line's own colour (None: the text's fills). + pub color: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum TextCase { + #[default] + Original, + Upper, + Lower, + Title, + SmallCaps, +} + +impl TextCase { + pub fn apply(self, s: &str) -> String { + self.apply_after(s, None) + } + + /// Apply the case to `s`, which follows `prev` in the text (so title case only capitalises + /// the first letter of each word even when a word spans several styled runs). An apostrophe + /// as `prev` is taken to continue a word. + pub fn apply_after(self, s: &str, prev: Option) -> String { + self.apply_impl(s, prev, prev.is_some_and(is_word_char)) + } + + /// Like [`apply_after`](Self::apply_after), also given the char `before` `prev`: an apostrophe + /// only continues a word when a letter or digit precedes it. + pub fn apply_between(self, s: &str, before: Option, prev: Option) -> String { + let continues = prev.is_some_and(|c| is_word_char(c) && (c.is_alphanumeric() || before.is_some_and(char::is_alphanumeric))); + self.apply_impl(s, prev, continues) + } + + /// `in_word` says whether `prev` continues a word (rather than a new word starting here). + fn apply_impl(self, s: &str, prev: Option, in_word: bool) -> String { + match self { + TextCase::Original | TextCase::SmallCaps => s.to_string(), + TextCase::Upper => s.to_uppercase(), + TextCase::Lower => s.to_lowercase(), + TextCase::Title => { + let mut out = String::with_capacity(s.len()); + let mut start = !in_word; + let mut last = prev; + for ch in s.chars() { + if start && ch.is_alphanumeric() { + out.extend(ch.to_uppercase()); + start = false; + } else { + out.push(ch); + // An apostrophe only continues a word right after a letter or digit. + let opening_apostrophe = + matches!(ch, '\'' | '\u{2019}') && !last.is_some_and(|c| c.is_alphanumeric() || is_combining_mark(c)); + // A combining mark attaches to the char before it and never changes word state. + if !is_combining_mark(ch) { + start = !is_word_char(ch) || opening_apostrophe; + } + } + last = Some(ch); + } + out + } + } + } + + /// Whether the char at a position preceded by `prev` starts a word (for title case). + pub fn starts_word(prev: Option) -> bool { + prev.is_none_or(|c| !is_word_char(c)) + } +} + +/// Letters, digits, combining marks and apostrophes continue a word (so "don't" stays "Don't" +/// and decomposed accents stay inside their word). +fn is_word_char(c: char) -> bool { + c.is_alphanumeric() || is_combining_mark(c) || matches!(c, '\'' | '\u{2019}') +} + +/// Combining marks such as the U+0301 accent in decomposed text: non-alphanumeric chars that +/// extend the grapheme of the char before them. +fn is_combining_mark(c: char) -> bool { + use unicode_segmentation::UnicodeSegmentation; + if c.is_ascii() || c.is_alphanumeric() { + return false; + } + let mut buf = [0u8; 8]; + buf[0] = b'a'; + let end = 1 + c.encode_utf8(&mut buf[1..]).len(); + std::str::from_utf8(&buf[..end]).is_ok_and(|s| s.graphemes(true).count() == 1) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum TextAlignH { + #[default] + Left, + Center, + Right, + Justified, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum TextAlignV { + #[default] + Top, + Middle, + Bottom, +} + +/// How a text box resizes as its content changes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum TextAutoResize { + /// Auto width: one line per paragraph, box grows both ways. + #[default] + WidthAndHeight, + /// Fixed width, height grows. + Height, + /// Fixed size. + None, + /// Fixed size, truncate with an ellipsis. + Truncate, +} + +/// Vertical trim: what bounds a text box vertically. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum LeadingTrim { + /// The full line height of the first and last lines. + #[default] + None, + /// From the first line's cap height to the last line's baseline. + CapHeight, +} + +/// Where lines break when text wraps to more than one line ("Wrap style controls where lines +/// break when text wraps to more than one line", Explore text properties). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum WrapStyle { + /// "Figma fits as many words as possible on each line before wrapping to the next." + #[default] + Auto, + /// "Figma distributes text as evenly as possible across every line, so each line is close to + /// the same length." + Balance, + /// "Figma keeps each line full, but adjusts the last four lines to avoid an orphan -- a single + /// word stranded alone on the last line." + Pretty, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum ListStyle { + #[default] + None, + Bulleted, + Numbered, +} + +/// Deepest list nesting (levels 0..=MAX_LIST_INDENT). +pub const MAX_LIST_INDENT: u8 = 8; + +/// One paragraph's list settings. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct ParaList { + pub list: ListStyle, + /// Nesting level (0 = outermost). A plain paragraph is 0, except one that left its list by + /// Backspace or Delete at its start ([`TextData::unlist_keeping_levels`]): it keeps the level + /// it had and starts where that level's item text does ("delete the counter, but keep the + /// same level of indentation"). + pub indent: u8, + /// A numbered list that starts counting at this paragraph counts from `start_offset + 1` + /// (items that go on counting ignore it; other paragraphs are always 0). + #[serde(skip_serializing_if = "crate::node::is_default")] + pub start_offset: u32, +} + +/// Character style. In runs, every field is an override; `None` means "inherit the base". +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct TextStyle { + pub font_family: String, + /// The style name, e.g. "Regular", "Bold", "Semi Bold Italic". + pub font_style: String, + pub font_size: f64, + pub line_height: LineHeight, + pub letter_spacing: LetterSpacing, + pub decoration: TextDecoration, + /// How the decoration looks (None: the default look; boxed to keep styles small). + #[serde(skip_serializing_if = "Option::is_none")] + pub decoration_look: Option>, + pub case: TextCase, + /// Run fills (None = node fills). + pub fills: Option>, + /// Hyperlink. + pub link: Option, + /// Variable font axis values in user space, keyed by 4-char OpenType axis tag (e.g. `wght`: + /// 550, `wdth`: 85). Empty = what the style name implies; axes the face lacks are ignored. + #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub variations: std::collections::BTreeMap, + /// The text style (shared style id) these chars are linked to. A layer's chars can link to + /// different styles; editing what a style sets unlinks the chars edited. + #[serde(skip_serializing_if = "Option::is_none")] + pub style_id: Option, +} + +/// What a text style sets at the paragraph and layer level, beside its character style +/// ([`TextStyle`]): paragraph spacing and indent, the list style and the OpenType features +/// ("Supported in text styles": "Paragraph spacing and indentation", "Lists", "OpenType +/// features", Create and apply text styles). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct ParagraphStyle { + #[serde(skip_serializing_if = "crate::node::is_default")] + pub paragraph_spacing: f64, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub paragraph_indent: f64, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub list: ListStyle, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub features: std::collections::BTreeMap, +} + +/// The font new text starts in. A build can name another (`FIGCRAFT_DEFAULT_FONT="Noto Sans Thai"`, +/// for a distribution whose users mostly write a script Inter lacks); empty means Inter. +pub const DEFAULT_FONT: &str = match option_env!("FIGCRAFT_DEFAULT_FONT") { + Some(family) if !family.is_empty() => family, + _ => "Inter", +}; + +impl Default for TextStyle { + fn default() -> Self { + Self { + font_family: DEFAULT_FONT.into(), + font_style: "Regular".into(), + font_size: 12.0, + line_height: LineHeight::Auto, + letter_spacing: LetterSpacing::default(), + decoration: TextDecoration::None, + decoration_look: None, + case: TextCase::Original, + fills: None, + link: None, + variations: std::collections::BTreeMap::new(), + style_id: None, + } + } +} + +/// Axes a style name implies (weight, italic, slant): picking a named style clears their custom values. +pub const STYLE_AXES: [&str; 3] = ["wght", "ital", "slnt"]; + +impl TextStyle { + /// Numeric weight: a custom `wght` axis value, else the one implied by the style name. + pub fn weight(&self) -> u16 { + match self.variations.get("wght") { + Some(w) if w.is_finite() => w.round().clamp(1.0, 1000.0) as u16, + _ => style_weight(&self.font_style), + } + } + pub fn italic(&self) -> bool { + self.font_style.to_ascii_lowercase().contains("italic") + || self.variations.get("ital").is_some_and(|v| *v >= 0.5) + || self.variations.get("slnt").is_some_and(|v| *v != 0.0) + } + + /// Take what text style `def` sets (font, size, line height, letter spacing, decoration, case + /// and axis values) and link to it as `id`; fills and hyperlinks stay. + pub fn take_text_style(&mut self, def: &TextStyle, id: &str) { + *self = TextStyle { fills: self.fills.take(), link: self.link.take(), style_id: Some(id.to_string()), ..def.clone() }; + } + + /// Whether these chars show what text style `def` sets. + pub fn shows_text_style(&self, def: &TextStyle) -> bool { + self.font_family == def.font_family + && self.font_style == def.font_style + && self.font_size == def.font_size + && self.line_height == def.line_height + && self.letter_spacing == def.letter_spacing + && self.decoration == def.decoration + && self.decoration_look == def.decoration_look + && self.case == def.case + && self.variations == def.variations + } + + /// This style as a text style's definition (linked to nothing). + pub fn as_text_style(&self) -> TextStyle { + TextStyle { style_id: None, link: None, ..self.clone() } + } + + /// How the decoration looks. + pub fn look(&self) -> DecorationLook { + self.decoration_look.as_deref().copied().unwrap_or_default() + } + + /// Change how the decoration looks (the default look is stored as None). + pub fn set_look(&mut self, f: impl FnOnce(&mut DecorationLook)) { + let mut look = self.look(); + f(&mut look); + self.decoration_look = (look != DecorationLook::default()).then(|| Box::new(look)); + } + + /// Switch to the named style, dropping custom values of the axes the name implies. + pub fn set_font_style(&mut self, name: impl Into) { + self.font_style = name.into(); + for tag in STYLE_AXES { + self.variations.remove(tag); + } + } +} + +/// Weight from a style name ("Semi Bold Italic" → 600). +pub fn style_weight(style: &str) -> u16 { + let s = style.to_ascii_lowercase().replace([' ', '-'], ""); + // A weight number ("600", "600 Italic"), as some apps name styles. + let digits: String = s.chars().take_while(char::is_ascii_digit).collect(); + if let Ok(n) = digits.parse::() + && (1..=1000).contains(&n) + { + return n; + } + let table: [(&str, u16); 10] = [ + ("thin", 100), + ("extralight", 200), + ("ultralight", 200), + ("light", 300), + ("medium", 500), + ("semibold", 600), + ("demibold", 600), + ("extrabold", 800), + ("ultrabold", 800), + ("black", 900), + ]; + for (k, w) in table { + if s.contains(k) { + return w; + } + } + if s.contains("bold") { + return 700; + } + if s.contains("heavy") { + return 900; + } + 400 +} + +/// A styled range of characters (char indices, end exclusive). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct StyleRun { + pub start: usize, + pub end: usize, + pub style: TextStyle, +} + +/// Text node content. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct TextData { + pub characters: String, + pub style: TextStyle, + /// Ranges whose style differs from `style`; full styles (already merged), non-overlapping, sorted. + #[serde(skip_serializing_if = "crate::node::is_default")] + pub runs: Vec, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub auto_resize: TextAutoResize, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub align_h: TextAlignH, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub align_v: TextAlignV, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub paragraph_spacing: f64, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub paragraph_indent: f64, + /// The list style of paragraphs `paragraphs` doesn't cover (all of them when it's empty). + #[serde(skip_serializing_if = "crate::node::is_default")] + pub list: ListStyle, + /// Per-paragraph list settings, by paragraph index; empty when every paragraph is `list` at + /// level 0. Kept in step with the characters by [`TextData::replace_range`]. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub paragraphs: Vec, + /// Space between two items of a list (px), in place of the paragraph spacing. + #[serde(skip_serializing_if = "crate::node::is_default")] + pub list_spacing: f64, + /// Opening and closing punctuation at a line's aligned edge sits outside the box. + #[serde(skip_serializing_if = "crate::node::is_default")] + pub hanging_punctuation: bool, + /// List bullets and numbers sit outside the box; item text lines up with plain paragraphs. + #[serde(skip_serializing_if = "crate::node::is_default")] + pub hanging_list: bool, + /// Vertical trim (`capHeight`: the box runs from the first line's cap height to the last + /// line's baseline). + #[serde(skip_serializing_if = "crate::node::is_default")] + pub leading_trim: LeadingTrim, + /// Max lines when truncating, or before an auto-height text ends in an ellipsis (0 = as many + /// as fit). + #[serde(skip_serializing_if = "crate::node::is_default")] + pub max_lines: u32, + /// Where lines break when the text wraps: greedily (Auto), as evenly as the words allow + /// (Balance), or full with no one word alone on the last line (Pretty). + #[serde(skip_serializing_if = "crate::node::is_default")] + pub wrap_style: WrapStyle, + /// OpenType feature toggles (e.g. "liga": false). + #[serde(skip_serializing_if = "crate::node::is_default")] + pub features: std::collections::BTreeMap, + /// The path the text follows (text on a path); `None`: lines in the box. Boxed to keep text + /// data small. + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option>, + /// Where the file this text came from wrapped its lines (an imported `.fig`'s saved layout). + /// Layout follows them only while the box width and everything that moves a line break are + /// as they were saved, so an edit that could change the wrap drops them. + #[serde(skip_serializing_if = "Option::is_none")] + pub saved_breaks: Option>, +} + +/// Line breaks a file saved with a text: the chars that start a wrapped line (not those after a +/// hard break), for the box width and the content ([`TextData::layout_key`]) they were made for. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct SavedBreaks { + pub starts: Vec, + pub width: f64, + pub for_text: u64, +} + +/// Text on a path: the baseline follows `d`. The text starts at `start` (aligned there by the +/// horizontal alignment: left starts, centre centres, right ends at it); glyphs past an open +/// path's ends are hidden, a closed path wraps them around. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct TextPath { + /// SVG path data in the layer's own space. + pub d: String, + /// Where the text starts along the path, 0..1 by length. + pub start: f64, + /// On the other side of the path, running the other way. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub flip: bool, +} + +impl TextPath { + /// A text path following `path` (layer space). + pub fn new(path: &figcraft_geom::BezPath) -> Self { + Self { d: path.to_svg(), start: 0.0, flip: false } + } + + /// The path (empty when `d` doesn't parse). + pub fn path(&self) -> figcraft_geom::BezPath { + figcraft_geom::BezPath::from_svg(&self.d).unwrap_or_default() + } + + /// The start offset clamped into 0..1 (NaN: 0). + pub fn start(&self) -> f64 { + if self.start.is_finite() { self.start.clamp(0.0, 1.0) } else { 0.0 } + } + + /// Scale the path by `sx`, `sy` (the layer was resized). + pub fn scale(&mut self, sx: f64, sy: f64) { + if sx.is_finite() && sy.is_finite() { + let mut p = self.path(); + p.apply_affine(figcraft_geom::Affine::scale_non_uniform(sx, sy)); + self.d = p.to_svg(); + } + } +} + +/// Whether `tag` is a valid OpenType feature tag (four printable ASCII chars). +pub fn valid_feature_tag(tag: &str) -> bool { + tag.len() == 4 && tag.bytes().all(|b| (0x20..0x7f).contains(&b)) +} + +/// Whether `tag` is a valid OpenType variation axis tag (same shape as a feature tag). +pub fn valid_axis_tag(tag: &str) -> bool { + valid_feature_tag(tag) +} + +impl TextData { + pub fn new(characters: impl Into) -> Self { + Self { characters: characters.into(), ..Default::default() } + } + + /// A stable hash of what decides where lines break: everything but paints, links, style links, + /// decorations, vertical settings and the saved breaks themselves (FNV-1a over the JSON, so it + /// stays the same across builds and can be saved). + pub fn layout_key(&self) -> u64 { + let clear = |s: &mut TextStyle| { + (s.fills, s.link, s.style_id, s.decoration, s.decoration_look) = (None, None, None, TextDecoration::None, None); + }; + let mut t = TextData { + align_v: TextAlignV::default(), + paragraph_spacing: 0.0, + list_spacing: 0.0, + leading_trim: LeadingTrim::default(), + max_lines: 0, + saved_breaks: None, + ..self.clone() + }; + clear(&mut t.style); + t.runs.iter_mut().for_each(|r| clear(&mut r.style)); + t.normalize(); + serde_json::to_vec(&t).unwrap_or_default().iter().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) + } + + /// Keep `starts` (chars that start a wrapped line) as this text's saved line breaks in a box + /// `width` wide. + pub fn save_breaks(&mut self, starts: Vec, width: f64) { + self.saved_breaks = Some(Box::new(SavedBreaks { starts, width, for_text: self.layout_key() })); + } + + /// The saved line starts (empty: no wrapped line) while they still hold: the same box width and + /// layout content, and starts increasing inside the text. + pub fn saved_breaks_for(&self, width: f64) -> Option<&[usize]> { + let b = self.saved_breaks.as_deref()?; + let inside = b.starts.first().is_none_or(|s| *s > 0) && b.starts.last().is_none_or(|s| *s < self.char_count()); + let same_box = (b.width - width).abs() <= 1e-6 * width.abs().max(1.0); + (inside && same_box && b.starts.is_sorted_by(|a, b| a < b) && b.for_text == self.layout_key()).then_some(b.starts.as_slice()) + } + + /// How far text on a path paints past its path's box (glyphs stand on the path, lines after + /// the first run beside it): about one and a half of the largest size per line; 0 off a path. + pub fn path_reach(&self) -> f64 { + if self.path.is_none() { + return 0.0; + } + let lines = self.characters.lines().count().clamp(1, 10_000) as f64; + self.max_size() * 1.5 * lines + } + + /// How far vertically trimmed text paints past its box (descenders below the last baseline, + /// accents above the first cap height): half the largest size; 0 untrimmed. + pub fn trim_reach(&self) -> f64 { + if self.leading_trim == LeadingTrim::None { 0.0 } else { self.max_size() * 0.5 } + } + + /// The largest font size used (capped like layout caps it). + fn max_size(&self) -> f64 { + self.spans().iter().map(|(_, _, s)| s.font_size).filter(|v| v.is_finite()).fold(0.0, f64::max).min(5000.0) + } + + pub fn char_count(&self) -> usize { + self.characters.chars().count() + } + + /// Whether text that runs out of room ends in an ellipsis: a truncating box, or auto height + /// or auto width with a line limit (the box hugs up to `max_lines` lines: "Max lines is + /// available only if truncate text is enabled, and: Text resizing is set to auto height or + /// auto width"). + pub fn truncates(&self) -> bool { + match self.auto_resize { + TextAutoResize::Truncate => true, + TextAutoResize::Height | TextAutoResize::WidthAndHeight => self.max_lines > 0, + TextAutoResize::None => false, + } + } + + /// The resize mode once the box is given an explicit `width` and/or `height`: an explicit + /// height fixes the box, an explicit width turns auto width into auto height, and truncating + /// text keeps truncating. + pub fn fix_size(&mut self, width: bool, height: bool) { + self.auto_resize = match self.auto_resize { + _ if height && self.truncates() => TextAutoResize::Truncate, + _ if height => TextAutoResize::None, + TextAutoResize::WidthAndHeight if width => TextAutoResize::Height, + mode => mode, + }; + } + + /// The style at char index `i`. + pub fn style_at(&self, i: usize) -> &TextStyle { + self.runs.iter().find(|r| r.start <= i && i < r.end).map(|r| &r.style).unwrap_or(&self.style) + } + + /// Spans of uniform style covering the whole text: (start, end, style). + pub fn spans(&self) -> Vec<(usize, usize, &TextStyle)> { + let n = self.char_count(); + let mut out = Vec::new(); + let mut pos = 0; + let mut runs: Vec<&StyleRun> = self.runs.iter().filter(|r| r.start < r.end && r.start < n).collect(); + runs.sort_by_key(|r| r.start); + for r in runs { + let start = r.start.max(pos); + let end = r.end.min(n); + if start >= end { + continue; + } + if start > pos { + out.push((pos, start, &self.style)); + } + out.push((start, end, &r.style)); + pos = end; + } + if pos < n || out.is_empty() { + out.push((pos, n, &self.style)); + } + out + } + + /// Apply `f` to the style of chars `start..end` (all text when the range is the whole text or + /// empty text), splitting runs as needed and merging equal neighbours. + pub fn restyle(&mut self, start: usize, end: usize, f: impl Fn(&mut TextStyle)) { + let n = self.char_count(); + let (start, end) = (start.min(n), end.min(n)); + if n == 0 || (start == 0 && end >= n) { + f(&mut self.style); + for r in &mut self.runs { + f(&mut r.style); + } + self.normalize(); + return; + } + if start >= end { + return; + } + // Expand to per-char styles, modify, re-compress. + let mut per: Vec = (0..n).map(|i| self.style_at(i).clone()).collect(); + for s in per.iter_mut().take(end).skip(start) { + f(s); + } + self.runs.clear(); + let mut i = 0; + while i < n { + let Some(s) = per.get(i) else { break }; + let mut j = i + 1; + while per.get(j).is_some_and(|t| t == s) { + j += 1; + } + if *s != self.style { + self.runs.push(StyleRun { start: i, end: j, style: s.clone() }); + } + i = j; + } + } + + /// Drop empty/out-of-range runs and runs equal to the base style, and merge touching equal runs. + pub fn normalize(&mut self) { + let n = self.char_count(); + let base = self.style.clone(); + self.runs.retain(|r| r.start < r.end && r.start < n && r.style != base); + for r in &mut self.runs { + r.end = r.end.min(n); + } + self.runs.sort_by_key(|r| r.start); + let mut merged: Vec = Vec::with_capacity(self.runs.len()); + for mut r in std::mem::take(&mut self.runs) { + // Runs never overlap: a later run starts where the previous one ends at the earliest. + if let Some(prev) = merged.last() { + r.start = r.start.max(prev.end); + if r.start >= r.end { + continue; + } + } + match merged.last_mut() { + Some(prev) if prev.end == r.start && prev.style == r.style => prev.end = r.end, + _ => merged.push(r), + } + } + self.runs = merged; + } + + /// Replace chars `start..end` with `text`, shifting runs (inserted text takes the style at `start`). + pub fn replace_range(&mut self, start: usize, end: usize, text: &str) { + let n = self.char_count(); + let (start, end) = (start.min(n), end.min(n).max(start.min(n))); + let byte = |i: usize| self.characters.char_indices().nth(i).map(|(b, _)| b).unwrap_or(self.characters.len()); + let (bs, be) = (byte(start), byte(end)); + if !self.paragraphs.is_empty() { + // Paragraphs merged by removed newlines take the first one's list; new ones copy it. + let p = self.para_of(start); + let removed = self.characters.get(bs..be).unwrap_or("").matches('\n').count(); + let added = text.matches('\n').count(); + self.fill_paragraphs(); + let at = self.para_list(p); + let tail = (p + 1).min(self.paragraphs.len()); + self.paragraphs.drain(tail..(p + 1 + removed).min(self.paragraphs.len())); + self.paragraphs.splice(tail..tail, std::iter::repeat_n(at, added)); + } + let mut s = String::with_capacity(self.characters.len() + text.len()); + s.push_str(self.characters.get(..bs).unwrap_or("")); + s.push_str(text); + s.push_str(self.characters.get(be..).unwrap_or("")); + self.characters = s; + let inserted = text.chars().count(); + let removed = end - start; + for r in &mut self.runs { + let shift = |p: usize| -> usize { + if p <= start { + p + } else if p >= end { + // Runs of a file that reach past the text (nothing clamps them on load) + // would otherwise overflow here; `normalize` below drops what is left. + p.saturating_sub(removed).saturating_add(inserted) + } else { + start + inserted + } + }; + // A run touching the insertion point at its end grows with the typed text. + let new_start = shift(r.start); + let new_end = if r.end == start && r.start < start { start + inserted } else { shift(r.end) }; + r.start = new_start; + r.end = new_end; + } + self.normalize(); + } + + pub fn paragraph_count(&self) -> usize { + self.characters.matches('\n').count() + 1 + } + + /// The paragraph char index `i` is in. + pub fn para_of(&self, i: usize) -> usize { + self.characters.chars().take(i).filter(|c| *c == '\n').count() + } + + /// Paragraph `p`'s list settings. + pub fn para_list(&self, p: usize) -> ParaList { + self.paragraphs.get(p).copied().unwrap_or(ParaList { list: self.list, ..ParaList::default() }) + } + + /// Spell out every paragraph's list settings in `paragraphs` (and drop extra entries). + fn fill_paragraphs(&mut self) { + let n = self.paragraph_count(); + let fill = ParaList { list: self.list, ..ParaList::default() }; + self.paragraphs.resize(n, fill); + } + + /// The paragraphs chars `start..end` touch (a caret: its paragraph; a selection ending just + /// after a newline leaves the next paragraph out). + pub fn para_span(&self, start: usize, end: usize) -> (usize, usize) { + let (s, e) = (start.min(end), start.max(end)); + let (a, b) = (self.para_of(s), self.para_of(e)); + let ends_at_start = e > s && b > a && self.characters.chars().nth(e - 1) == Some('\n'); + (a, if ends_at_start { b - 1 } else { b }) + } + + /// Apply `f` to the list settings of the paragraphs chars `start..end` touch (plain + /// paragraphs stay at level 0, only numbered ones keep a start, levels stop at + /// [`MAX_LIST_INDENT`]); one style for all with no nesting or start folds back into `list`. + pub fn set_para_lists(&mut self, start: usize, end: usize, f: impl Fn(&mut ParaList)) { + self.set_para_lists_with(start, end, false, f); + } + + /// Take the list items among the paragraphs chars `start..end` touch out of their list at the + /// level they had, as Backspace or Delete at an item's start does: "delete the counter, but + /// keep the same level of indentation" (Create bulleted and numbered lists). + pub fn unlist_keeping_levels(&mut self, start: usize, end: usize) { + self.set_para_lists_with(start, end, true, |pl| pl.list = ListStyle::None); + } + + fn set_para_lists_with(&mut self, start: usize, end: usize, keep_levels: bool, f: impl Fn(&mut ParaList)) { + let (a, b) = self.para_span(start, end); + self.set_para_lists_between(a, b, keep_levels, f); + } + + /// As [`set_para_lists`](Self::set_para_lists), for paragraphs `a..=b` addressed directly. + fn set_para_lists_between(&mut self, a: usize, b: usize, keep_levels: bool, f: impl Fn(&mut ParaList)) { + self.fill_paragraphs(); + for pl in self.paragraphs.get_mut(a..=b).unwrap_or(&mut []) { + f(pl); + if pl.list == ListStyle::None && !keep_levels { + pl.indent = 0; + } + if pl.list != ListStyle::Numbered { + pl.start_offset = 0; + } + pl.indent = pl.indent.min(MAX_LIST_INDENT); + } + if let Some(first) = self.paragraphs.first().copied() + && first == (ParaList { list: first.list, ..ParaList::default() }) + && self.paragraphs.iter().all(|p| *p == first) + { + self.list = first.list; + self.paragraphs.clear(); + } + } + + /// The list style and level shared by the paragraphs chars `start..end` touch (the first + /// one's settings), or None when they differ. Start numbers don't count. + pub fn common_para_list(&self, start: usize, end: usize) -> Option { + let (a, b) = self.para_span(start, end); + let first = self.para_list(a); + (a..=b).all(|p| self.para_list(p).list == first.list && self.para_list(p).indent == first.indent).then_some(first) + } + + /// What a text style made from this text sets at the paragraph and layer level: the paragraph + /// spacing and indent, the list style (the one every paragraph shares; the base one when they + /// differ) and the OpenType features. + pub fn paragraph_style(&self) -> ParagraphStyle { + let list = match self.paragraphs.first() { + Some(first) if self.paragraphs.iter().all(|p| p.list == first.list) => first.list, + _ => self.list, + }; + ParagraphStyle { paragraph_spacing: self.paragraph_spacing, paragraph_indent: self.paragraph_indent, list, features: self.features.clone() } + } + + /// Take what text style `ps` sets at the paragraph and layer level: the spacing, indent and + /// features on the layer, the list style on every paragraph. + pub fn take_paragraph_style(&mut self, ps: &ParagraphStyle) { + self.paragraph_spacing = ps.paragraph_spacing; + self.paragraph_indent = ps.paragraph_indent; + self.features.clone_from(&ps.features); + // Every paragraph by index: `para_span` leaves out an empty one after a final newline. + let last = self.paragraph_count() - 1; + self.set_para_lists_between(0, last, false, |pl| pl.list = ps.list); + } + + /// As [`take_paragraph_style`](Self::take_paragraph_style), with the list style going to the + /// paragraphs chars `start..end` touch only; the spacing, indent and features are the + /// layer's, as in Figma. + pub fn take_paragraph_style_in(&mut self, start: usize, end: usize, ps: &ParagraphStyle) { + self.paragraph_spacing = ps.paragraph_spacing; + self.paragraph_indent = ps.paragraph_indent; + self.features.clone_from(&ps.features); + self.set_para_lists(start, end, |pl| pl.list = ps.list); + } + + /// Follow text style `id`'s paragraph-level definition wherever chars link to it. + pub fn update_paragraph_style(&mut self, id: &str, ps: &ParagraphStyle) { + let linked: Vec<(usize, usize)> = + self.spans().into_iter().filter(|(_, _, s)| s.style_id.as_deref() == Some(id)).map(|(a, b, _)| (a, b)).collect(); + for (a, b) in linked { + self.take_paragraph_style_in(a, b, ps); + } + } + + /// Whether chars `start..end` show what text style `ps` sets at the paragraph and layer + /// level: the layer's spacing, indent and features, and their paragraphs' list style. + pub fn shows_paragraph_style_in(&self, start: usize, end: usize, ps: &ParagraphStyle) -> bool { + self.paragraph_spacing == ps.paragraph_spacing + && self.paragraph_indent == ps.paragraph_indent + && self.features == ps.features + && self.common_para_list(start, end).is_some_and(|pl| pl.list == ps.list) + } + + /// Whether the whole text shows what text style `ps` sets at the paragraph and layer level. + pub fn shows_paragraph_style(&self, ps: &ParagraphStyle) -> bool { + self.shows_paragraph_style_in(0, self.char_count(), ps) + } + + /// Link chars `start..end` (all of them when the range is empty or the whole text) to text + /// style `id`, defined as `def`. + pub fn link_text_style(&mut self, start: usize, end: usize, def: &TextStyle, id: &str) { + let (start, end) = if start == end { (0, self.char_count()) } else { (start, end) }; + self.restyle(start, end, |s| s.take_text_style(def, id)); + } + + /// Unlink chars `start..end` (all when empty or whole) from their text styles; values stay. + pub fn unlink_text_style(&mut self, start: usize, end: usize) { + let (start, end) = if start == end { (0, self.char_count()) } else { (start, end) }; + self.restyle(start, end, |s| s.style_id = None); + } + + /// The text style every char is linked to: `Some(None)` when none is, None when they differ. + pub fn text_style_link(&self) -> Option> { + let mut spans = self.spans().into_iter().map(|(_, _, s)| s.style_id.as_deref()); + let first = spans.next()?; + spans.all(|s| s == first).then_some(first) + } + + /// Apply `f` to every distinct style (the base and each run) and merge runs that became equal. + pub(crate) fn each_style(&mut self, mut f: impl FnMut(&mut TextStyle)) { + f(&mut self.style); + for r in &mut self.runs { + f(&mut r.style); + } + self.normalize(); + } + + /// Whether any char links to text style `id`. + pub fn links_text_style(&self, id: &str) -> bool { + std::iter::once(&self.style).chain(self.runs.iter().map(|r| &r.style)).any(|s| s.style_id.as_deref() == Some(id)) + } + + /// Follow text style `id`'s new definition wherever chars link to it. + pub fn update_text_style(&mut self, id: &str, def: &TextStyle) { + self.each_style(|s| { + if s.style_id.as_deref() == Some(id) { + s.take_text_style(def, id); + } + }); + } + + /// Point text style links elsewhere: `f(id)` gives the new id, None unlinks (values stay). + pub fn map_text_styles(&mut self, f: impl Fn(&str) -> Option) { + self.each_style(|s| s.style_id = s.style_id.as_deref().and_then(&f)); + } + + /// Unlink chars whose style is gone (`def` gives None) or that no longer show it (edited since). + pub fn check_text_styles<'a>(&mut self, def: impl Fn(&str) -> Option<&'a TextStyle>) { + self.each_style(|s| { + if s.style_id.as_deref().is_some_and(|id| !def(id).is_some_and(|d| s.shows_text_style(d))) { + s.style_id = None; + } + }); + } + + /// Whether every char shares one style (the panel shows "Mixed" otherwise). + pub fn is_uniform(&self) -> bool { + self.runs.is_empty() + } +} + +#[cfg(test)] +mod case_tests { + use super::*; + + #[test] + fn trim_num_prints_huge_whole_numbers() { + assert_eq!(trim_num(1e19), "10000000000000000000"); + assert_eq!(trim_num(-1e19), "-10000000000000000000"); + assert_eq!(trim_num(12.0), "12"); + let v = 12345678901234567890.0_f64; + assert_eq!(trim_num(v).parse::().unwrap(), v); + } + + #[test] + fn title_case_respects_context() { + assert_eq!(TextCase::Title.apply("hello wORLD don't 3d x-ray"), "Hello WORLD Don't 3d X-Ray"); + // Continuing a word from a previous run: no capital. + assert_eq!(TextCase::Title.apply_after("lo world", Some('l')), "lo World"); + assert_eq!(TextCase::Title.apply_after("lo", Some(' ')), "Lo"); + assert_eq!(TextCase::Upper.apply_after("ß", Some('a')), "SS"); + assert!(valid_feature_tag("liga") && valid_feature_tag("ss01")); + assert!(!valid_feature_tag("lig") && !valid_feature_tag("ligatures") && !valid_feature_tag("li\u{e9}")); + } + + #[test] + fn new_text_starts_in_the_builds_default_font() { + // Inter, unless the build names another with `FIGCRAFT_DEFAULT_FONT` (empty means Inter). + let named = option_env!("FIGCRAFT_DEFAULT_FONT").filter(|f| !f.is_empty()); + assert_eq!(DEFAULT_FONT, named.unwrap_or("Inter")); + let st = TextStyle::default(); + assert_eq!(st.font_family, DEFAULT_FONT); + // The family is always written, so a saved file keeps it in a build with another default. + let saved = serde_json::to_value(&st).unwrap(); + assert_eq!(saved["font_family"], DEFAULT_FONT); + } + + #[test] + fn variations_are_backward_compatible_and_imply_weight() { + // Files written before variable fonts load with no custom axes, and stay byte-identical. + let old = r#"{"font_family":"Inter","font_style":"Bold","font_size":12.0}"#; + let st: TextStyle = serde_json::from_str(old).unwrap(); + assert!(st.variations.is_empty()); + assert!(!serde_json::to_string(&st).unwrap().contains("variations")); + let mut st = TextStyle { font_style: "Regular".into(), ..Default::default() }; + st.variations.insert("wght".into(), 640.0); + st.variations.insert("wdth".into(), 80.0); + assert_eq!(st.weight(), 640); + assert!(!st.italic()); + st.variations.insert("slnt".into(), -8.0); + assert!(st.italic()); + let round: TextStyle = serde_json::from_str(&serde_json::to_string(&st).unwrap()).unwrap(); + assert_eq!(round, st); + // Picking a named style drops the axes its name implies, keeps the others. + st.set_font_style("Bold"); + assert_eq!(st.weight(), 700); + assert_eq!(st.variations.keys().collect::>(), ["wdth"]); + assert!(valid_axis_tag("wght") && !valid_axis_tag("weight")); + } + + #[test] + fn list_starts_load_from_old_files_and_follow_edits() { + use ListStyle::{Bulleted as B, None as P, Numbered as N}; + // Files written before start numbers load with none, and write the same bytes. + let old = r#"{"list":"numbered","indent":1}"#; + let pl: ParaList = serde_json::from_str(old).unwrap(); + assert_eq!(pl, ParaList { list: N, indent: 1, start_offset: 0 }); + assert_eq!(serde_json::to_string(&pl).unwrap(), old); + // One numbered paragraph with a start keeps it (it doesn't fold into `list`). + let mut t = TextData { characters: "Next".into(), ..Default::default() }; + t.set_para_lists(0, 0, |p| *p = ParaList { list: N, indent: 0, start_offset: 1 }); + assert_eq!(t.para_list(0), ParaList { list: N, indent: 0, start_offset: 1 }); + // Enter copies it to the new item; different starts don't make the list mixed. + t.replace_range(4, 4, "\nMore"); + assert_eq!(t.para_list(1).start_offset, 1); + t.set_para_lists(5, 5, |p| p.start_offset = 0); + assert!(t.common_para_list(0, t.char_count()).is_some_and(|p| p.list == N)); + // Bullets have no number, so no start. + t.set_para_lists(0, 0, |p| *p = ParaList { list: B, indent: 1, start_offset: 4 }); + assert_eq!(t.para_list(0), ParaList { list: B, indent: 1, start_offset: 0 }); + // A plain paragraph has none. + t.set_para_lists(0, 0, |p| p.list = P); + assert_eq!(t.para_list(0), ParaList::default()); + } +} + +#[cfg(test)] +mod title_case_tests { + use super::TextCase; + + #[test] + fn title_case_after_opening_apostrophe() { + assert_eq!(TextCase::Title.apply("'hello world'"), "'Hello World'"); + assert_eq!(TextCase::Title.apply("say 'hi'"), "Say 'Hi'"); + assert_eq!(TextCase::Title.apply("don't"), "Don't"); + assert_eq!(TextCase::Title.apply("\u{2019}hello"), "\u{2019}Hello"); + } + + #[test] + fn title_case_between_runs_sees_char_before_apostrophe() { + assert_eq!(TextCase::Title.apply_after("t", Some('\'')), "t"); + assert_eq!(TextCase::Title.apply_between("hello", None, Some('\'')), "Hello"); + assert_eq!(TextCase::Title.apply_between("t", Some('n'), Some('\'')), "t"); + assert_eq!(TextCase::Title.apply_between("t", Some(' '), Some('\u{2019}')), "T"); + } + + #[test] + fn title_case_combining_marks_do_not_break_words() { + assert_eq!(TextCase::Title.apply("re\u{301}sume\u{301}"), "Re\u{301}sume\u{301}"); + assert_eq!(TextCase::Title.apply("re\u{301}sume\u{301} bon"), "Re\u{301}sume\u{301} Bon"); + assert_eq!(TextCase::Title.apply("a \u{301}b"), "A \u{301}B"); + assert_eq!(TextCase::Title.apply("cafe\u{301}'s"), "Cafe\u{301}'s"); + } +} + +#[cfg(test)] +mod whole_text_paragraph_style_tests { + use super::*; + + #[test] + fn a_text_style_on_the_whole_layer_reaches_a_trailing_empty_paragraph() { + let ps = ParagraphStyle { list: ListStyle::Bulleted, ..Default::default() }; + let mut t = TextData::new("a\nb\n"); + t.take_paragraph_style(&ps); + assert_eq!(t.paragraph_count(), 3); + assert_eq!(t.para_list(2).list, ListStyle::Bulleted); + assert_eq!(t.list, ListStyle::Bulleted); + assert!(t.paragraphs.is_empty()); + let mut plain = TextData::new("a\nb"); + plain.take_paragraph_style(&ps); + assert_eq!((plain.list, plain.paragraphs.len()), (t.list, t.paragraphs.len())); + } +} From 9e356096e382abc60f0f26e1d518c9affa4f3cd1 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 5 Nov 2026 17:22:53 -0500 Subject: [PATCH 089/102] text.rs keeps its LF line endings The previous commit saved the file with CRLF endings; only the 30 changed lines are a real change. Co-Authored-By: Claude Fable 5.1 --- crates/doc/src/text.rs | 2274 ++++++++++++++++++++-------------------- 1 file changed, 1137 insertions(+), 1137 deletions(-) diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index f4d087589..7183efbf6 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -1,1137 +1,1137 @@ -//! Text node data: characters plus a base style and styled runs. - -use figcraft_color::{Color, Paint}; -use serde::{Deserialize, Serialize}; - -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "unit", content = "value", rename_all = "camelCase")] -#[derive(Default)] -pub enum LineHeight { - #[default] - Auto, - Pixels(f64), - Percent(f64), -} - -impl LineHeight { - /// Resolved line height in px for `font_size` (`auto` uses the font's natural ratio). - pub fn resolve(self, font_size: f64, natural_ratio: f64) -> f64 { - match self { - LineHeight::Auto => font_size * natural_ratio, - LineHeight::Pixels(v) => v.max(0.0), - LineHeight::Percent(p) => font_size * p.max(0.0) / 100.0, - } - } - pub fn label(self) -> String { - match self { - LineHeight::Auto => "Auto".into(), - LineHeight::Pixels(v) => trim_num(v), - LineHeight::Percent(p) => format!("{}%", trim_num(p)), - } - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "unit", content = "value", rename_all = "camelCase")] -pub enum LetterSpacing { - Pixels(f64), - Percent(f64), -} - -impl Default for LetterSpacing { - fn default() -> Self { - LetterSpacing::Percent(0.0) - } -} - -impl LetterSpacing { - pub fn resolve(self, font_size: f64) -> f64 { - match self { - LetterSpacing::Pixels(v) => v, - LetterSpacing::Percent(p) => font_size * p / 100.0, - } - } - pub fn label(self) -> String { - match self { - LetterSpacing::Pixels(v) => trim_num(v), - LetterSpacing::Percent(p) => format!("{}%", trim_num(p)), - } - } -} - -pub fn trim_num(v: f64) -> String { - if v.abs() >= 9.0e18 { - return format!("{v}"); - } - let r = (v * 100.0).round() / 100.0; - if r.fract().abs() < 1e-9 { format!("{}", r as i64) } else { format!("{r}") } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum TextDecoration { - #[default] - None, - Underline, - Strikethrough, -} - -/// How an underline or strikethrough is drawn. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum DecorationStyle { - #[default] - Solid, - Dotted, - Wavy, -} - -/// A decoration length: `Auto` (the font's own value), pixels, or a percentage of the font size. -pub type DecorationLength = LineHeight; - -/// How a decoration line looks; the default is the font's own solid line in the text's colour. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Default)] -#[serde(default)] -pub struct DecorationLook { - pub style: DecorationStyle, - pub thickness: DecorationLength, - /// Underlines: from the baseline down to the line's top edge (negative: above the baseline). - pub offset: DecorationLength, - /// Underlines break where descenders cross them. - pub skip_ink: bool, - /// The line's own colour (None: the text's fills). - pub color: Option, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum TextCase { - #[default] - Original, - Upper, - Lower, - Title, - SmallCaps, -} - -impl TextCase { - pub fn apply(self, s: &str) -> String { - self.apply_after(s, None) - } - - /// Apply the case to `s`, which follows `prev` in the text (so title case only capitalises - /// the first letter of each word even when a word spans several styled runs). An apostrophe - /// as `prev` is taken to continue a word. - pub fn apply_after(self, s: &str, prev: Option) -> String { - self.apply_impl(s, prev, prev.is_some_and(is_word_char)) - } - - /// Like [`apply_after`](Self::apply_after), also given the char `before` `prev`: an apostrophe - /// only continues a word when a letter or digit precedes it. - pub fn apply_between(self, s: &str, before: Option, prev: Option) -> String { - let continues = prev.is_some_and(|c| is_word_char(c) && (c.is_alphanumeric() || before.is_some_and(char::is_alphanumeric))); - self.apply_impl(s, prev, continues) - } - - /// `in_word` says whether `prev` continues a word (rather than a new word starting here). - fn apply_impl(self, s: &str, prev: Option, in_word: bool) -> String { - match self { - TextCase::Original | TextCase::SmallCaps => s.to_string(), - TextCase::Upper => s.to_uppercase(), - TextCase::Lower => s.to_lowercase(), - TextCase::Title => { - let mut out = String::with_capacity(s.len()); - let mut start = !in_word; - let mut last = prev; - for ch in s.chars() { - if start && ch.is_alphanumeric() { - out.extend(ch.to_uppercase()); - start = false; - } else { - out.push(ch); - // An apostrophe only continues a word right after a letter or digit. - let opening_apostrophe = - matches!(ch, '\'' | '\u{2019}') && !last.is_some_and(|c| c.is_alphanumeric() || is_combining_mark(c)); - // A combining mark attaches to the char before it and never changes word state. - if !is_combining_mark(ch) { - start = !is_word_char(ch) || opening_apostrophe; - } - } - last = Some(ch); - } - out - } - } - } - - /// Whether the char at a position preceded by `prev` starts a word (for title case). - pub fn starts_word(prev: Option) -> bool { - prev.is_none_or(|c| !is_word_char(c)) - } -} - -/// Letters, digits, combining marks and apostrophes continue a word (so "don't" stays "Don't" -/// and decomposed accents stay inside their word). -fn is_word_char(c: char) -> bool { - c.is_alphanumeric() || is_combining_mark(c) || matches!(c, '\'' | '\u{2019}') -} - -/// Combining marks such as the U+0301 accent in decomposed text: non-alphanumeric chars that -/// extend the grapheme of the char before them. -fn is_combining_mark(c: char) -> bool { - use unicode_segmentation::UnicodeSegmentation; - if c.is_ascii() || c.is_alphanumeric() { - return false; - } - let mut buf = [0u8; 8]; - buf[0] = b'a'; - let end = 1 + c.encode_utf8(&mut buf[1..]).len(); - std::str::from_utf8(&buf[..end]).is_ok_and(|s| s.graphemes(true).count() == 1) -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum TextAlignH { - #[default] - Left, - Center, - Right, - Justified, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum TextAlignV { - #[default] - Top, - Middle, - Bottom, -} - -/// How a text box resizes as its content changes. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum TextAutoResize { - /// Auto width: one line per paragraph, box grows both ways. - #[default] - WidthAndHeight, - /// Fixed width, height grows. - Height, - /// Fixed size. - None, - /// Fixed size, truncate with an ellipsis. - Truncate, -} - -/// Vertical trim: what bounds a text box vertically. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum LeadingTrim { - /// The full line height of the first and last lines. - #[default] - None, - /// From the first line's cap height to the last line's baseline. - CapHeight, -} - -/// Where lines break when text wraps to more than one line ("Wrap style controls where lines -/// break when text wraps to more than one line", Explore text properties). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum WrapStyle { - /// "Figma fits as many words as possible on each line before wrapping to the next." - #[default] - Auto, - /// "Figma distributes text as evenly as possible across every line, so each line is close to - /// the same length." - Balance, - /// "Figma keeps each line full, but adjusts the last four lines to avoid an orphan -- a single - /// word stranded alone on the last line." - Pretty, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum ListStyle { - #[default] - None, - Bulleted, - Numbered, -} - -/// Deepest list nesting (levels 0..=MAX_LIST_INDENT). -pub const MAX_LIST_INDENT: u8 = 8; - -/// One paragraph's list settings. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(default)] -pub struct ParaList { - pub list: ListStyle, - /// Nesting level (0 = outermost). A plain paragraph is 0, except one that left its list by - /// Backspace or Delete at its start ([`TextData::unlist_keeping_levels`]): it keeps the level - /// it had and starts where that level's item text does ("delete the counter, but keep the - /// same level of indentation"). - pub indent: u8, - /// A numbered list that starts counting at this paragraph counts from `start_offset + 1` - /// (items that go on counting ignore it; other paragraphs are always 0). - #[serde(skip_serializing_if = "crate::node::is_default")] - pub start_offset: u32, -} - -/// Character style. In runs, every field is an override; `None` means "inherit the base". -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct TextStyle { - pub font_family: String, - /// The style name, e.g. "Regular", "Bold", "Semi Bold Italic". - pub font_style: String, - pub font_size: f64, - pub line_height: LineHeight, - pub letter_spacing: LetterSpacing, - pub decoration: TextDecoration, - /// How the decoration looks (None: the default look; boxed to keep styles small). - #[serde(skip_serializing_if = "Option::is_none")] - pub decoration_look: Option>, - pub case: TextCase, - /// Run fills (None = node fills). - pub fills: Option>, - /// Hyperlink. - pub link: Option, - /// Variable font axis values in user space, keyed by 4-char OpenType axis tag (e.g. `wght`: - /// 550, `wdth`: 85). Empty = what the style name implies; axes the face lacks are ignored. - #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")] - pub variations: std::collections::BTreeMap, - /// The text style (shared style id) these chars are linked to. A layer's chars can link to - /// different styles; editing what a style sets unlinks the chars edited. - #[serde(skip_serializing_if = "Option::is_none")] - pub style_id: Option, -} - -/// What a text style sets at the paragraph and layer level, beside its character style -/// ([`TextStyle`]): paragraph spacing and indent, the list style and the OpenType features -/// ("Supported in text styles": "Paragraph spacing and indentation", "Lists", "OpenType -/// features", Create and apply text styles). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] -#[serde(default)] -pub struct ParagraphStyle { - #[serde(skip_serializing_if = "crate::node::is_default")] - pub paragraph_spacing: f64, - #[serde(skip_serializing_if = "crate::node::is_default")] - pub paragraph_indent: f64, - #[serde(skip_serializing_if = "crate::node::is_default")] - pub list: ListStyle, - #[serde(skip_serializing_if = "crate::node::is_default")] - pub features: std::collections::BTreeMap, -} - -/// The font new text starts in. A build can name another (`FIGCRAFT_DEFAULT_FONT="Noto Sans Thai"`, -/// for a distribution whose users mostly write a script Inter lacks); empty means Inter. -pub const DEFAULT_FONT: &str = match option_env!("FIGCRAFT_DEFAULT_FONT") { - Some(family) if !family.is_empty() => family, - _ => "Inter", -}; - -impl Default for TextStyle { - fn default() -> Self { - Self { - font_family: DEFAULT_FONT.into(), - font_style: "Regular".into(), - font_size: 12.0, - line_height: LineHeight::Auto, - letter_spacing: LetterSpacing::default(), - decoration: TextDecoration::None, - decoration_look: None, - case: TextCase::Original, - fills: None, - link: None, - variations: std::collections::BTreeMap::new(), - style_id: None, - } - } -} - -/// Axes a style name implies (weight, italic, slant): picking a named style clears their custom values. -pub const STYLE_AXES: [&str; 3] = ["wght", "ital", "slnt"]; - -impl TextStyle { - /// Numeric weight: a custom `wght` axis value, else the one implied by the style name. - pub fn weight(&self) -> u16 { - match self.variations.get("wght") { - Some(w) if w.is_finite() => w.round().clamp(1.0, 1000.0) as u16, - _ => style_weight(&self.font_style), - } - } - pub fn italic(&self) -> bool { - self.font_style.to_ascii_lowercase().contains("italic") - || self.variations.get("ital").is_some_and(|v| *v >= 0.5) - || self.variations.get("slnt").is_some_and(|v| *v != 0.0) - } - - /// Take what text style `def` sets (font, size, line height, letter spacing, decoration, case - /// and axis values) and link to it as `id`; fills and hyperlinks stay. - pub fn take_text_style(&mut self, def: &TextStyle, id: &str) { - *self = TextStyle { fills: self.fills.take(), link: self.link.take(), style_id: Some(id.to_string()), ..def.clone() }; - } - - /// Whether these chars show what text style `def` sets. - pub fn shows_text_style(&self, def: &TextStyle) -> bool { - self.font_family == def.font_family - && self.font_style == def.font_style - && self.font_size == def.font_size - && self.line_height == def.line_height - && self.letter_spacing == def.letter_spacing - && self.decoration == def.decoration - && self.decoration_look == def.decoration_look - && self.case == def.case - && self.variations == def.variations - } - - /// This style as a text style's definition (linked to nothing). - pub fn as_text_style(&self) -> TextStyle { - TextStyle { style_id: None, link: None, ..self.clone() } - } - - /// How the decoration looks. - pub fn look(&self) -> DecorationLook { - self.decoration_look.as_deref().copied().unwrap_or_default() - } - - /// Change how the decoration looks (the default look is stored as None). - pub fn set_look(&mut self, f: impl FnOnce(&mut DecorationLook)) { - let mut look = self.look(); - f(&mut look); - self.decoration_look = (look != DecorationLook::default()).then(|| Box::new(look)); - } - - /// Switch to the named style, dropping custom values of the axes the name implies. - pub fn set_font_style(&mut self, name: impl Into) { - self.font_style = name.into(); - for tag in STYLE_AXES { - self.variations.remove(tag); - } - } -} - -/// Weight from a style name ("Semi Bold Italic" → 600). -pub fn style_weight(style: &str) -> u16 { - let s = style.to_ascii_lowercase().replace([' ', '-'], ""); - // A weight number ("600", "600 Italic"), as some apps name styles. - let digits: String = s.chars().take_while(char::is_ascii_digit).collect(); - if let Ok(n) = digits.parse::() - && (1..=1000).contains(&n) - { - return n; - } - let table: [(&str, u16); 10] = [ - ("thin", 100), - ("extralight", 200), - ("ultralight", 200), - ("light", 300), - ("medium", 500), - ("semibold", 600), - ("demibold", 600), - ("extrabold", 800), - ("ultrabold", 800), - ("black", 900), - ]; - for (k, w) in table { - if s.contains(k) { - return w; - } - } - if s.contains("bold") { - return 700; - } - if s.contains("heavy") { - return 900; - } - 400 -} - -/// A styled range of characters (char indices, end exclusive). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct StyleRun { - pub start: usize, - pub end: usize, - pub style: TextStyle, -} - -/// Text node content. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] -#[serde(default)] -pub struct TextData { - pub characters: String, - pub style: TextStyle, - /// Ranges whose style differs from `style`; full styles (already merged), non-overlapping, sorted. - #[serde(skip_serializing_if = "crate::node::is_default")] - pub runs: Vec, - #[serde(skip_serializing_if = "crate::node::is_default")] - pub auto_resize: TextAutoResize, - #[serde(skip_serializing_if = "crate::node::is_default")] - pub align_h: TextAlignH, - #[serde(skip_serializing_if = "crate::node::is_default")] - pub align_v: TextAlignV, - #[serde(skip_serializing_if = "crate::node::is_default")] - pub paragraph_spacing: f64, - #[serde(skip_serializing_if = "crate::node::is_default")] - pub paragraph_indent: f64, - /// The list style of paragraphs `paragraphs` doesn't cover (all of them when it's empty). - #[serde(skip_serializing_if = "crate::node::is_default")] - pub list: ListStyle, - /// Per-paragraph list settings, by paragraph index; empty when every paragraph is `list` at - /// level 0. Kept in step with the characters by [`TextData::replace_range`]. - #[serde(skip_serializing_if = "Vec::is_empty")] - pub paragraphs: Vec, - /// Space between two items of a list (px), in place of the paragraph spacing. - #[serde(skip_serializing_if = "crate::node::is_default")] - pub list_spacing: f64, - /// Opening and closing punctuation at a line's aligned edge sits outside the box. - #[serde(skip_serializing_if = "crate::node::is_default")] - pub hanging_punctuation: bool, - /// List bullets and numbers sit outside the box; item text lines up with plain paragraphs. - #[serde(skip_serializing_if = "crate::node::is_default")] - pub hanging_list: bool, - /// Vertical trim (`capHeight`: the box runs from the first line's cap height to the last - /// line's baseline). - #[serde(skip_serializing_if = "crate::node::is_default")] - pub leading_trim: LeadingTrim, - /// Max lines when truncating, or before an auto-height text ends in an ellipsis (0 = as many - /// as fit). - #[serde(skip_serializing_if = "crate::node::is_default")] - pub max_lines: u32, - /// Where lines break when the text wraps: greedily (Auto), as evenly as the words allow - /// (Balance), or full with no one word alone on the last line (Pretty). - #[serde(skip_serializing_if = "crate::node::is_default")] - pub wrap_style: WrapStyle, - /// OpenType feature toggles (e.g. "liga": false). - #[serde(skip_serializing_if = "crate::node::is_default")] - pub features: std::collections::BTreeMap, - /// The path the text follows (text on a path); `None`: lines in the box. Boxed to keep text - /// data small. - #[serde(skip_serializing_if = "Option::is_none")] - pub path: Option>, - /// Where the file this text came from wrapped its lines (an imported `.fig`'s saved layout). - /// Layout follows them only while the box width and everything that moves a line break are - /// as they were saved, so an edit that could change the wrap drops them. - #[serde(skip_serializing_if = "Option::is_none")] - pub saved_breaks: Option>, -} - -/// Line breaks a file saved with a text: the chars that start a wrapped line (not those after a -/// hard break), for the box width and the content ([`TextData::layout_key`]) they were made for. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] -#[serde(default)] -pub struct SavedBreaks { - pub starts: Vec, - pub width: f64, - pub for_text: u64, -} - -/// Text on a path: the baseline follows `d`. The text starts at `start` (aligned there by the -/// horizontal alignment: left starts, centre centres, right ends at it); glyphs past an open -/// path's ends are hidden, a closed path wraps them around. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] -#[serde(default)] -pub struct TextPath { - /// SVG path data in the layer's own space. - pub d: String, - /// Where the text starts along the path, 0..1 by length. - pub start: f64, - /// On the other side of the path, running the other way. - #[serde(skip_serializing_if = "std::ops::Not::not")] - pub flip: bool, -} - -impl TextPath { - /// A text path following `path` (layer space). - pub fn new(path: &figcraft_geom::BezPath) -> Self { - Self { d: path.to_svg(), start: 0.0, flip: false } - } - - /// The path (empty when `d` doesn't parse). - pub fn path(&self) -> figcraft_geom::BezPath { - figcraft_geom::BezPath::from_svg(&self.d).unwrap_or_default() - } - - /// The start offset clamped into 0..1 (NaN: 0). - pub fn start(&self) -> f64 { - if self.start.is_finite() { self.start.clamp(0.0, 1.0) } else { 0.0 } - } - - /// Scale the path by `sx`, `sy` (the layer was resized). - pub fn scale(&mut self, sx: f64, sy: f64) { - if sx.is_finite() && sy.is_finite() { - let mut p = self.path(); - p.apply_affine(figcraft_geom::Affine::scale_non_uniform(sx, sy)); - self.d = p.to_svg(); - } - } -} - -/// Whether `tag` is a valid OpenType feature tag (four printable ASCII chars). -pub fn valid_feature_tag(tag: &str) -> bool { - tag.len() == 4 && tag.bytes().all(|b| (0x20..0x7f).contains(&b)) -} - -/// Whether `tag` is a valid OpenType variation axis tag (same shape as a feature tag). -pub fn valid_axis_tag(tag: &str) -> bool { - valid_feature_tag(tag) -} - -impl TextData { - pub fn new(characters: impl Into) -> Self { - Self { characters: characters.into(), ..Default::default() } - } - - /// A stable hash of what decides where lines break: everything but paints, links, style links, - /// decorations, vertical settings and the saved breaks themselves (FNV-1a over the JSON, so it - /// stays the same across builds and can be saved). - pub fn layout_key(&self) -> u64 { - let clear = |s: &mut TextStyle| { - (s.fills, s.link, s.style_id, s.decoration, s.decoration_look) = (None, None, None, TextDecoration::None, None); - }; - let mut t = TextData { - align_v: TextAlignV::default(), - paragraph_spacing: 0.0, - list_spacing: 0.0, - leading_trim: LeadingTrim::default(), - max_lines: 0, - saved_breaks: None, - ..self.clone() - }; - clear(&mut t.style); - t.runs.iter_mut().for_each(|r| clear(&mut r.style)); - t.normalize(); - serde_json::to_vec(&t).unwrap_or_default().iter().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) - } - - /// Keep `starts` (chars that start a wrapped line) as this text's saved line breaks in a box - /// `width` wide. - pub fn save_breaks(&mut self, starts: Vec, width: f64) { - self.saved_breaks = Some(Box::new(SavedBreaks { starts, width, for_text: self.layout_key() })); - } - - /// The saved line starts (empty: no wrapped line) while they still hold: the same box width and - /// layout content, and starts increasing inside the text. - pub fn saved_breaks_for(&self, width: f64) -> Option<&[usize]> { - let b = self.saved_breaks.as_deref()?; - let inside = b.starts.first().is_none_or(|s| *s > 0) && b.starts.last().is_none_or(|s| *s < self.char_count()); - let same_box = (b.width - width).abs() <= 1e-6 * width.abs().max(1.0); - (inside && same_box && b.starts.is_sorted_by(|a, b| a < b) && b.for_text == self.layout_key()).then_some(b.starts.as_slice()) - } - - /// How far text on a path paints past its path's box (glyphs stand on the path, lines after - /// the first run beside it): about one and a half of the largest size per line; 0 off a path. - pub fn path_reach(&self) -> f64 { - if self.path.is_none() { - return 0.0; - } - let lines = self.characters.lines().count().clamp(1, 10_000) as f64; - self.max_size() * 1.5 * lines - } - - /// How far vertically trimmed text paints past its box (descenders below the last baseline, - /// accents above the first cap height): half the largest size; 0 untrimmed. - pub fn trim_reach(&self) -> f64 { - if self.leading_trim == LeadingTrim::None { 0.0 } else { self.max_size() * 0.5 } - } - - /// The largest font size used (capped like layout caps it). - fn max_size(&self) -> f64 { - self.spans().iter().map(|(_, _, s)| s.font_size).filter(|v| v.is_finite()).fold(0.0, f64::max).min(5000.0) - } - - pub fn char_count(&self) -> usize { - self.characters.chars().count() - } - - /// Whether text that runs out of room ends in an ellipsis: a truncating box, or auto height - /// or auto width with a line limit (the box hugs up to `max_lines` lines: "Max lines is - /// available only if truncate text is enabled, and: Text resizing is set to auto height or - /// auto width"). - pub fn truncates(&self) -> bool { - match self.auto_resize { - TextAutoResize::Truncate => true, - TextAutoResize::Height | TextAutoResize::WidthAndHeight => self.max_lines > 0, - TextAutoResize::None => false, - } - } - - /// The resize mode once the box is given an explicit `width` and/or `height`: an explicit - /// height fixes the box, an explicit width turns auto width into auto height, and truncating - /// text keeps truncating. - pub fn fix_size(&mut self, width: bool, height: bool) { - self.auto_resize = match self.auto_resize { - _ if height && self.truncates() => TextAutoResize::Truncate, - _ if height => TextAutoResize::None, - TextAutoResize::WidthAndHeight if width => TextAutoResize::Height, - mode => mode, - }; - } - - /// The style at char index `i`. - pub fn style_at(&self, i: usize) -> &TextStyle { - self.runs.iter().find(|r| r.start <= i && i < r.end).map(|r| &r.style).unwrap_or(&self.style) - } - - /// Spans of uniform style covering the whole text: (start, end, style). - pub fn spans(&self) -> Vec<(usize, usize, &TextStyle)> { - let n = self.char_count(); - let mut out = Vec::new(); - let mut pos = 0; - let mut runs: Vec<&StyleRun> = self.runs.iter().filter(|r| r.start < r.end && r.start < n).collect(); - runs.sort_by_key(|r| r.start); - for r in runs { - let start = r.start.max(pos); - let end = r.end.min(n); - if start >= end { - continue; - } - if start > pos { - out.push((pos, start, &self.style)); - } - out.push((start, end, &r.style)); - pos = end; - } - if pos < n || out.is_empty() { - out.push((pos, n, &self.style)); - } - out - } - - /// Apply `f` to the style of chars `start..end` (all text when the range is the whole text or - /// empty text), splitting runs as needed and merging equal neighbours. - pub fn restyle(&mut self, start: usize, end: usize, f: impl Fn(&mut TextStyle)) { - let n = self.char_count(); - let (start, end) = (start.min(n), end.min(n)); - if n == 0 || (start == 0 && end >= n) { - f(&mut self.style); - for r in &mut self.runs { - f(&mut r.style); - } - self.normalize(); - return; - } - if start >= end { - return; - } - // Expand to per-char styles, modify, re-compress. - let mut per: Vec = (0..n).map(|i| self.style_at(i).clone()).collect(); - for s in per.iter_mut().take(end).skip(start) { - f(s); - } - self.runs.clear(); - let mut i = 0; - while i < n { - let Some(s) = per.get(i) else { break }; - let mut j = i + 1; - while per.get(j).is_some_and(|t| t == s) { - j += 1; - } - if *s != self.style { - self.runs.push(StyleRun { start: i, end: j, style: s.clone() }); - } - i = j; - } - } - - /// Drop empty/out-of-range runs and runs equal to the base style, and merge touching equal runs. - pub fn normalize(&mut self) { - let n = self.char_count(); - let base = self.style.clone(); - self.runs.retain(|r| r.start < r.end && r.start < n && r.style != base); - for r in &mut self.runs { - r.end = r.end.min(n); - } - self.runs.sort_by_key(|r| r.start); - let mut merged: Vec = Vec::with_capacity(self.runs.len()); - for mut r in std::mem::take(&mut self.runs) { - // Runs never overlap: a later run starts where the previous one ends at the earliest. - if let Some(prev) = merged.last() { - r.start = r.start.max(prev.end); - if r.start >= r.end { - continue; - } - } - match merged.last_mut() { - Some(prev) if prev.end == r.start && prev.style == r.style => prev.end = r.end, - _ => merged.push(r), - } - } - self.runs = merged; - } - - /// Replace chars `start..end` with `text`, shifting runs (inserted text takes the style at `start`). - pub fn replace_range(&mut self, start: usize, end: usize, text: &str) { - let n = self.char_count(); - let (start, end) = (start.min(n), end.min(n).max(start.min(n))); - let byte = |i: usize| self.characters.char_indices().nth(i).map(|(b, _)| b).unwrap_or(self.characters.len()); - let (bs, be) = (byte(start), byte(end)); - if !self.paragraphs.is_empty() { - // Paragraphs merged by removed newlines take the first one's list; new ones copy it. - let p = self.para_of(start); - let removed = self.characters.get(bs..be).unwrap_or("").matches('\n').count(); - let added = text.matches('\n').count(); - self.fill_paragraphs(); - let at = self.para_list(p); - let tail = (p + 1).min(self.paragraphs.len()); - self.paragraphs.drain(tail..(p + 1 + removed).min(self.paragraphs.len())); - self.paragraphs.splice(tail..tail, std::iter::repeat_n(at, added)); - } - let mut s = String::with_capacity(self.characters.len() + text.len()); - s.push_str(self.characters.get(..bs).unwrap_or("")); - s.push_str(text); - s.push_str(self.characters.get(be..).unwrap_or("")); - self.characters = s; - let inserted = text.chars().count(); - let removed = end - start; - for r in &mut self.runs { - let shift = |p: usize| -> usize { - if p <= start { - p - } else if p >= end { - // Runs of a file that reach past the text (nothing clamps them on load) - // would otherwise overflow here; `normalize` below drops what is left. - p.saturating_sub(removed).saturating_add(inserted) - } else { - start + inserted - } - }; - // A run touching the insertion point at its end grows with the typed text. - let new_start = shift(r.start); - let new_end = if r.end == start && r.start < start { start + inserted } else { shift(r.end) }; - r.start = new_start; - r.end = new_end; - } - self.normalize(); - } - - pub fn paragraph_count(&self) -> usize { - self.characters.matches('\n').count() + 1 - } - - /// The paragraph char index `i` is in. - pub fn para_of(&self, i: usize) -> usize { - self.characters.chars().take(i).filter(|c| *c == '\n').count() - } - - /// Paragraph `p`'s list settings. - pub fn para_list(&self, p: usize) -> ParaList { - self.paragraphs.get(p).copied().unwrap_or(ParaList { list: self.list, ..ParaList::default() }) - } - - /// Spell out every paragraph's list settings in `paragraphs` (and drop extra entries). - fn fill_paragraphs(&mut self) { - let n = self.paragraph_count(); - let fill = ParaList { list: self.list, ..ParaList::default() }; - self.paragraphs.resize(n, fill); - } - - /// The paragraphs chars `start..end` touch (a caret: its paragraph; a selection ending just - /// after a newline leaves the next paragraph out). - pub fn para_span(&self, start: usize, end: usize) -> (usize, usize) { - let (s, e) = (start.min(end), start.max(end)); - let (a, b) = (self.para_of(s), self.para_of(e)); - let ends_at_start = e > s && b > a && self.characters.chars().nth(e - 1) == Some('\n'); - (a, if ends_at_start { b - 1 } else { b }) - } - - /// Apply `f` to the list settings of the paragraphs chars `start..end` touch (plain - /// paragraphs stay at level 0, only numbered ones keep a start, levels stop at - /// [`MAX_LIST_INDENT`]); one style for all with no nesting or start folds back into `list`. - pub fn set_para_lists(&mut self, start: usize, end: usize, f: impl Fn(&mut ParaList)) { - self.set_para_lists_with(start, end, false, f); - } - - /// Take the list items among the paragraphs chars `start..end` touch out of their list at the - /// level they had, as Backspace or Delete at an item's start does: "delete the counter, but - /// keep the same level of indentation" (Create bulleted and numbered lists). - pub fn unlist_keeping_levels(&mut self, start: usize, end: usize) { - self.set_para_lists_with(start, end, true, |pl| pl.list = ListStyle::None); - } - - fn set_para_lists_with(&mut self, start: usize, end: usize, keep_levels: bool, f: impl Fn(&mut ParaList)) { - let (a, b) = self.para_span(start, end); - self.set_para_lists_between(a, b, keep_levels, f); - } - - /// As [`set_para_lists`](Self::set_para_lists), for paragraphs `a..=b` addressed directly. - fn set_para_lists_between(&mut self, a: usize, b: usize, keep_levels: bool, f: impl Fn(&mut ParaList)) { - self.fill_paragraphs(); - for pl in self.paragraphs.get_mut(a..=b).unwrap_or(&mut []) { - f(pl); - if pl.list == ListStyle::None && !keep_levels { - pl.indent = 0; - } - if pl.list != ListStyle::Numbered { - pl.start_offset = 0; - } - pl.indent = pl.indent.min(MAX_LIST_INDENT); - } - if let Some(first) = self.paragraphs.first().copied() - && first == (ParaList { list: first.list, ..ParaList::default() }) - && self.paragraphs.iter().all(|p| *p == first) - { - self.list = first.list; - self.paragraphs.clear(); - } - } - - /// The list style and level shared by the paragraphs chars `start..end` touch (the first - /// one's settings), or None when they differ. Start numbers don't count. - pub fn common_para_list(&self, start: usize, end: usize) -> Option { - let (a, b) = self.para_span(start, end); - let first = self.para_list(a); - (a..=b).all(|p| self.para_list(p).list == first.list && self.para_list(p).indent == first.indent).then_some(first) - } - - /// What a text style made from this text sets at the paragraph and layer level: the paragraph - /// spacing and indent, the list style (the one every paragraph shares; the base one when they - /// differ) and the OpenType features. - pub fn paragraph_style(&self) -> ParagraphStyle { - let list = match self.paragraphs.first() { - Some(first) if self.paragraphs.iter().all(|p| p.list == first.list) => first.list, - _ => self.list, - }; - ParagraphStyle { paragraph_spacing: self.paragraph_spacing, paragraph_indent: self.paragraph_indent, list, features: self.features.clone() } - } - - /// Take what text style `ps` sets at the paragraph and layer level: the spacing, indent and - /// features on the layer, the list style on every paragraph. - pub fn take_paragraph_style(&mut self, ps: &ParagraphStyle) { - self.paragraph_spacing = ps.paragraph_spacing; - self.paragraph_indent = ps.paragraph_indent; - self.features.clone_from(&ps.features); - // Every paragraph by index: `para_span` leaves out an empty one after a final newline. - let last = self.paragraph_count() - 1; - self.set_para_lists_between(0, last, false, |pl| pl.list = ps.list); - } - - /// As [`take_paragraph_style`](Self::take_paragraph_style), with the list style going to the - /// paragraphs chars `start..end` touch only; the spacing, indent and features are the - /// layer's, as in Figma. - pub fn take_paragraph_style_in(&mut self, start: usize, end: usize, ps: &ParagraphStyle) { - self.paragraph_spacing = ps.paragraph_spacing; - self.paragraph_indent = ps.paragraph_indent; - self.features.clone_from(&ps.features); - self.set_para_lists(start, end, |pl| pl.list = ps.list); - } - - /// Follow text style `id`'s paragraph-level definition wherever chars link to it. - pub fn update_paragraph_style(&mut self, id: &str, ps: &ParagraphStyle) { - let linked: Vec<(usize, usize)> = - self.spans().into_iter().filter(|(_, _, s)| s.style_id.as_deref() == Some(id)).map(|(a, b, _)| (a, b)).collect(); - for (a, b) in linked { - self.take_paragraph_style_in(a, b, ps); - } - } - - /// Whether chars `start..end` show what text style `ps` sets at the paragraph and layer - /// level: the layer's spacing, indent and features, and their paragraphs' list style. - pub fn shows_paragraph_style_in(&self, start: usize, end: usize, ps: &ParagraphStyle) -> bool { - self.paragraph_spacing == ps.paragraph_spacing - && self.paragraph_indent == ps.paragraph_indent - && self.features == ps.features - && self.common_para_list(start, end).is_some_and(|pl| pl.list == ps.list) - } - - /// Whether the whole text shows what text style `ps` sets at the paragraph and layer level. - pub fn shows_paragraph_style(&self, ps: &ParagraphStyle) -> bool { - self.shows_paragraph_style_in(0, self.char_count(), ps) - } - - /// Link chars `start..end` (all of them when the range is empty or the whole text) to text - /// style `id`, defined as `def`. - pub fn link_text_style(&mut self, start: usize, end: usize, def: &TextStyle, id: &str) { - let (start, end) = if start == end { (0, self.char_count()) } else { (start, end) }; - self.restyle(start, end, |s| s.take_text_style(def, id)); - } - - /// Unlink chars `start..end` (all when empty or whole) from their text styles; values stay. - pub fn unlink_text_style(&mut self, start: usize, end: usize) { - let (start, end) = if start == end { (0, self.char_count()) } else { (start, end) }; - self.restyle(start, end, |s| s.style_id = None); - } - - /// The text style every char is linked to: `Some(None)` when none is, None when they differ. - pub fn text_style_link(&self) -> Option> { - let mut spans = self.spans().into_iter().map(|(_, _, s)| s.style_id.as_deref()); - let first = spans.next()?; - spans.all(|s| s == first).then_some(first) - } - - /// Apply `f` to every distinct style (the base and each run) and merge runs that became equal. - pub(crate) fn each_style(&mut self, mut f: impl FnMut(&mut TextStyle)) { - f(&mut self.style); - for r in &mut self.runs { - f(&mut r.style); - } - self.normalize(); - } - - /// Whether any char links to text style `id`. - pub fn links_text_style(&self, id: &str) -> bool { - std::iter::once(&self.style).chain(self.runs.iter().map(|r| &r.style)).any(|s| s.style_id.as_deref() == Some(id)) - } - - /// Follow text style `id`'s new definition wherever chars link to it. - pub fn update_text_style(&mut self, id: &str, def: &TextStyle) { - self.each_style(|s| { - if s.style_id.as_deref() == Some(id) { - s.take_text_style(def, id); - } - }); - } - - /// Point text style links elsewhere: `f(id)` gives the new id, None unlinks (values stay). - pub fn map_text_styles(&mut self, f: impl Fn(&str) -> Option) { - self.each_style(|s| s.style_id = s.style_id.as_deref().and_then(&f)); - } - - /// Unlink chars whose style is gone (`def` gives None) or that no longer show it (edited since). - pub fn check_text_styles<'a>(&mut self, def: impl Fn(&str) -> Option<&'a TextStyle>) { - self.each_style(|s| { - if s.style_id.as_deref().is_some_and(|id| !def(id).is_some_and(|d| s.shows_text_style(d))) { - s.style_id = None; - } - }); - } - - /// Whether every char shares one style (the panel shows "Mixed" otherwise). - pub fn is_uniform(&self) -> bool { - self.runs.is_empty() - } -} - -#[cfg(test)] -mod case_tests { - use super::*; - - #[test] - fn trim_num_prints_huge_whole_numbers() { - assert_eq!(trim_num(1e19), "10000000000000000000"); - assert_eq!(trim_num(-1e19), "-10000000000000000000"); - assert_eq!(trim_num(12.0), "12"); - let v = 12345678901234567890.0_f64; - assert_eq!(trim_num(v).parse::().unwrap(), v); - } - - #[test] - fn title_case_respects_context() { - assert_eq!(TextCase::Title.apply("hello wORLD don't 3d x-ray"), "Hello WORLD Don't 3d X-Ray"); - // Continuing a word from a previous run: no capital. - assert_eq!(TextCase::Title.apply_after("lo world", Some('l')), "lo World"); - assert_eq!(TextCase::Title.apply_after("lo", Some(' ')), "Lo"); - assert_eq!(TextCase::Upper.apply_after("ß", Some('a')), "SS"); - assert!(valid_feature_tag("liga") && valid_feature_tag("ss01")); - assert!(!valid_feature_tag("lig") && !valid_feature_tag("ligatures") && !valid_feature_tag("li\u{e9}")); - } - - #[test] - fn new_text_starts_in_the_builds_default_font() { - // Inter, unless the build names another with `FIGCRAFT_DEFAULT_FONT` (empty means Inter). - let named = option_env!("FIGCRAFT_DEFAULT_FONT").filter(|f| !f.is_empty()); - assert_eq!(DEFAULT_FONT, named.unwrap_or("Inter")); - let st = TextStyle::default(); - assert_eq!(st.font_family, DEFAULT_FONT); - // The family is always written, so a saved file keeps it in a build with another default. - let saved = serde_json::to_value(&st).unwrap(); - assert_eq!(saved["font_family"], DEFAULT_FONT); - } - - #[test] - fn variations_are_backward_compatible_and_imply_weight() { - // Files written before variable fonts load with no custom axes, and stay byte-identical. - let old = r#"{"font_family":"Inter","font_style":"Bold","font_size":12.0}"#; - let st: TextStyle = serde_json::from_str(old).unwrap(); - assert!(st.variations.is_empty()); - assert!(!serde_json::to_string(&st).unwrap().contains("variations")); - let mut st = TextStyle { font_style: "Regular".into(), ..Default::default() }; - st.variations.insert("wght".into(), 640.0); - st.variations.insert("wdth".into(), 80.0); - assert_eq!(st.weight(), 640); - assert!(!st.italic()); - st.variations.insert("slnt".into(), -8.0); - assert!(st.italic()); - let round: TextStyle = serde_json::from_str(&serde_json::to_string(&st).unwrap()).unwrap(); - assert_eq!(round, st); - // Picking a named style drops the axes its name implies, keeps the others. - st.set_font_style("Bold"); - assert_eq!(st.weight(), 700); - assert_eq!(st.variations.keys().collect::>(), ["wdth"]); - assert!(valid_axis_tag("wght") && !valid_axis_tag("weight")); - } - - #[test] - fn list_starts_load_from_old_files_and_follow_edits() { - use ListStyle::{Bulleted as B, None as P, Numbered as N}; - // Files written before start numbers load with none, and write the same bytes. - let old = r#"{"list":"numbered","indent":1}"#; - let pl: ParaList = serde_json::from_str(old).unwrap(); - assert_eq!(pl, ParaList { list: N, indent: 1, start_offset: 0 }); - assert_eq!(serde_json::to_string(&pl).unwrap(), old); - // One numbered paragraph with a start keeps it (it doesn't fold into `list`). - let mut t = TextData { characters: "Next".into(), ..Default::default() }; - t.set_para_lists(0, 0, |p| *p = ParaList { list: N, indent: 0, start_offset: 1 }); - assert_eq!(t.para_list(0), ParaList { list: N, indent: 0, start_offset: 1 }); - // Enter copies it to the new item; different starts don't make the list mixed. - t.replace_range(4, 4, "\nMore"); - assert_eq!(t.para_list(1).start_offset, 1); - t.set_para_lists(5, 5, |p| p.start_offset = 0); - assert!(t.common_para_list(0, t.char_count()).is_some_and(|p| p.list == N)); - // Bullets have no number, so no start. - t.set_para_lists(0, 0, |p| *p = ParaList { list: B, indent: 1, start_offset: 4 }); - assert_eq!(t.para_list(0), ParaList { list: B, indent: 1, start_offset: 0 }); - // A plain paragraph has none. - t.set_para_lists(0, 0, |p| p.list = P); - assert_eq!(t.para_list(0), ParaList::default()); - } -} - -#[cfg(test)] -mod title_case_tests { - use super::TextCase; - - #[test] - fn title_case_after_opening_apostrophe() { - assert_eq!(TextCase::Title.apply("'hello world'"), "'Hello World'"); - assert_eq!(TextCase::Title.apply("say 'hi'"), "Say 'Hi'"); - assert_eq!(TextCase::Title.apply("don't"), "Don't"); - assert_eq!(TextCase::Title.apply("\u{2019}hello"), "\u{2019}Hello"); - } - - #[test] - fn title_case_between_runs_sees_char_before_apostrophe() { - assert_eq!(TextCase::Title.apply_after("t", Some('\'')), "t"); - assert_eq!(TextCase::Title.apply_between("hello", None, Some('\'')), "Hello"); - assert_eq!(TextCase::Title.apply_between("t", Some('n'), Some('\'')), "t"); - assert_eq!(TextCase::Title.apply_between("t", Some(' '), Some('\u{2019}')), "T"); - } - - #[test] - fn title_case_combining_marks_do_not_break_words() { - assert_eq!(TextCase::Title.apply("re\u{301}sume\u{301}"), "Re\u{301}sume\u{301}"); - assert_eq!(TextCase::Title.apply("re\u{301}sume\u{301} bon"), "Re\u{301}sume\u{301} Bon"); - assert_eq!(TextCase::Title.apply("a \u{301}b"), "A \u{301}B"); - assert_eq!(TextCase::Title.apply("cafe\u{301}'s"), "Cafe\u{301}'s"); - } -} - -#[cfg(test)] -mod whole_text_paragraph_style_tests { - use super::*; - - #[test] - fn a_text_style_on_the_whole_layer_reaches_a_trailing_empty_paragraph() { - let ps = ParagraphStyle { list: ListStyle::Bulleted, ..Default::default() }; - let mut t = TextData::new("a\nb\n"); - t.take_paragraph_style(&ps); - assert_eq!(t.paragraph_count(), 3); - assert_eq!(t.para_list(2).list, ListStyle::Bulleted); - assert_eq!(t.list, ListStyle::Bulleted); - assert!(t.paragraphs.is_empty()); - let mut plain = TextData::new("a\nb"); - plain.take_paragraph_style(&ps); - assert_eq!((plain.list, plain.paragraphs.len()), (t.list, t.paragraphs.len())); - } -} +//! Text node data: characters plus a base style and styled runs. + +use figcraft_color::{Color, Paint}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "unit", content = "value", rename_all = "camelCase")] +#[derive(Default)] +pub enum LineHeight { + #[default] + Auto, + Pixels(f64), + Percent(f64), +} + +impl LineHeight { + /// Resolved line height in px for `font_size` (`auto` uses the font's natural ratio). + pub fn resolve(self, font_size: f64, natural_ratio: f64) -> f64 { + match self { + LineHeight::Auto => font_size * natural_ratio, + LineHeight::Pixels(v) => v.max(0.0), + LineHeight::Percent(p) => font_size * p.max(0.0) / 100.0, + } + } + pub fn label(self) -> String { + match self { + LineHeight::Auto => "Auto".into(), + LineHeight::Pixels(v) => trim_num(v), + LineHeight::Percent(p) => format!("{}%", trim_num(p)), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "unit", content = "value", rename_all = "camelCase")] +pub enum LetterSpacing { + Pixels(f64), + Percent(f64), +} + +impl Default for LetterSpacing { + fn default() -> Self { + LetterSpacing::Percent(0.0) + } +} + +impl LetterSpacing { + pub fn resolve(self, font_size: f64) -> f64 { + match self { + LetterSpacing::Pixels(v) => v, + LetterSpacing::Percent(p) => font_size * p / 100.0, + } + } + pub fn label(self) -> String { + match self { + LetterSpacing::Pixels(v) => trim_num(v), + LetterSpacing::Percent(p) => format!("{}%", trim_num(p)), + } + } +} + +pub fn trim_num(v: f64) -> String { + if v.abs() >= 9.0e18 { + return format!("{v}"); + } + let r = (v * 100.0).round() / 100.0; + if r.fract().abs() < 1e-9 { format!("{}", r as i64) } else { format!("{r}") } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum TextDecoration { + #[default] + None, + Underline, + Strikethrough, +} + +/// How an underline or strikethrough is drawn. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum DecorationStyle { + #[default] + Solid, + Dotted, + Wavy, +} + +/// A decoration length: `Auto` (the font's own value), pixels, or a percentage of the font size. +pub type DecorationLength = LineHeight; + +/// How a decoration line looks; the default is the font's own solid line in the text's colour. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct DecorationLook { + pub style: DecorationStyle, + pub thickness: DecorationLength, + /// Underlines: from the baseline down to the line's top edge (negative: above the baseline). + pub offset: DecorationLength, + /// Underlines break where descenders cross them. + pub skip_ink: bool, + /// The line's own colour (None: the text's fills). + pub color: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum TextCase { + #[default] + Original, + Upper, + Lower, + Title, + SmallCaps, +} + +impl TextCase { + pub fn apply(self, s: &str) -> String { + self.apply_after(s, None) + } + + /// Apply the case to `s`, which follows `prev` in the text (so title case only capitalises + /// the first letter of each word even when a word spans several styled runs). An apostrophe + /// as `prev` is taken to continue a word. + pub fn apply_after(self, s: &str, prev: Option) -> String { + self.apply_impl(s, prev, prev.is_some_and(is_word_char)) + } + + /// Like [`apply_after`](Self::apply_after), also given the char `before` `prev`: an apostrophe + /// only continues a word when a letter or digit precedes it. + pub fn apply_between(self, s: &str, before: Option, prev: Option) -> String { + let continues = prev.is_some_and(|c| is_word_char(c) && (c.is_alphanumeric() || before.is_some_and(char::is_alphanumeric))); + self.apply_impl(s, prev, continues) + } + + /// `in_word` says whether `prev` continues a word (rather than a new word starting here). + fn apply_impl(self, s: &str, prev: Option, in_word: bool) -> String { + match self { + TextCase::Original | TextCase::SmallCaps => s.to_string(), + TextCase::Upper => s.to_uppercase(), + TextCase::Lower => s.to_lowercase(), + TextCase::Title => { + let mut out = String::with_capacity(s.len()); + let mut start = !in_word; + let mut last = prev; + for ch in s.chars() { + if start && ch.is_alphanumeric() { + out.extend(ch.to_uppercase()); + start = false; + } else { + out.push(ch); + // An apostrophe only continues a word right after a letter or digit. + let opening_apostrophe = + matches!(ch, '\'' | '\u{2019}') && !last.is_some_and(|c| c.is_alphanumeric() || is_combining_mark(c)); + // A combining mark attaches to the char before it and never changes word state. + if !is_combining_mark(ch) { + start = !is_word_char(ch) || opening_apostrophe; + } + } + last = Some(ch); + } + out + } + } + } + + /// Whether the char at a position preceded by `prev` starts a word (for title case). + pub fn starts_word(prev: Option) -> bool { + prev.is_none_or(|c| !is_word_char(c)) + } +} + +/// Letters, digits, combining marks and apostrophes continue a word (so "don't" stays "Don't" +/// and decomposed accents stay inside their word). +fn is_word_char(c: char) -> bool { + c.is_alphanumeric() || is_combining_mark(c) || matches!(c, '\'' | '\u{2019}') +} + +/// Combining marks such as the U+0301 accent in decomposed text: non-alphanumeric chars that +/// extend the grapheme of the char before them. +fn is_combining_mark(c: char) -> bool { + use unicode_segmentation::UnicodeSegmentation; + if c.is_ascii() || c.is_alphanumeric() { + return false; + } + let mut buf = [0u8; 8]; + buf[0] = b'a'; + let end = 1 + c.encode_utf8(&mut buf[1..]).len(); + std::str::from_utf8(&buf[..end]).is_ok_and(|s| s.graphemes(true).count() == 1) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum TextAlignH { + #[default] + Left, + Center, + Right, + Justified, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum TextAlignV { + #[default] + Top, + Middle, + Bottom, +} + +/// How a text box resizes as its content changes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum TextAutoResize { + /// Auto width: one line per paragraph, box grows both ways. + #[default] + WidthAndHeight, + /// Fixed width, height grows. + Height, + /// Fixed size. + None, + /// Fixed size, truncate with an ellipsis. + Truncate, +} + +/// Vertical trim: what bounds a text box vertically. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum LeadingTrim { + /// The full line height of the first and last lines. + #[default] + None, + /// From the first line's cap height to the last line's baseline. + CapHeight, +} + +/// Where lines break when text wraps to more than one line ("Wrap style controls where lines +/// break when text wraps to more than one line", Explore text properties). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum WrapStyle { + /// "Figma fits as many words as possible on each line before wrapping to the next." + #[default] + Auto, + /// "Figma distributes text as evenly as possible across every line, so each line is close to + /// the same length." + Balance, + /// "Figma keeps each line full, but adjusts the last four lines to avoid an orphan -- a single + /// word stranded alone on the last line." + Pretty, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum ListStyle { + #[default] + None, + Bulleted, + Numbered, +} + +/// Deepest list nesting (levels 0..=MAX_LIST_INDENT). +pub const MAX_LIST_INDENT: u8 = 8; + +/// One paragraph's list settings. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct ParaList { + pub list: ListStyle, + /// Nesting level (0 = outermost). A plain paragraph is 0, except one that left its list by + /// Backspace or Delete at its start ([`TextData::unlist_keeping_levels`]): it keeps the level + /// it had and starts where that level's item text does ("delete the counter, but keep the + /// same level of indentation"). + pub indent: u8, + /// A numbered list that starts counting at this paragraph counts from `start_offset + 1` + /// (items that go on counting ignore it; other paragraphs are always 0). + #[serde(skip_serializing_if = "crate::node::is_default")] + pub start_offset: u32, +} + +/// Character style. In runs, every field is an override; `None` means "inherit the base". +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct TextStyle { + pub font_family: String, + /// The style name, e.g. "Regular", "Bold", "Semi Bold Italic". + pub font_style: String, + pub font_size: f64, + pub line_height: LineHeight, + pub letter_spacing: LetterSpacing, + pub decoration: TextDecoration, + /// How the decoration looks (None: the default look; boxed to keep styles small). + #[serde(skip_serializing_if = "Option::is_none")] + pub decoration_look: Option>, + pub case: TextCase, + /// Run fills (None = node fills). + pub fills: Option>, + /// Hyperlink. + pub link: Option, + /// Variable font axis values in user space, keyed by 4-char OpenType axis tag (e.g. `wght`: + /// 550, `wdth`: 85). Empty = what the style name implies; axes the face lacks are ignored. + #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub variations: std::collections::BTreeMap, + /// The text style (shared style id) these chars are linked to. A layer's chars can link to + /// different styles; editing what a style sets unlinks the chars edited. + #[serde(skip_serializing_if = "Option::is_none")] + pub style_id: Option, +} + +/// What a text style sets at the paragraph and layer level, beside its character style +/// ([`TextStyle`]): paragraph spacing and indent, the list style and the OpenType features +/// ("Supported in text styles": "Paragraph spacing and indentation", "Lists", "OpenType +/// features", Create and apply text styles). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct ParagraphStyle { + #[serde(skip_serializing_if = "crate::node::is_default")] + pub paragraph_spacing: f64, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub paragraph_indent: f64, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub list: ListStyle, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub features: std::collections::BTreeMap, +} + +/// The font new text starts in. A build can name another (`FIGCRAFT_DEFAULT_FONT="Noto Sans Thai"`, +/// for a distribution whose users mostly write a script Inter lacks); empty means Inter. +pub const DEFAULT_FONT: &str = match option_env!("FIGCRAFT_DEFAULT_FONT") { + Some(family) if !family.is_empty() => family, + _ => "Inter", +}; + +impl Default for TextStyle { + fn default() -> Self { + Self { + font_family: DEFAULT_FONT.into(), + font_style: "Regular".into(), + font_size: 12.0, + line_height: LineHeight::Auto, + letter_spacing: LetterSpacing::default(), + decoration: TextDecoration::None, + decoration_look: None, + case: TextCase::Original, + fills: None, + link: None, + variations: std::collections::BTreeMap::new(), + style_id: None, + } + } +} + +/// Axes a style name implies (weight, italic, slant): picking a named style clears their custom values. +pub const STYLE_AXES: [&str; 3] = ["wght", "ital", "slnt"]; + +impl TextStyle { + /// Numeric weight: a custom `wght` axis value, else the one implied by the style name. + pub fn weight(&self) -> u16 { + match self.variations.get("wght") { + Some(w) if w.is_finite() => w.round().clamp(1.0, 1000.0) as u16, + _ => style_weight(&self.font_style), + } + } + pub fn italic(&self) -> bool { + self.font_style.to_ascii_lowercase().contains("italic") + || self.variations.get("ital").is_some_and(|v| *v >= 0.5) + || self.variations.get("slnt").is_some_and(|v| *v != 0.0) + } + + /// Take what text style `def` sets (font, size, line height, letter spacing, decoration, case + /// and axis values) and link to it as `id`; fills and hyperlinks stay. + pub fn take_text_style(&mut self, def: &TextStyle, id: &str) { + *self = TextStyle { fills: self.fills.take(), link: self.link.take(), style_id: Some(id.to_string()), ..def.clone() }; + } + + /// Whether these chars show what text style `def` sets. + pub fn shows_text_style(&self, def: &TextStyle) -> bool { + self.font_family == def.font_family + && self.font_style == def.font_style + && self.font_size == def.font_size + && self.line_height == def.line_height + && self.letter_spacing == def.letter_spacing + && self.decoration == def.decoration + && self.decoration_look == def.decoration_look + && self.case == def.case + && self.variations == def.variations + } + + /// This style as a text style's definition (linked to nothing). + pub fn as_text_style(&self) -> TextStyle { + TextStyle { style_id: None, link: None, ..self.clone() } + } + + /// How the decoration looks. + pub fn look(&self) -> DecorationLook { + self.decoration_look.as_deref().copied().unwrap_or_default() + } + + /// Change how the decoration looks (the default look is stored as None). + pub fn set_look(&mut self, f: impl FnOnce(&mut DecorationLook)) { + let mut look = self.look(); + f(&mut look); + self.decoration_look = (look != DecorationLook::default()).then(|| Box::new(look)); + } + + /// Switch to the named style, dropping custom values of the axes the name implies. + pub fn set_font_style(&mut self, name: impl Into) { + self.font_style = name.into(); + for tag in STYLE_AXES { + self.variations.remove(tag); + } + } +} + +/// Weight from a style name ("Semi Bold Italic" → 600). +pub fn style_weight(style: &str) -> u16 { + let s = style.to_ascii_lowercase().replace([' ', '-'], ""); + // A weight number ("600", "600 Italic"), as some apps name styles. + let digits: String = s.chars().take_while(char::is_ascii_digit).collect(); + if let Ok(n) = digits.parse::() + && (1..=1000).contains(&n) + { + return n; + } + let table: [(&str, u16); 10] = [ + ("thin", 100), + ("extralight", 200), + ("ultralight", 200), + ("light", 300), + ("medium", 500), + ("semibold", 600), + ("demibold", 600), + ("extrabold", 800), + ("ultrabold", 800), + ("black", 900), + ]; + for (k, w) in table { + if s.contains(k) { + return w; + } + } + if s.contains("bold") { + return 700; + } + if s.contains("heavy") { + return 900; + } + 400 +} + +/// A styled range of characters (char indices, end exclusive). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct StyleRun { + pub start: usize, + pub end: usize, + pub style: TextStyle, +} + +/// Text node content. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct TextData { + pub characters: String, + pub style: TextStyle, + /// Ranges whose style differs from `style`; full styles (already merged), non-overlapping, sorted. + #[serde(skip_serializing_if = "crate::node::is_default")] + pub runs: Vec, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub auto_resize: TextAutoResize, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub align_h: TextAlignH, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub align_v: TextAlignV, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub paragraph_spacing: f64, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub paragraph_indent: f64, + /// The list style of paragraphs `paragraphs` doesn't cover (all of them when it's empty). + #[serde(skip_serializing_if = "crate::node::is_default")] + pub list: ListStyle, + /// Per-paragraph list settings, by paragraph index; empty when every paragraph is `list` at + /// level 0. Kept in step with the characters by [`TextData::replace_range`]. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub paragraphs: Vec, + /// Space between two items of a list (px), in place of the paragraph spacing. + #[serde(skip_serializing_if = "crate::node::is_default")] + pub list_spacing: f64, + /// Opening and closing punctuation at a line's aligned edge sits outside the box. + #[serde(skip_serializing_if = "crate::node::is_default")] + pub hanging_punctuation: bool, + /// List bullets and numbers sit outside the box; item text lines up with plain paragraphs. + #[serde(skip_serializing_if = "crate::node::is_default")] + pub hanging_list: bool, + /// Vertical trim (`capHeight`: the box runs from the first line's cap height to the last + /// line's baseline). + #[serde(skip_serializing_if = "crate::node::is_default")] + pub leading_trim: LeadingTrim, + /// Max lines when truncating, or before an auto-height text ends in an ellipsis (0 = as many + /// as fit). + #[serde(skip_serializing_if = "crate::node::is_default")] + pub max_lines: u32, + /// Where lines break when the text wraps: greedily (Auto), as evenly as the words allow + /// (Balance), or full with no one word alone on the last line (Pretty). + #[serde(skip_serializing_if = "crate::node::is_default")] + pub wrap_style: WrapStyle, + /// OpenType feature toggles (e.g. "liga": false). + #[serde(skip_serializing_if = "crate::node::is_default")] + pub features: std::collections::BTreeMap, + /// The path the text follows (text on a path); `None`: lines in the box. Boxed to keep text + /// data small. + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option>, + /// Where the file this text came from wrapped its lines (an imported `.fig`'s saved layout). + /// Layout follows them only while the box width and everything that moves a line break are + /// as they were saved, so an edit that could change the wrap drops them. + #[serde(skip_serializing_if = "Option::is_none")] + pub saved_breaks: Option>, +} + +/// Line breaks a file saved with a text: the chars that start a wrapped line (not those after a +/// hard break), for the box width and the content ([`TextData::layout_key`]) they were made for. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct SavedBreaks { + pub starts: Vec, + pub width: f64, + pub for_text: u64, +} + +/// Text on a path: the baseline follows `d`. The text starts at `start` (aligned there by the +/// horizontal alignment: left starts, centre centres, right ends at it); glyphs past an open +/// path's ends are hidden, a closed path wraps them around. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct TextPath { + /// SVG path data in the layer's own space. + pub d: String, + /// Where the text starts along the path, 0..1 by length. + pub start: f64, + /// On the other side of the path, running the other way. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub flip: bool, +} + +impl TextPath { + /// A text path following `path` (layer space). + pub fn new(path: &figcraft_geom::BezPath) -> Self { + Self { d: path.to_svg(), start: 0.0, flip: false } + } + + /// The path (empty when `d` doesn't parse). + pub fn path(&self) -> figcraft_geom::BezPath { + figcraft_geom::BezPath::from_svg(&self.d).unwrap_or_default() + } + + /// The start offset clamped into 0..1 (NaN: 0). + pub fn start(&self) -> f64 { + if self.start.is_finite() { self.start.clamp(0.0, 1.0) } else { 0.0 } + } + + /// Scale the path by `sx`, `sy` (the layer was resized). + pub fn scale(&mut self, sx: f64, sy: f64) { + if sx.is_finite() && sy.is_finite() { + let mut p = self.path(); + p.apply_affine(figcraft_geom::Affine::scale_non_uniform(sx, sy)); + self.d = p.to_svg(); + } + } +} + +/// Whether `tag` is a valid OpenType feature tag (four printable ASCII chars). +pub fn valid_feature_tag(tag: &str) -> bool { + tag.len() == 4 && tag.bytes().all(|b| (0x20..0x7f).contains(&b)) +} + +/// Whether `tag` is a valid OpenType variation axis tag (same shape as a feature tag). +pub fn valid_axis_tag(tag: &str) -> bool { + valid_feature_tag(tag) +} + +impl TextData { + pub fn new(characters: impl Into) -> Self { + Self { characters: characters.into(), ..Default::default() } + } + + /// A stable hash of what decides where lines break: everything but paints, links, style links, + /// decorations, vertical settings and the saved breaks themselves (FNV-1a over the JSON, so it + /// stays the same across builds and can be saved). + pub fn layout_key(&self) -> u64 { + let clear = |s: &mut TextStyle| { + (s.fills, s.link, s.style_id, s.decoration, s.decoration_look) = (None, None, None, TextDecoration::None, None); + }; + let mut t = TextData { + align_v: TextAlignV::default(), + paragraph_spacing: 0.0, + list_spacing: 0.0, + leading_trim: LeadingTrim::default(), + max_lines: 0, + saved_breaks: None, + ..self.clone() + }; + clear(&mut t.style); + t.runs.iter_mut().for_each(|r| clear(&mut r.style)); + t.normalize(); + serde_json::to_vec(&t).unwrap_or_default().iter().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) + } + + /// Keep `starts` (chars that start a wrapped line) as this text's saved line breaks in a box + /// `width` wide. + pub fn save_breaks(&mut self, starts: Vec, width: f64) { + self.saved_breaks = Some(Box::new(SavedBreaks { starts, width, for_text: self.layout_key() })); + } + + /// The saved line starts (empty: no wrapped line) while they still hold: the same box width and + /// layout content, and starts increasing inside the text. + pub fn saved_breaks_for(&self, width: f64) -> Option<&[usize]> { + let b = self.saved_breaks.as_deref()?; + let inside = b.starts.first().is_none_or(|s| *s > 0) && b.starts.last().is_none_or(|s| *s < self.char_count()); + let same_box = (b.width - width).abs() <= 1e-6 * width.abs().max(1.0); + (inside && same_box && b.starts.is_sorted_by(|a, b| a < b) && b.for_text == self.layout_key()).then_some(b.starts.as_slice()) + } + + /// How far text on a path paints past its path's box (glyphs stand on the path, lines after + /// the first run beside it): about one and a half of the largest size per line; 0 off a path. + pub fn path_reach(&self) -> f64 { + if self.path.is_none() { + return 0.0; + } + let lines = self.characters.lines().count().clamp(1, 10_000) as f64; + self.max_size() * 1.5 * lines + } + + /// How far vertically trimmed text paints past its box (descenders below the last baseline, + /// accents above the first cap height): half the largest size; 0 untrimmed. + pub fn trim_reach(&self) -> f64 { + if self.leading_trim == LeadingTrim::None { 0.0 } else { self.max_size() * 0.5 } + } + + /// The largest font size used (capped like layout caps it). + fn max_size(&self) -> f64 { + self.spans().iter().map(|(_, _, s)| s.font_size).filter(|v| v.is_finite()).fold(0.0, f64::max).min(5000.0) + } + + pub fn char_count(&self) -> usize { + self.characters.chars().count() + } + + /// Whether text that runs out of room ends in an ellipsis: a truncating box, or auto height + /// or auto width with a line limit (the box hugs up to `max_lines` lines: "Max lines is + /// available only if truncate text is enabled, and: Text resizing is set to auto height or + /// auto width"). + pub fn truncates(&self) -> bool { + match self.auto_resize { + TextAutoResize::Truncate => true, + TextAutoResize::Height | TextAutoResize::WidthAndHeight => self.max_lines > 0, + TextAutoResize::None => false, + } + } + + /// The resize mode once the box is given an explicit `width` and/or `height`: an explicit + /// height fixes the box, an explicit width turns auto width into auto height, and truncating + /// text keeps truncating. + pub fn fix_size(&mut self, width: bool, height: bool) { + self.auto_resize = match self.auto_resize { + _ if height && self.truncates() => TextAutoResize::Truncate, + _ if height => TextAutoResize::None, + TextAutoResize::WidthAndHeight if width => TextAutoResize::Height, + mode => mode, + }; + } + + /// The style at char index `i`. + pub fn style_at(&self, i: usize) -> &TextStyle { + self.runs.iter().find(|r| r.start <= i && i < r.end).map(|r| &r.style).unwrap_or(&self.style) + } + + /// Spans of uniform style covering the whole text: (start, end, style). + pub fn spans(&self) -> Vec<(usize, usize, &TextStyle)> { + let n = self.char_count(); + let mut out = Vec::new(); + let mut pos = 0; + let mut runs: Vec<&StyleRun> = self.runs.iter().filter(|r| r.start < r.end && r.start < n).collect(); + runs.sort_by_key(|r| r.start); + for r in runs { + let start = r.start.max(pos); + let end = r.end.min(n); + if start >= end { + continue; + } + if start > pos { + out.push((pos, start, &self.style)); + } + out.push((start, end, &r.style)); + pos = end; + } + if pos < n || out.is_empty() { + out.push((pos, n, &self.style)); + } + out + } + + /// Apply `f` to the style of chars `start..end` (all text when the range is the whole text or + /// empty text), splitting runs as needed and merging equal neighbours. + pub fn restyle(&mut self, start: usize, end: usize, f: impl Fn(&mut TextStyle)) { + let n = self.char_count(); + let (start, end) = (start.min(n), end.min(n)); + if n == 0 || (start == 0 && end >= n) { + f(&mut self.style); + for r in &mut self.runs { + f(&mut r.style); + } + self.normalize(); + return; + } + if start >= end { + return; + } + // Expand to per-char styles, modify, re-compress. + let mut per: Vec = (0..n).map(|i| self.style_at(i).clone()).collect(); + for s in per.iter_mut().take(end).skip(start) { + f(s); + } + self.runs.clear(); + let mut i = 0; + while i < n { + let Some(s) = per.get(i) else { break }; + let mut j = i + 1; + while per.get(j).is_some_and(|t| t == s) { + j += 1; + } + if *s != self.style { + self.runs.push(StyleRun { start: i, end: j, style: s.clone() }); + } + i = j; + } + } + + /// Drop empty/out-of-range runs and runs equal to the base style, and merge touching equal runs. + pub fn normalize(&mut self) { + let n = self.char_count(); + let base = self.style.clone(); + self.runs.retain(|r| r.start < r.end && r.start < n && r.style != base); + for r in &mut self.runs { + r.end = r.end.min(n); + } + self.runs.sort_by_key(|r| r.start); + let mut merged: Vec = Vec::with_capacity(self.runs.len()); + for mut r in std::mem::take(&mut self.runs) { + // Runs never overlap: a later run starts where the previous one ends at the earliest. + if let Some(prev) = merged.last() { + r.start = r.start.max(prev.end); + if r.start >= r.end { + continue; + } + } + match merged.last_mut() { + Some(prev) if prev.end == r.start && prev.style == r.style => prev.end = r.end, + _ => merged.push(r), + } + } + self.runs = merged; + } + + /// Replace chars `start..end` with `text`, shifting runs (inserted text takes the style at `start`). + pub fn replace_range(&mut self, start: usize, end: usize, text: &str) { + let n = self.char_count(); + let (start, end) = (start.min(n), end.min(n).max(start.min(n))); + let byte = |i: usize| self.characters.char_indices().nth(i).map(|(b, _)| b).unwrap_or(self.characters.len()); + let (bs, be) = (byte(start), byte(end)); + if !self.paragraphs.is_empty() { + // Paragraphs merged by removed newlines take the first one's list; new ones copy it. + let p = self.para_of(start); + let removed = self.characters.get(bs..be).unwrap_or("").matches('\n').count(); + let added = text.matches('\n').count(); + self.fill_paragraphs(); + let at = self.para_list(p); + let tail = (p + 1).min(self.paragraphs.len()); + self.paragraphs.drain(tail..(p + 1 + removed).min(self.paragraphs.len())); + self.paragraphs.splice(tail..tail, std::iter::repeat_n(at, added)); + } + let mut s = String::with_capacity(self.characters.len() + text.len()); + s.push_str(self.characters.get(..bs).unwrap_or("")); + s.push_str(text); + s.push_str(self.characters.get(be..).unwrap_or("")); + self.characters = s; + let inserted = text.chars().count(); + let removed = end - start; + for r in &mut self.runs { + let shift = |p: usize| -> usize { + if p <= start { + p + } else if p >= end { + // Runs of a file that reach past the text (nothing clamps them on load) + // would otherwise overflow here; `normalize` below drops what is left. + p.saturating_sub(removed).saturating_add(inserted) + } else { + start + inserted + } + }; + // A run touching the insertion point at its end grows with the typed text. + let new_start = shift(r.start); + let new_end = if r.end == start && r.start < start { start + inserted } else { shift(r.end) }; + r.start = new_start; + r.end = new_end; + } + self.normalize(); + } + + pub fn paragraph_count(&self) -> usize { + self.characters.matches('\n').count() + 1 + } + + /// The paragraph char index `i` is in. + pub fn para_of(&self, i: usize) -> usize { + self.characters.chars().take(i).filter(|c| *c == '\n').count() + } + + /// Paragraph `p`'s list settings. + pub fn para_list(&self, p: usize) -> ParaList { + self.paragraphs.get(p).copied().unwrap_or(ParaList { list: self.list, ..ParaList::default() }) + } + + /// Spell out every paragraph's list settings in `paragraphs` (and drop extra entries). + fn fill_paragraphs(&mut self) { + let n = self.paragraph_count(); + let fill = ParaList { list: self.list, ..ParaList::default() }; + self.paragraphs.resize(n, fill); + } + + /// The paragraphs chars `start..end` touch (a caret: its paragraph; a selection ending just + /// after a newline leaves the next paragraph out). + pub fn para_span(&self, start: usize, end: usize) -> (usize, usize) { + let (s, e) = (start.min(end), start.max(end)); + let (a, b) = (self.para_of(s), self.para_of(e)); + let ends_at_start = e > s && b > a && self.characters.chars().nth(e - 1) == Some('\n'); + (a, if ends_at_start { b - 1 } else { b }) + } + + /// Apply `f` to the list settings of the paragraphs chars `start..end` touch (plain + /// paragraphs stay at level 0, only numbered ones keep a start, levels stop at + /// [`MAX_LIST_INDENT`]); one style for all with no nesting or start folds back into `list`. + pub fn set_para_lists(&mut self, start: usize, end: usize, f: impl Fn(&mut ParaList)) { + self.set_para_lists_with(start, end, false, f); + } + + /// Take the list items among the paragraphs chars `start..end` touch out of their list at the + /// level they had, as Backspace or Delete at an item's start does: "delete the counter, but + /// keep the same level of indentation" (Create bulleted and numbered lists). + pub fn unlist_keeping_levels(&mut self, start: usize, end: usize) { + self.set_para_lists_with(start, end, true, |pl| pl.list = ListStyle::None); + } + + fn set_para_lists_with(&mut self, start: usize, end: usize, keep_levels: bool, f: impl Fn(&mut ParaList)) { + let (a, b) = self.para_span(start, end); + self.set_para_lists_between(a, b, keep_levels, f); + } + + /// As [`set_para_lists`](Self::set_para_lists), for paragraphs `a..=b` addressed directly. + fn set_para_lists_between(&mut self, a: usize, b: usize, keep_levels: bool, f: impl Fn(&mut ParaList)) { + self.fill_paragraphs(); + for pl in self.paragraphs.get_mut(a..=b).unwrap_or(&mut []) { + f(pl); + if pl.list == ListStyle::None && !keep_levels { + pl.indent = 0; + } + if pl.list != ListStyle::Numbered { + pl.start_offset = 0; + } + pl.indent = pl.indent.min(MAX_LIST_INDENT); + } + if let Some(first) = self.paragraphs.first().copied() + && first == (ParaList { list: first.list, ..ParaList::default() }) + && self.paragraphs.iter().all(|p| *p == first) + { + self.list = first.list; + self.paragraphs.clear(); + } + } + + /// The list style and level shared by the paragraphs chars `start..end` touch (the first + /// one's settings), or None when they differ. Start numbers don't count. + pub fn common_para_list(&self, start: usize, end: usize) -> Option { + let (a, b) = self.para_span(start, end); + let first = self.para_list(a); + (a..=b).all(|p| self.para_list(p).list == first.list && self.para_list(p).indent == first.indent).then_some(first) + } + + /// What a text style made from this text sets at the paragraph and layer level: the paragraph + /// spacing and indent, the list style (the one every paragraph shares; the base one when they + /// differ) and the OpenType features. + pub fn paragraph_style(&self) -> ParagraphStyle { + let list = match self.paragraphs.first() { + Some(first) if self.paragraphs.iter().all(|p| p.list == first.list) => first.list, + _ => self.list, + }; + ParagraphStyle { paragraph_spacing: self.paragraph_spacing, paragraph_indent: self.paragraph_indent, list, features: self.features.clone() } + } + + /// Take what text style `ps` sets at the paragraph and layer level: the spacing, indent and + /// features on the layer, the list style on every paragraph. + pub fn take_paragraph_style(&mut self, ps: &ParagraphStyle) { + self.paragraph_spacing = ps.paragraph_spacing; + self.paragraph_indent = ps.paragraph_indent; + self.features.clone_from(&ps.features); + // Every paragraph by index: `para_span` leaves out an empty one after a final newline. + let last = self.paragraph_count() - 1; + self.set_para_lists_between(0, last, false, |pl| pl.list = ps.list); + } + + /// As [`take_paragraph_style`](Self::take_paragraph_style), with the list style going to the + /// paragraphs chars `start..end` touch only; the spacing, indent and features are the + /// layer's, as in Figma. + pub fn take_paragraph_style_in(&mut self, start: usize, end: usize, ps: &ParagraphStyle) { + self.paragraph_spacing = ps.paragraph_spacing; + self.paragraph_indent = ps.paragraph_indent; + self.features.clone_from(&ps.features); + self.set_para_lists(start, end, |pl| pl.list = ps.list); + } + + /// Follow text style `id`'s paragraph-level definition wherever chars link to it. + pub fn update_paragraph_style(&mut self, id: &str, ps: &ParagraphStyle) { + let linked: Vec<(usize, usize)> = + self.spans().into_iter().filter(|(_, _, s)| s.style_id.as_deref() == Some(id)).map(|(a, b, _)| (a, b)).collect(); + for (a, b) in linked { + self.take_paragraph_style_in(a, b, ps); + } + } + + /// Whether chars `start..end` show what text style `ps` sets at the paragraph and layer + /// level: the layer's spacing, indent and features, and their paragraphs' list style. + pub fn shows_paragraph_style_in(&self, start: usize, end: usize, ps: &ParagraphStyle) -> bool { + self.paragraph_spacing == ps.paragraph_spacing + && self.paragraph_indent == ps.paragraph_indent + && self.features == ps.features + && self.common_para_list(start, end).is_some_and(|pl| pl.list == ps.list) + } + + /// Whether the whole text shows what text style `ps` sets at the paragraph and layer level. + pub fn shows_paragraph_style(&self, ps: &ParagraphStyle) -> bool { + self.shows_paragraph_style_in(0, self.char_count(), ps) + } + + /// Link chars `start..end` (all of them when the range is empty or the whole text) to text + /// style `id`, defined as `def`. + pub fn link_text_style(&mut self, start: usize, end: usize, def: &TextStyle, id: &str) { + let (start, end) = if start == end { (0, self.char_count()) } else { (start, end) }; + self.restyle(start, end, |s| s.take_text_style(def, id)); + } + + /// Unlink chars `start..end` (all when empty or whole) from their text styles; values stay. + pub fn unlink_text_style(&mut self, start: usize, end: usize) { + let (start, end) = if start == end { (0, self.char_count()) } else { (start, end) }; + self.restyle(start, end, |s| s.style_id = None); + } + + /// The text style every char is linked to: `Some(None)` when none is, None when they differ. + pub fn text_style_link(&self) -> Option> { + let mut spans = self.spans().into_iter().map(|(_, _, s)| s.style_id.as_deref()); + let first = spans.next()?; + spans.all(|s| s == first).then_some(first) + } + + /// Apply `f` to every distinct style (the base and each run) and merge runs that became equal. + pub(crate) fn each_style(&mut self, mut f: impl FnMut(&mut TextStyle)) { + f(&mut self.style); + for r in &mut self.runs { + f(&mut r.style); + } + self.normalize(); + } + + /// Whether any char links to text style `id`. + pub fn links_text_style(&self, id: &str) -> bool { + std::iter::once(&self.style).chain(self.runs.iter().map(|r| &r.style)).any(|s| s.style_id.as_deref() == Some(id)) + } + + /// Follow text style `id`'s new definition wherever chars link to it. + pub fn update_text_style(&mut self, id: &str, def: &TextStyle) { + self.each_style(|s| { + if s.style_id.as_deref() == Some(id) { + s.take_text_style(def, id); + } + }); + } + + /// Point text style links elsewhere: `f(id)` gives the new id, None unlinks (values stay). + pub fn map_text_styles(&mut self, f: impl Fn(&str) -> Option) { + self.each_style(|s| s.style_id = s.style_id.as_deref().and_then(&f)); + } + + /// Unlink chars whose style is gone (`def` gives None) or that no longer show it (edited since). + pub fn check_text_styles<'a>(&mut self, def: impl Fn(&str) -> Option<&'a TextStyle>) { + self.each_style(|s| { + if s.style_id.as_deref().is_some_and(|id| !def(id).is_some_and(|d| s.shows_text_style(d))) { + s.style_id = None; + } + }); + } + + /// Whether every char shares one style (the panel shows "Mixed" otherwise). + pub fn is_uniform(&self) -> bool { + self.runs.is_empty() + } +} + +#[cfg(test)] +mod case_tests { + use super::*; + + #[test] + fn trim_num_prints_huge_whole_numbers() { + assert_eq!(trim_num(1e19), "10000000000000000000"); + assert_eq!(trim_num(-1e19), "-10000000000000000000"); + assert_eq!(trim_num(12.0), "12"); + let v = 12345678901234567890.0_f64; + assert_eq!(trim_num(v).parse::().unwrap(), v); + } + + #[test] + fn title_case_respects_context() { + assert_eq!(TextCase::Title.apply("hello wORLD don't 3d x-ray"), "Hello WORLD Don't 3d X-Ray"); + // Continuing a word from a previous run: no capital. + assert_eq!(TextCase::Title.apply_after("lo world", Some('l')), "lo World"); + assert_eq!(TextCase::Title.apply_after("lo", Some(' ')), "Lo"); + assert_eq!(TextCase::Upper.apply_after("ß", Some('a')), "SS"); + assert!(valid_feature_tag("liga") && valid_feature_tag("ss01")); + assert!(!valid_feature_tag("lig") && !valid_feature_tag("ligatures") && !valid_feature_tag("li\u{e9}")); + } + + #[test] + fn new_text_starts_in_the_builds_default_font() { + // Inter, unless the build names another with `FIGCRAFT_DEFAULT_FONT` (empty means Inter). + let named = option_env!("FIGCRAFT_DEFAULT_FONT").filter(|f| !f.is_empty()); + assert_eq!(DEFAULT_FONT, named.unwrap_or("Inter")); + let st = TextStyle::default(); + assert_eq!(st.font_family, DEFAULT_FONT); + // The family is always written, so a saved file keeps it in a build with another default. + let saved = serde_json::to_value(&st).unwrap(); + assert_eq!(saved["font_family"], DEFAULT_FONT); + } + + #[test] + fn variations_are_backward_compatible_and_imply_weight() { + // Files written before variable fonts load with no custom axes, and stay byte-identical. + let old = r#"{"font_family":"Inter","font_style":"Bold","font_size":12.0}"#; + let st: TextStyle = serde_json::from_str(old).unwrap(); + assert!(st.variations.is_empty()); + assert!(!serde_json::to_string(&st).unwrap().contains("variations")); + let mut st = TextStyle { font_style: "Regular".into(), ..Default::default() }; + st.variations.insert("wght".into(), 640.0); + st.variations.insert("wdth".into(), 80.0); + assert_eq!(st.weight(), 640); + assert!(!st.italic()); + st.variations.insert("slnt".into(), -8.0); + assert!(st.italic()); + let round: TextStyle = serde_json::from_str(&serde_json::to_string(&st).unwrap()).unwrap(); + assert_eq!(round, st); + // Picking a named style drops the axes its name implies, keeps the others. + st.set_font_style("Bold"); + assert_eq!(st.weight(), 700); + assert_eq!(st.variations.keys().collect::>(), ["wdth"]); + assert!(valid_axis_tag("wght") && !valid_axis_tag("weight")); + } + + #[test] + fn list_starts_load_from_old_files_and_follow_edits() { + use ListStyle::{Bulleted as B, None as P, Numbered as N}; + // Files written before start numbers load with none, and write the same bytes. + let old = r#"{"list":"numbered","indent":1}"#; + let pl: ParaList = serde_json::from_str(old).unwrap(); + assert_eq!(pl, ParaList { list: N, indent: 1, start_offset: 0 }); + assert_eq!(serde_json::to_string(&pl).unwrap(), old); + // One numbered paragraph with a start keeps it (it doesn't fold into `list`). + let mut t = TextData { characters: "Next".into(), ..Default::default() }; + t.set_para_lists(0, 0, |p| *p = ParaList { list: N, indent: 0, start_offset: 1 }); + assert_eq!(t.para_list(0), ParaList { list: N, indent: 0, start_offset: 1 }); + // Enter copies it to the new item; different starts don't make the list mixed. + t.replace_range(4, 4, "\nMore"); + assert_eq!(t.para_list(1).start_offset, 1); + t.set_para_lists(5, 5, |p| p.start_offset = 0); + assert!(t.common_para_list(0, t.char_count()).is_some_and(|p| p.list == N)); + // Bullets have no number, so no start. + t.set_para_lists(0, 0, |p| *p = ParaList { list: B, indent: 1, start_offset: 4 }); + assert_eq!(t.para_list(0), ParaList { list: B, indent: 1, start_offset: 0 }); + // A plain paragraph has none. + t.set_para_lists(0, 0, |p| p.list = P); + assert_eq!(t.para_list(0), ParaList::default()); + } +} + +#[cfg(test)] +mod title_case_tests { + use super::TextCase; + + #[test] + fn title_case_after_opening_apostrophe() { + assert_eq!(TextCase::Title.apply("'hello world'"), "'Hello World'"); + assert_eq!(TextCase::Title.apply("say 'hi'"), "Say 'Hi'"); + assert_eq!(TextCase::Title.apply("don't"), "Don't"); + assert_eq!(TextCase::Title.apply("\u{2019}hello"), "\u{2019}Hello"); + } + + #[test] + fn title_case_between_runs_sees_char_before_apostrophe() { + assert_eq!(TextCase::Title.apply_after("t", Some('\'')), "t"); + assert_eq!(TextCase::Title.apply_between("hello", None, Some('\'')), "Hello"); + assert_eq!(TextCase::Title.apply_between("t", Some('n'), Some('\'')), "t"); + assert_eq!(TextCase::Title.apply_between("t", Some(' '), Some('\u{2019}')), "T"); + } + + #[test] + fn title_case_combining_marks_do_not_break_words() { + assert_eq!(TextCase::Title.apply("re\u{301}sume\u{301}"), "Re\u{301}sume\u{301}"); + assert_eq!(TextCase::Title.apply("re\u{301}sume\u{301} bon"), "Re\u{301}sume\u{301} Bon"); + assert_eq!(TextCase::Title.apply("a \u{301}b"), "A \u{301}B"); + assert_eq!(TextCase::Title.apply("cafe\u{301}'s"), "Cafe\u{301}'s"); + } +} + +#[cfg(test)] +mod whole_text_paragraph_style_tests { + use super::*; + + #[test] + fn a_text_style_on_the_whole_layer_reaches_a_trailing_empty_paragraph() { + let ps = ParagraphStyle { list: ListStyle::Bulleted, ..Default::default() }; + let mut t = TextData::new("a\nb\n"); + t.take_paragraph_style(&ps); + assert_eq!(t.paragraph_count(), 3); + assert_eq!(t.para_list(2).list, ListStyle::Bulleted); + assert_eq!(t.list, ListStyle::Bulleted); + assert!(t.paragraphs.is_empty()); + let mut plain = TextData::new("a\nb"); + plain.take_paragraph_style(&ps); + assert_eq!((plain.list, plain.paragraphs.len()), (t.list, t.paragraphs.len())); + } +} From 971c82b8f1897957a18fbe9cf7ee91946d91c100 Mon Sep 17 00:00:00 2001 From: ashokram-si <347905169+ashokram-si@users.noreply.github.com> Date: Fri, 6 Nov 2026 09:48:06 +0530 Subject: [PATCH 090/102] M1, #1758: a primary drag let go during a pan still ends --- crates/ui-egui/src/canvas/input.rs | 40 ++++++++++++------- crates/ui-egui/tests/it/canvas_pan_release.rs | 22 ++++++++++ 2 files changed, 48 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index d59054c0b..30c964c44 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -148,6 +148,31 @@ fn import_dropped(app: &mut FigApp, ctx: &egui::Context, hover_pos: Option app.canvas.middle_pan = Some((pos, ds.view.cx, ds.view.cy)), + Some((p0, cx, cy)) => { + let z = ds.view.zoom.max(1e-6); + ds.view.cx = cx - f64::from(pos.x - p0.x) / z; + ds.view.cy = cy - f64::from(pos.y - p0.y) / z; + ds.revision += 1; + } + } + } + // A primary drag under way when the pan began ends when its button is let go, pan or + // not: the engine gets its release here, as it does over the canvas or off it. + if app.canvas.dragging && !ctx.input(|i| i.pointer.primary_down()) { + app.canvas.dragging = false; + send(app, PointerKind::Up, pos, mods); + } + if !middle_down && !ctx.input(|i| i.pointer.primary_down()) { + app.canvas.middle_pan = None; + } +} + /// The pointer and keys on the canvas. False when something on it with a cursor of its own has /// the pointer (a comment pin, a ruler guide, a gradient or padding handle): the tool's cursor /// then doesn't show. @@ -224,20 +249,7 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo // Middle-button (or side-button) / space panning. let middle_down = ctx.input(pan_button_down); if (middle_down || (app.canvas.space_pan && ctx.input(|i| i.pointer.primary_down()))) && resp.hovered() || app.canvas.middle_pan.is_some() { - if let Ok(ds) = app.session.ds_mut() { - match app.canvas.middle_pan { - None => app.canvas.middle_pan = Some((pos, ds.view.cx, ds.view.cy)), - Some((p0, cx, cy)) => { - let z = ds.view.zoom.max(1e-6); - ds.view.cx = cx - f64::from(pos.x - p0.x) / z; - ds.view.cy = cy - f64::from(pos.y - p0.y) / z; - ds.revision += 1; - } - } - } - if !middle_down && !ctx.input(|i| i.pointer.primary_down()) { - app.canvas.middle_pan = None; - } + pan_view(app, &ctx, pos, &mods, middle_down); return true; } // A handle drag whose button went up ends first, wherever on the canvas the pointer is: over a diff --git a/crates/ui-egui/tests/it/canvas_pan_release.rs b/crates/ui-egui/tests/it/canvas_pan_release.rs index 07b0643b8..de5b409b1 100644 --- a/crates/ui-egui/tests/it/canvas_pan_release.rs +++ b/crates/ui-egui/tests/it/canvas_pan_release.rs @@ -109,3 +109,25 @@ fn side_buttons_pan_like_the_middle_button() { check_button(b, false, true); } } + +/// A primary drag under way when a pan starts (a side or the middle button pressed mid-drag) ends +/// when the primary button is let go during the pan: the engine gets the release, so its gesture +/// isn't left open once the pan is over. +#[test] +fn a_primary_drag_released_during_a_pan_ends() { + for pan in [PointerButton::Middle, PointerButton::Extra1] { + let mut u = Frames::new(); + let rect = u.app.canvas.rect; + let start = Pos2::new(rect.min.x + 200.0, rect.center().y); + let moved = Pos2::new(rect.min.x + 400.0, rect.center().y); + u.frame(vec![Event::PointerMoved(start)]); + u.frame(vec![button(start, PointerButton::Primary, true)]); + u.frame(vec![Event::PointerMoved(moved)]); + assert!(u.app.session.tool.busy(), "{pan:?}: a primary drag is under way"); + u.frame(vec![button(moved, pan, true)]); + u.frame(vec![button(moved, PointerButton::Primary, false)]); + u.frame(vec![button(moved, pan, false)]); + u.frame(vec![]); + assert!(!u.app.session.tool.busy(), "{pan:?}: the primary release reached the engine"); + } +} From 853e8c6cc437e8ebe0c336f4621815e7396a8714 Mon Sep 17 00:00:00 2001 From: Filip Strajnar Date: Fri, 6 Nov 2026 12:27:59 +0100 Subject: [PATCH 091/102] M8: a minimised window under Wayland answers control requests (#1906) Under Wayland an app can't tell that its window is minimised (no `minimized`, no `occluded`), and the compositor stops asking it to draw. eframe keeps running the app's logic for a window whose redraw is overdue, but `control::background` still left every request for "the window's frame", which never came: with the window minimised on GNOME or KDE Plasma each control-channel or attached-MCP request waited and timed out after 60 s ("it was not applied"). `control::background` now treats a window that drew no frame for `NOT_DRAWING_AFTER` (0.2 s) while a request waited for it as hidden: requests that act on the app's state are answered from the logic passes, as they are for a window the platform reports minimised. `FigApp::control_waits` keeps, per window, its pass count and the time the wait began; a frame drawn since starts the wait again, and a pass is asked for 0.2 s later while a request waits. Screenshots and `ui.input` still wait for a drawn frame. Measured on GNOME Wayland with the window minimised by its own button: 0.54 s a request (before: 13.7 s for one, then 60 s timeouts). Test: `idle_tests::a_window_that_stopped_drawing_answers_from_its_logic_passes`. Docs: control-protocol.md, mcp.md, hardware-parity.md, target-app-parity.md, ROADMAP.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LvG6E2LxvJ6MuFmiLA6Zqm --- ROADMAP.md | 3 +- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/control.rs | 28 ++++++++++++++++++- crates/ui-egui/src/idle_tests.rs | 47 ++++++++++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 3 ++ docs/control-protocol.md | 6 ++-- docs/hardware-parity.md | 5 ++-- docs/mcp.md | 3 +- docs/target-app-parity.md | 5 ++-- 9 files changed, 92 insertions(+), 9 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 60f5962d2..60ab41a98 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** patch (under Wayland a minimised window answers control and MCP requests in about half a second instead of timing out after 60 s (#1906); glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -358,6 +358,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-06 | patch | M8, #1906: under Wayland a minimised window answers control-channel and attached-MCP requests from its logic passes once it has drawn nothing for 0.2 s while a request waits (about half a second each; every request timed out after 60 s before). Test: `idle_tests::a_window_that_stopped_drawing_answers_from_its_logic_passes`. 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 | | 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 and 0.6 as much on the opposite side, with a faint gradient across the curve, 5% darker facing the light and lighter opposite (it was a glow mixed towards white, as deep as `splay` made it). `splay` turns the bend from along the edge's normal towards the way away from the layer's centre, as the reference tool's does, and no longer widens the light: files with a splay above 0 look different. The direction to the centre is worked out in the shape's own frame, so cut renders match. 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`. Numbers unchanged | diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index e13acce68..279f76897 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -37,6 +37,7 @@ impl FigApp { field_focus: false, panels_unsaved: false, control_queue: Vec::new(), + control_waits: Default::default(), control_input: Vec::new(), frame_stats: frame_stats::FrameStats::default(), windows: windows::Windows::default(), diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 322d9032c..2310f48e2 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -454,6 +454,24 @@ fn hidden(ctx: &Context, id: u64) -> bool { visibility(ctx, id) == Some(false) } +/// How long, in seconds, a window may draw no frame while a control request waits for it before +/// [`background`] answers the request as it answers one for a hidden window. eframe runs the app's +/// logic for a window whose redraw is 0.25 s overdue, so the second such pass answers. +pub const NOT_DRAWING_AFTER: f64 = 0.2; + +/// Whether window `id` has drawn no frame for [`NOT_DRAWING_AFTER`] while a request waited for it. +/// The platform may still call it visible: under Wayland an app can't tell that its window is +/// minimised, and the compositor then stops asking it to draw. The wait starts again whenever the +/// window draws. +fn stopped_drawing(app: &mut FigApp, ctx: &Context, id: u64, now: f64) -> bool { + let pass = ctx.cumulative_pass_nr_for(crate::windows::viewport(id)); + let wait = app.control_waits.entry(id).or_insert((pass, now)); + if wait.0 != pass { + *wait = (pass, now); + } + now - wait.1 >= NOT_DRAWING_AFTER +} + /// Send `RequestPaintWhileHidden` for work that needs a real UI pass (a queued capture or /// synthetic input), and schedule a wakeup for the next capture deadline. Native eframe honours /// this command; the shared web runner does not implement it yet, so a hidden browser tab remains @@ -511,7 +529,7 @@ pub fn background(app: &mut FigApp, ctx: &Context) { let _ = r.reply.send(ControlReply { id: r.id, result: Err(format!("no window {target}")) }); continue; } - let is_hidden = hidden(ctx, target); + let is_hidden = hidden(ctx, target) || stopped_drawing(app, ctx, target, now); if r.method == "ui.screenshot" && visibility(ctx, target) != Some(true) { // Hidden, minimised, or with visibility the platform has not reported: admit it now // so the request gets its deadline and a forced paint. Waiting for a frame that may @@ -564,6 +582,14 @@ pub fn background(app: &mut FigApp, ctx: &Context) { } let _ = r.reply.send(ControlReply { id: r.id, result: res.unwrap_or_else(|| Err(format!("no window {target}"))) }); } + // A window a request still waits for is checked again soon: if it draws, its frame answers; + // if it doesn't (minimised under Wayland), the next logic pass does. + let waiting: std::collections::BTreeSet = + app.control_queue.iter().map(|r| r.params.get("window").and_then(Value::as_u64).unwrap_or(app.windows.focused)).collect(); + app.control_waits.retain(|id, _| waiting.contains(id)); + if !waiting.is_empty() { + crate::repaint_in(ctx, NOT_DRAWING_AFTER); + } request_paint(app, ctx); } diff --git a/crates/ui-egui/src/idle_tests.rs b/crates/ui-egui/src/idle_tests.rs index ae34ded78..ad547b7cc 100644 --- a/crates/ui-egui/src/idle_tests.rs +++ b/crates/ui-egui/src/idle_tests.rs @@ -434,6 +434,53 @@ fn a_hidden_window_answers_at_once() { let _ = std::fs::remove_dir_all(&dir); } +/// #1906: under Wayland a minimised window still reports itself visible (no `minimized`, no +/// `occluded`) and draws no frames; eframe runs only its logic. A request waiting for that +/// window's frame is answered from the logic passes once the window has drawn nothing for +/// [`crate::control::NOT_DRAWING_AFTER`], instead of timing out after 60 s. A window that draws +/// keeps answering from its frame. +#[test] +fn a_window_that_stopped_drawing_answers_from_its_logic_passes() { + let (mut h, text) = document(); + h.settle(); + h.time += 120.0; + h.app.clock.set_test_now(Some(h.time)); + let (tx, rx) = std::sync::mpsc::channel(); + let rename = |id: u64, name: &str| ControlRequest { + id: json!(id), + method: "engine.execute".into(), + params: json!({"command": "node.set", "params": {"ids": [text.clone()], "props": {"name": name}}}), + reply: tx.clone(), + state: Default::default(), + }; + let node = figcraft_doc::NodeId(text.as_u64().unwrap()); + let name = |h: &Harness| h.app.session.doc().unwrap().node(node).unwrap().name.clone(); + // What Wayland reports for a minimised window: nothing about its visibility. + let unknown = RawInput::default(); + let ctx = h.ctx.clone(); + h.app.control_queue.push(rename(1, "while minimised")); + let _ = ctx.run_logic(&unknown, |ctx| crate::control::background(&mut h.app, ctx)); + assert!(rx.try_recv().is_err(), "a window that may still draw answers from its frame"); + assert_eq!(h.app.control_queue.len(), 1); + // No frame comes: the next logic pass answers. + h.app.clock.set_test_now(Some(h.time + crate::control::NOT_DRAWING_AFTER + 0.05)); + let _ = ctx.run_logic(&unknown, |ctx| crate::control::background(&mut h.app, ctx)); + let reply = rx.try_recv().expect("answered while the window draws nothing"); + assert_eq!(reply.id, json!(1)); + assert!(reply.result.is_ok(), "{:?}", reply.result); + assert_eq!(name(&h), "while minimised"); + assert!(h.app.control_queue.is_empty(), "nothing waits for the window"); + // Back on screen: a frame drawn after the wait began starts it again, and the frame answers. + h.time += 1.0; + h.app.clock.set_test_now(Some(h.time)); + h.app.control_queue.push(rename(2, "on screen")); + let _ = ctx.run_logic(&unknown, |ctx| crate::control::background(&mut h.app, ctx)); + h.app.clock.set_test_now(Some(h.time + crate::control::NOT_DRAWING_AFTER + 0.05)); + h.frame(vec![]); + let reply = rx.try_recv().expect("the frame answers"); + assert_eq!((reply.id, name(&h)), (json!(2), "on screen".to_string())); +} + #[test] fn auto_save_writes_a_changed_file_then_rests() { let dir = std::env::temp_dir().join(format!("figcraft-auto-save-{}", std::process::id())); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a7397cee4..76d1b10a1 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -750,6 +750,9 @@ pub struct FigApp { panels_unsaved: bool, /// Control-channel requests waiting for the next frame. pub control_queue: Vec, + /// Windows a control request waits for: the window's pass count when the wait began and the + /// app-clock time it began, to tell a window that stopped drawing ([`control::background`]). + control_waits: std::collections::BTreeMap, /// Input events from the control channel (`ui.input`) for the next frame's raw input. pub control_input: Vec, /// Frames drawn and what asked for them (`ui.inspect`). diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 82ba08bd1..6a2cbe00f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -59,8 +59,10 @@ queue. A screenshot settles on three completed, presented UI frames (a discarded not count), then is issued, and expires once at its 60 s deadline if no paint arrives. `window.new` remains an error at once (`window 0 is minimised or hidden: …`) instead of waiting for the window to show; `ui.render` draws the document without it. Under Wayland the app can't tell that its -window is minimised: where the compositor then stops drawing it, a request waits for the window -and gets the 60 s timeout error. The browser's shared eframe runner does not implement +window is minimised, and the compositor stops asking it to draw: a window that draws no frame for +0.2 s while a request waits for it is treated as hidden, so the requests that act on the app's +state are answered without a frame (about half a second each), while `ui.screenshot` and +`ui.input` keep waiting for one. The browser's shared eframe runner does not implement `RequestPaintWhileHidden` yet, so hidden-tab screenshots and injected input are unqualified there. Coordinates are page units, y down. `x`/`y` in `node.set`/`node.create` are relative to the parent diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index eb8ac2e77..1d64bc411 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,6 +1,6 @@ # Hardware and platform parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (images copied in other apps paste in the browser (#492); text reads only the fallback fonts it draws with; `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); a batch keeps one undo snapshot, not one per step (#1099); one depth cap bounds a whole render, pattern sources included, and render threads get 8 MiB stacks (#1082); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); macOS: the Quit menu and ⌘Q ask about unsaved changes (#857); egui/eframe 0.37 dependency migration; hidden-window screenshot deadlines; zoom previews; hidden windows answer control requests; macOS file opening, the Windows start-up message, Linux packaging; copy and paste in the browser; Windows QA pass; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; pen pressure for the Pencil and brushes on Windows and from browser styluses; macOS: quitting ends the process once everything is kept, avoiding the Touch Bar teardown crash (#781); Linux and BSD clipboard: images under Wayland, reads time out; minimised windows under Wayland; window controls on Wayland without server decorations; canvas textures on device pixels) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** patch (under Wayland a minimised window answers control and MCP requests in about half a second instead of timing out after 60 s (#1906); images copied in other apps paste in the browser (#492); text reads only the fallback fonts it draws with; `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); a batch keeps one undo snapshot, not one per step (#1099); one depth cap bounds a whole render, pattern sources included, and render threads get 8 MiB stacks (#1082); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); macOS: the Quit menu and ⌘Q ask about unsaved changes (#857); egui/eframe 0.37 dependency migration; hidden-window screenshot deadlines; zoom previews; hidden windows answer control requests; macOS file opening, the Windows start-up message, Linux packaging; copy and paste in the browser; Windows QA pass; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; pen pressure for the Pencil and brushes on Windows and from browser styluses; macOS: quitting ends the process once everything is kept, avoiding the Touch Bar teardown crash (#781); Linux and BSD clipboard: images under Wayland, reads time out; minimised windows under Wayland; window controls on Wayland without server decorations; canvas textures on device pixels) · **Target:** Figma Design (desktop app 126.10.7) How FigCraft uses hardware and which platforms it runs on, against Figma. Figma's desktop app is Electron with a GPU helper process; its canvas renders on the GPU (WebGL, with WebGPU rolling out @@ -41,7 +41,7 @@ Nothing has been timed against Figma on the same document (needs `.fig` import). |---|---|---|---| | macOS | desktop app (Intel and Apple silicon) | universal `.dmg`, signed and notarized (v0.2.0) | where nearly all QA happens. Quitting ends the process once the preferences, recovery copies and live sessions are taken care of: the window's teardown crashed on Macs with a Touch Bar (#781); the Quit menu and ⌘Q ask about unsaved changes like the main window's close button (#857), and like it close the main window only: with several windows open, each quit closes one; a quit that never asked — killed or crashed — still leaves recovery copies for the next start | | Windows x64 / arm64 | desktop app | `.msi` and portable zip for x64, x86 and arm64 | built in CI; Windows: QA pass done 2026-10-11, findings in PR. The portable zip keeps its settings in `config\` beside `figcraft.exe` (a `portable` file there), taking an installed copy's preferences on its first start (#1320). Draws with Direct3D 12 (FXC shaders) or OpenGL; when the graphics fail before the first frame it starts again on Vulkan, then OpenGL, then the power-saving GPU with lower limits (#965) | -| Linux | none (browser only) | AppImage, `.deb`, `.rpm`, Flatpak, tarball, x86_64 and aarch64; riscv64 tarball | CI tests run here. Clipboard (also the BSDs): reads run on a helper thread that gives up after 2 s, and images copied in other apps paste under Wayland through the data-control protocol (#693). Under Wayland the app can't tell its window is minimised, so control requests that need a drawn frame may still wait there (#720). None of this run on a Linux desktop here. On a Wayland compositor without server-side decorations (GNOME) the window gets winit's Adwaita controls (#592: checked by its author in a GNOME Wayland session; KDE not run) | +| Linux | none (browser only) | AppImage, `.deb`, `.rpm`, Flatpak, tarball, x86_64 and aarch64; riscv64 tarball | CI tests run here. Clipboard (also the BSDs): reads run on a helper thread that gives up after 2 s, and images copied in other apps paste under Wayland through the data-control protocol (#693). Under Wayland the app can't tell its window is minimised: a window that draws nothing for 0.2 s while a control request waits for it answers the request as a hidden window does (about half a second each, #1906), and only requests that need a drawn frame (screenshots, input) wait there (#720). None of this run on a Linux desktop here. On a Wayland compositor without server-side decorations (GNOME) the window gets winit's Adwaita controls (#592: checked by its author in a GNOME Wayland session; KDE not run) | | FreeBSD | none | tarball | | | Web | primary (figma.com) | `figcraft-web` (WASM, WebGPU/WebGL2), web zip | no accessibility tree; file access through the browser; copy and paste through the system clipboard (copies written from the copy event, pastes read from the paste event, its text or an image copied in another app); an internal error stops the page (a panic can't be caught there), but its unsaved files are kept in the page's local storage (about 5 MB) and open again on reload (#1123) | | iOS / Android | apps: view, comment, mirror prototypes | none (the web build is not touch-first) | 20–40 h for a viewer | @@ -50,6 +50,7 @@ Nothing has been timed against Figma on the same document (needs `.fig` import). | Date | Change | Summary | |---|---|---| +| 2026-11-06 | patch | M8, #1906: under Wayland (seen on GNOME and KDE Plasma) a minimised FigCraft window still reports itself visible and the compositor stops asking it to draw, so every control or attached-MCP request waited for a frame and timed out after 60 s ("it was not applied"), though eframe kept running the app's logic. `control::background` now treats a window that drew no frame for `NOT_DRAWING_AFTER` (0.2 s) while a request waited for it as hidden: state-only requests are answered from the logic passes (0.54 s each, measured on GNOME Wayland; they took 13.7 s or timed out before), the wait starts again when the window draws, and screenshots and `ui.input` still wait for a frame. Test: `idle_tests::a_window_that_stopped_drawing_answers_from_its_logic_passes` | | 2026-10-31 | minor | M1, #492: Web row: the browser pastes images copied in other apps, read from the paste event under the same limits as the desktop. Numbers unchanged. | | 2026-10-30 | minor | M8: text reads only the fallback fonts it draws with. Each fallback family reads the face nearest a run's style, not all of them (Noto Sans CJK is seven files of 16–20 MB); families naming the faces of one file share its bytes; and the faces are worked out once per style until fonts change, not for every text laid out. First text laid out on a Linux machine with Noto Sans CJK, DejaVu Sans and Inter: 41 files (265 MiB, kept in memory) and 41 faces parsed → 3 files (20 MiB) and 4 faces; fallback lookups per text laid out ~45 µs → 0.2 µs. Tests: `fontdb_fallback_tests`. Numbers unchanged | | 2026-10-30 | minor | M8, #1117: AI agents and plugins no longer learn where the open files are on disk from `doc.list`. Numbers unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index b5e49e749..0530d0370 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -42,7 +42,8 @@ replaced then, so a pause between calls is not an error. The app keeps answering while its window is minimised or covered by other windows (see `docs/control-protocol.md`): edits, inspection (`inspect_ui` too), pointer, key and text input and -renders work as usual (minimised, each request to the app takes up to about 0.1 s). Only a capture +renders work as usual (minimised, each request to the app takes up to about 0.1 s; under Wayland, +which can't report a minimised window, about half a second). Only a capture of the window itself (`screenshot` with `window`) needs it on screen: it is then an error at once; `screenshot` without `window` renders the document instead. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5d910dabf..7a535ff77 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -642,8 +642,9 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th `figcraft-cli mcp` and the desktop app, #715). A minimised or covered window answers every request that acts on the app's state without drawing (about 100 ms each on Windows), and the ones that need a drawn frame (`ui.screenshot`, `ui.input`, `window.new`) fail at once instead of - waiting 60 s (#720; not tested on macOS, and under Wayland a minimised window can't be told - apart). + waiting 60 s (#720; not tested on macOS). Under Wayland a minimised window can't be told apart, + so a window that draws nothing for 0.2 s while a request waits is answered as a hidden one + (about half a second a request, #1906). - **Tests:** 963 `#[test]` functions (2026-10-10) including junk-parameter sweeps over every command (and every vector-edit command while editing), importer fuzzing and render regressions. ## Revision history From 98710acb801b7c4a8b08ea7b670ffc46d4cc36bb Mon Sep 17 00:00:00 2001 From: Filip Strajnar Date: Fri, 6 Nov 2026 12:39:39 +0100 Subject: [PATCH 092/102] M7: closing a tab with unsaved changes asks Don't Save / Cancel / Save (#2032) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closing a tab whose file has unsaved changes, by its X, a middle click, File ▸ Close tab or its shortcut, only showed a toast ("save first, or close again with Alt to discard"; from the menu "close the tab with Alt-click") and left the tab open, so closing a tab seemed not to work. A `file.close` refused for unsaved changes asked the UI with `dialog.unsaved`, which toasted too. Closing such a tab now asks the unsaved-changes question the window asks when it closes (`windows::unsaved_question`, shared): Don't Save closes the tab and drops the changes, Cancel or Escape keeps it, Save saves the file next frame and then closes the tab. A file without a path, or saved as .fig, asks where with Save as first; the tab closes once that saved it and stays open if it is cancelled or fails. `UiState::close_tab` (`windows::TabClose`: Ask, Save, AfterSaveAs) keeps where it is; `ask_close_tab` starts it for the tab strip, the menu and `dialog.unsaved`. Alt+close still drops the changes without asking. The three toasts are gone from the code and the catalogs. Reordering tabs by dragging, the issue's other half, already works on main (landed 2026-10-19, `dragging_a_tab_along_the_bar_reorders_it_without_detaching`). Tests: `titlebar_tests::closing_a_tab_with_unsaved_changes_asks` (the X asks, Escape keeps the tab, Don't Save closes it, Alt+click closes without asking, File ▸ Close tab asks), `titlebar_tests::save_in_the_tab_question_saves_then_closes` (Enter saves then closes; no path: the tab stays). The title bar test harness can hold modifier keys. Docs: ui-parity.md, ROADMAP.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LvG6E2LxvJ6MuFmiLA6Zqm --- ROADMAP.md | 3 +- crates/ui-egui/locales/ar.toml | 3 - crates/ui-egui/locales/bn.toml | 3 - crates/ui-egui/locales/bs.toml | 3 - crates/ui-egui/locales/cs.toml | 3 - crates/ui-egui/locales/de.toml | 3 - crates/ui-egui/locales/en.toml | 3 - crates/ui-egui/locales/es.toml | 3 - crates/ui-egui/locales/fi.toml | 3 - crates/ui-egui/locales/fr.toml | 3 - crates/ui-egui/locales/id.toml | 3 - crates/ui-egui/locales/it.toml | 3 - crates/ui-egui/locales/ja.toml | 3 - crates/ui-egui/locales/ka.toml | 3 - crates/ui-egui/locales/ko.toml | 3 - crates/ui-egui/locales/nl.toml | 3 - crates/ui-egui/locales/pl.toml | 3 - crates/ui-egui/locales/pt-BR.toml | 3 - crates/ui-egui/locales/ru.toml | 3 - crates/ui-egui/locales/sv.toml | 3 - crates/ui-egui/locales/th.toml | 3 - crates/ui-egui/locales/tr.toml | 3 - crates/ui-egui/locales/vi.toml | 3 - crates/ui-egui/locales/zh-Hans.toml | 3 - crates/ui-egui/src/app/commands.rs | 12 ++- crates/ui-egui/src/dialogs.rs | 6 ++ crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/menus.rs | 6 +- crates/ui-egui/src/tabs.rs | 13 ++- crates/ui-egui/src/titlebar_tests.rs | 111 ++++++++++++++++++++++++- crates/ui-egui/src/windows.rs | 119 ++++++++++++++++++++++++++- docs/ui-parity.md | 5 +- 32 files changed, 255 insertions(+), 92 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 60f5962d2..917f0fb24 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** patch (closing a tab whose file has unsaved changes (its X, a middle click, File ▸ Close tab) asks Don't Save / Cancel / Save as closing the window does, instead of a toast that left it open (#2032); glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -358,6 +358,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-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 | | 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 and 0.6 as much on the opposite side, with a faint gradient across the curve, 5% darker facing the light and lighter opposite (it was a glow mixed towards white, as deep as `splay` made it). `splay` turns the bend from along the edge's normal towards the way away from the layer's centre, as the reference tool's does, and no longer widens the light: files with a splay above 0 look different. The direction to the centre is worked out in the shape's own frame, so cut renders match. 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`. Numbers unchanged | diff --git a/crates/ui-egui/locales/ar.toml b/crates/ui-egui/locales/ar.toml index a3dcf0844..da4474e79 100644 --- a/crates/ui-egui/locales/ar.toml +++ b/crates/ui-egui/locales/ar.toml @@ -1520,7 +1520,6 @@ status = "draft — needs native review" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "تحتفظ هذه الصفحة برمز المالك ما دامت مفتوحة فقط. انسخه لإدارة الملف لاحقًا؛ فهو كلمة مرور لهذا الملف ولن يُعرض مجددًا." "This condition is edited as an expression" = "يُحرر هذا الشرط كتعبير" "This file" = "هذا الملف" -"This file has unsaved changes" = "يحتوي هذا الملف على تغييرات غير محفوظة" "This file is too large to join here (up to {mb} MB)" = "هذا الملف أكبر من أن يمكن الانضمام إليه هنا (الحد {mb} ميغابايت)" "This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "يستخدم هذا الملف خطوطًا غير مثبتة على هذا الحاسوب. يُعرض نصها بخط بديل حتى تثبتها." "This file is on {server}, open only to you. Share it to let others in with a new code." = "هذا الملف على {server} ومتاح لك وحدك. شاركه ليتمكن الآخرون من الانضمام برمز جديد." @@ -1580,8 +1579,6 @@ status = "draft — needs native review" "Unresolve" = "إعادة فتح" "Unsaved changes" = "تغييرات غير محفوظة" "Unsaved changes in {names}. Save them before closing?" = "تغييرات غير محفوظة في {names}. هل تريد حفظها قبل الإغلاق؟" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "تغييرات غير محفوظة: احفظ أولًا ({save})، أو أغلق علامة التبويب بالنقر مع {alt} لتجاهلها" -"Unsaved changes: save first, or close again with {key} to discard" = "تغييرات غير محفوظة: احفظ أولًا، أو أغلق مجددًا مع {key} لتجاهلها" "Up" = "لأعلى" "Update check is not supported in the web browser." = "التحقق من التحديثات غير مدعوم في المتصفح." "Update plugin" = "تحديث الإضافة" diff --git a/crates/ui-egui/locales/bn.toml b/crates/ui-egui/locales/bn.toml index 32d66721f..5d01928bf 100644 --- a/crates/ui-egui/locales/bn.toml +++ b/crates/ui-egui/locales/bn.toml @@ -1476,7 +1476,6 @@ status = "draft — needs native review" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "এই পেজটি খোলা থাকা পর্যন্তই ওনার টোকেন রাখে। পরে ফাইলটি পরিচালনা করতে এটি কপি করুন: এটি এই ফাইলের জন্য একটি পাসওয়ার্ড এবং আর কখনো দেখানো হবে না।" "This condition is edited as an expression" = "এই শর্তটি এক্সপ্রেশন হিসেবে এডিট করা হয়েছে" "This file" = "এই ফাইল" -"This file has unsaved changes" = "এই ফাইলে সেভ করা হয়নি এমন পরিবর্তন রয়েছে" "This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "এই ফাইলে এমন ফন্ট ব্যবহার করা হয়েছে যা এই কম্পিউটারে ইনস্টল করা নেই। আপনি ইনস্টল না করা পর্যন্ত সেগুলোর টেক্সট একটি ফলব্যাক ফন্টে দেখানো হয়।" "This file is on {server}, open only to you. Share it to let others in with a new code." = "এই ফাইলটি {server}-এ আছে, শুধুমাত্র আপনার জন্য খোলা। নতুন কোড দিয়ে অন্যদের প্রবেশ করাতে এটি শেয়ার করুন।" "This frame is new on the branch." = "এই ফ্রেমটি ব্রাঞ্চে নতুন।" @@ -1531,8 +1530,6 @@ status = "draft — needs native review" "Unresolve" = "অমীমাংসিত করুন" "Unsaved changes" = "সংরক্ষিত হয়নি এমন পরিবর্তন" "Unsaved changes in {names}. Save them before closing?" = "{names}-এ সংরক্ষিত হয়নি এমন পরিবর্তন রয়েছে। বন্ধ করার আগে সেগুলো সংরক্ষণ করবেন?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "সংরক্ষিত হয়নি এমন পরিবর্তন: প্রথমে সেভ করুন ({save}), অথবা বাতিল করতে {alt}-ক্লিক করে ট্যাব বন্ধ করুন" -"Unsaved changes: save first, or close again with {key} to discard" = "সংরক্ষিত হয়নি এমন পরিবর্তন: প্রথমে সেভ করুন, অথবা বাতিল করতে {key} দিয়ে আবার বন্ধ করুন" "Up" = "উপরে" "Update plugin" = "প্লাগইন আপডেট করুন" "Update" = "আপডেট" diff --git a/crates/ui-egui/locales/bs.toml b/crates/ui-egui/locales/bs.toml index 72f0268bd..36d71664c 100644 --- a/crates/ui-egui/locales/bs.toml +++ b/crates/ui-egui/locales/bs.toml @@ -1533,7 +1533,6 @@ status = "draft — needs native review" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "Ova stranica čuva token vlasnika samo dok je otvorena. Kopirajte ga da kasnije upravljate datotekom: to je lozinka za ovu datoteku i neće se ponovo prikazati." "This condition is edited as an expression" = "Ovaj uslov se uređuje kao izraz" "This file" = "Ova datoteka" -"This file has unsaved changes" = "Ova datoteka ima nesačuvane promjene" "This file is too large to join here (up to {mb} MB)" = "Ova datoteka je prevelika za pridruživanje ovdje (do {mb} MB)" "This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "Ova datoteka koristi fontove koji nisu instalirani na ovom računaru. Njihov tekst se iscrtava rezervnim fontom dok ih ne instalirate." "This file is on {server}, open only to you. Share it to let others in with a new code." = "Ova datoteka je na serveru {server}, otvorena samo Vama. Podijelite je da drugi uđu s novim kodom." @@ -1594,8 +1593,6 @@ status = "draft — needs native review" "Unresolve" = "Poništi rješenje" "Unsaved changes" = "Nesačuvane promjene" "Unsaved changes in {names}. Save them before closing?" = "Nesačuvane promjene u: {names}. Sačuvati ih prije zatvaranja?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "Nesačuvane promjene: prvo sačuvajte ({save}) ili zatvorite karticu uz {alt}-klik da ih odbacite" -"Unsaved changes: save first, or close again with {key} to discard" = "Nesačuvane promjene: prvo sačuvajte ili ponovo zatvorite s {key} da ih odbacite" "Up" = "Gore" "Update check is not supported in the web browser." = "Provjera ažuriranja nije podržana u web pregledniku." "Update plugin" = "Ažuriraj dodatak" diff --git a/crates/ui-egui/locales/cs.toml b/crates/ui-egui/locales/cs.toml index 16de8065a..d401654ac 100644 --- a/crates/ui-egui/locales/cs.toml +++ b/crates/ui-egui/locales/cs.toml @@ -1448,7 +1448,6 @@ status = "draft — needs native review" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "Tato stránka si token vlastníka pamatuje, jen dokud je otevřená. Zkopírujte ho pro pozdější správu souboru: je to heslo k tomuto souboru a znovu se nezobrazí." "This condition is edited as an expression" = "Tato podmínka se upravuje jako výraz" "This file" = "Tento soubor" -"This file has unsaved changes" = "Tento soubor obsahuje neuložené změny" "This file is on {server}, open only to you. Share it to let others in with a new code." = "Tento soubor je na serveru {server}, přístupný pouze vám. Sdílením umožníte ostatním připojení pomocí nového kódu." "This frame is new on the branch." = "Tento rámec je ve větvi nový." "This frame isn't on the branch." = "Tento rámec není ve větvi." @@ -1501,8 +1500,6 @@ status = "draft — needs native review" "Unresolve" = "Znovu otevřít" "Unsaved changes" = "Neuložené změny" "Unsaved changes in {names}. Save them before closing?" = "Neuložené změny v {names}. Uložit je před zavřením?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "Neuložené změny: nejprve uložte ({save}) nebo zavřete kartu kliknutím s {alt} a zahoďte je" -"Unsaved changes: save first, or close again with {key} to discard" = "Neuložené změny: nejprve uložte nebo zavřete znovu s {key} a zahoďte je" "Up" = "Nahoru" "Update plugin" = "Aktualizovat plugin" "Update" = "Aktualizovat" diff --git a/crates/ui-egui/locales/de.toml b/crates/ui-egui/locales/de.toml index 344e70912..b6f55f821 100644 --- a/crates/ui-egui/locales/de.toml +++ b/crates/ui-egui/locales/de.toml @@ -1416,7 +1416,6 @@ status = "draft — needs native review" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "Diese Seite behält das Eigentümer-Token nur, solange sie geöffnet ist. Kopieren Sie es, um die Datei später zu verwalten: Es ist ein Passwort für diese Datei und wird nicht noch einmal angezeigt." "This condition is edited as an expression" = "Diese Bedingung wird als Ausdruck bearbeitet" "This file" = "Diese Datei" -"This file has unsaved changes" = "Diese Datei hat nicht gespeicherte Änderungen" "This file is on {server}, open only to you. Share it to let others in with a new code." = "Diese Datei liegt auf {server} und ist nur für Sie zugänglich. Teilen Sie sie, um andere mit einem neuen Code hereinzulassen." "This frame is new on the branch." = "Dieser Rahmen ist im Branch neu." "This frame isn't on the branch." = "Dieser Rahmen ist nicht im Branch." @@ -1469,8 +1468,6 @@ status = "draft — needs native review" "Unresolve" = "Wieder öffnen" "Unsaved changes" = "Nicht gespeicherte Änderungen" "Unsaved changes in {names}. Save them before closing?" = "Nicht gespeicherte Änderungen in {names}. Vor dem Schließen speichern?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "Nicht gespeicherte Änderungen: Speichern Sie zuerst ({save}) oder schließen Sie den Tab mit {alt}+Klick, um sie zu verwerfen" -"Unsaved changes: save first, or close again with {key} to discard" = "Nicht gespeicherte Änderungen: Speichern Sie zuerst oder schließen Sie erneut mit {key}, um sie zu verwerfen" "Up" = "Nach oben" "Update" = "Aktualisieren" "Update from main" = "Aus Hauptdatei aktualisieren" diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 11f0bb4ac..fbce00adf 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -1573,7 +1573,6 @@ name = "English" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." "This condition is edited as an expression" = "This condition is edited as an expression" "This file" = "This file" -"This file has unsaved changes" = "This file has unsaved changes" "This file is too large to join here (up to {mb} MB)" = "This file is too large to join here (up to {mb} MB)" "This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." "This file is on {server}, open only to you. Share it to let others in with a new code." = "This file is on {server}, open only to you. Share it to let others in with a new code." @@ -1635,8 +1634,6 @@ name = "English" "Unresolve" = "Unresolve" "Unsaved changes" = "Unsaved changes" "Unsaved changes in {names}. Save them before closing?" = "Unsaved changes in {names}. Save them before closing?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" -"Unsaved changes: save first, or close again with {key} to discard" = "Unsaved changes: save first, or close again with {key} to discard" "Up" = "Up" "Update check is not supported in the web browser." = "Update check is not supported in the web browser." "Update plugin" = "Update plugin" diff --git a/crates/ui-egui/locales/es.toml b/crates/ui-egui/locales/es.toml index b9e004dd0..e6e8ecd7f 100644 --- a/crates/ui-egui/locales/es.toml +++ b/crates/ui-egui/locales/es.toml @@ -1515,7 +1515,6 @@ status = "draft — needs native review" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "Esta página guarda el token de propietario solo mientras está abierta. Cópialo para gestionar el archivo más tarde: es una contraseña para este archivo y no se volverá a mostrar." "This condition is edited as an expression" = "Esta condición se edita como expresión" "This file" = "Este archivo" -"This file has unsaved changes" = "Este archivo tiene cambios sin guardar" "This file is too large to join here (up to {mb} MB)" = "Este archivo es demasiado grande para unirte aquí (hasta {mb} MB)" "This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "Este archivo usa fuentes que no están instaladas en este equipo. Su texto se dibuja con una fuente de reserva hasta que las instales." "This file is on {server}, open only to you. Share it to let others in with a new code." = "Este archivo está en {server}, abierto solo para ti. Compártelo para dejar entrar a otros con un código nuevo." @@ -1573,8 +1572,6 @@ status = "draft — needs native review" "Unresolve" = "Reabrir" "Unsaved changes" = "Cambios sin guardar" "Unsaved changes in {names}. Save them before closing?" = "Hay cambios sin guardar en {names}. ¿Guardarlos antes de cerrar?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "Cambios sin guardar: guarda primero ({save}) o cierra la pestaña con {alt}+clic para descartarlos" -"Unsaved changes: save first, or close again with {key} to discard" = "Cambios sin guardar: guarda primero o vuelve a cerrar con {key} para descartarlos" "Up" = "Arriba" "Update plugin" = "Actualizar plugin" "Update" = "Actualizar" diff --git a/crates/ui-egui/locales/fi.toml b/crates/ui-egui/locales/fi.toml index 0c74f9de7..b3f8cee10 100644 --- a/crates/ui-egui/locales/fi.toml +++ b/crates/ui-egui/locales/fi.toml @@ -1546,7 +1546,6 @@ status = "draft — needs native review" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "Tämä sivu säilyttää omistajan tunnisteen vain niin kauan kuin se on auki. Kopioi tunniste hallitaksesi tiedostoa myöhemmin. Se on tämän tiedoston salasana, eikä sitä näytetä uudelleen." "This condition is edited as an expression" = "Tätä ehtoa muokataan lausekkeena" "This file" = "Tämä tiedosto" -"This file has unsaved changes" = "Tässä tiedostossa on tallentamattomia muutoksia" "This file is too large to join here (up to {mb} MB)" = "Tiedosto on liian suuri liitettäväksi tähän (enintään {mb} Mt)" "This file is on {server}, open only to you. Share it to let others in with a new code." = "Tämä tiedosto on palvelimella {server} vain sinun käytössäsi. Jaa se, jotta muut voivat liittyä uudella koodilla." "This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "Tämä tiedosto käyttää fontteja, joita ei ole asennettu tälle tietokoneelle. Teksti piirretään korvaavalla fontilla, kunnes asennat puuttuvat fontit." @@ -1608,8 +1607,6 @@ status = "draft — needs native review" "Unresolve" = "Merkitse ratkaisemattomaksi" "Unsaved changes" = "Tallentamattomat muutokset" "Unsaved changes in {names}. Save them before closing?" = "Tallentamattomia muutoksia kohteissa {names}. Tallennetaanko ne ennen sulkemista?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "Tallentamattomia muutoksia: tallenna ensin ({save}) tai hylkää sulkemalla välilehti {alt}-napsautuksella" -"Unsaved changes: save first, or close again with {key} to discard" = "Tallentamattomia muutoksia: tallenna ensin tai hylkää sulkemalla uudelleen näppäimellä {key}" "Up" = "Ylös" "Update check is not supported in the web browser." = "Päivitysten tarkistusta ei tueta selaimessa." "Update" = "Päivitä" diff --git a/crates/ui-egui/locales/fr.toml b/crates/ui-egui/locales/fr.toml index b30abe731..d47ad9597 100644 --- a/crates/ui-egui/locales/fr.toml +++ b/crates/ui-egui/locales/fr.toml @@ -1481,7 +1481,6 @@ status = "draft — needs native review" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "Cette page ne garde le jeton de propriétaire que tant qu’elle est ouverte. Copiez-le pour gérer le fichier plus tard : c’est un mot de passe pour ce fichier et il ne sera plus affiché." "This condition is edited as an expression" = "Cette condition se modifie en tant qu’expression" "This file" = "Ce fichier" -"This file has unsaved changes" = "Ce fichier contient des modifications non enregistrées" "This file is on {server}, open only to you. Share it to let others in with a new code." = "Ce fichier est sur {server}, accessible à vous seul. Partagez-le pour laisser entrer d’autres personnes avec un nouveau code." "This frame is new on the branch." = "Ce cadre est nouveau dans la branche." "This frame isn't on the branch." = "Ce cadre n’est pas dans la branche." @@ -1536,8 +1535,6 @@ status = "draft — needs native review" "Unresolve" = "Rouvrir" "Unsaved changes" = "Modifications non enregistrées" "Unsaved changes in {names}. Save them before closing?" = "Modifications non enregistrées dans {names}. Les enregistrer avant de fermer ?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "Modifications non enregistrées : enregistrez d’abord ({save}) ou fermez l’onglet avec {alt}+clic pour les abandonner" -"Unsaved changes: save first, or close again with {key} to discard" = "Modifications non enregistrées : enregistrez d’abord ou fermez à nouveau avec {key} pour les abandonner" "Up" = "Haut" "Update" = "Mettre à jour" "Update from main" = "Mettre à jour depuis le fichier principal" diff --git a/crates/ui-egui/locales/id.toml b/crates/ui-egui/locales/id.toml index da08f159d..cbebaf1c4 100644 --- a/crates/ui-egui/locales/id.toml +++ b/crates/ui-egui/locales/id.toml @@ -1454,7 +1454,6 @@ status = "draft — needs native review" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "Halaman ini hanya menyimpan token pemilik selama halaman terbuka. Salin token untuk mengelola file nanti: token ini adalah kata sandi untuk file ini dan tidak akan ditampilkan lagi." "This condition is edited as an expression" = "Kondisi ini diedit sebagai ekspresi" "This file" = "File ini" -"This file has unsaved changes" = "File ini memiliki perubahan yang belum disimpan" "This file is on {server}, open only to you. Share it to let others in with a new code." = "File ini ada di {server}, hanya dapat dibuka oleh Anda. Bagikan untuk mengizinkan orang lain masuk dengan kode baru." "This frame is new on the branch." = "Frame ini baru di branch." "This frame isn't on the branch." = "Frame ini tidak ada di branch." @@ -1506,8 +1505,6 @@ status = "draft — needs native review" "Unresolve" = "Buka kembali" "Unsaved changes" = "Perubahan belum disimpan" "Unsaved changes in {names}. Save them before closing?" = "Perubahan belum disimpan di {names}. Simpan sebelum menutup?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "Perubahan belum disimpan: simpan dulu ({save}), atau tutup tab dengan {alt}-klik untuk membuangnya" -"Unsaved changes: save first, or close again with {key} to discard" = "Perubahan belum disimpan: simpan dulu, atau tutup lagi dengan {key} untuk membuangnya" "Up" = "Atas" "Update plugin" = "Perbarui plugin" "Update" = "Perbarui" diff --git a/crates/ui-egui/locales/it.toml b/crates/ui-egui/locales/it.toml index 3d2877e7e..364aeedf8 100644 --- a/crates/ui-egui/locales/it.toml +++ b/crates/ui-egui/locales/it.toml @@ -1413,7 +1413,6 @@ status = "draft — needs native review" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "Questa pagina conserva il token del proprietario solo finché resta aperta. Copialo per gestire il file in seguito: è una password per questo file e non verrà mostrato di nuovo." "This condition is edited as an expression" = "Questa condizione viene modificata come espressione" "This file" = "Questo file" -"This file has unsaved changes" = "Questo file ha modifiche non salvate" "This file is too large to join here (up to {mb} MB)" = "Questo file è troppo grande per parteciparvi da qui (fino a {mb} MB)" "This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "Questo file usa font che non sono installati su questo computer. Il loro testo è disegnato con un font di riserva finché non li installi." "This file is on {server}, open only to you. Share it to let others in with a new code." = "Questo file è su {server}, aperto solo a te. Condividilo per far entrare altri con un nuovo codice." @@ -1464,8 +1463,6 @@ status = "draft — needs native review" "Unread" = "Non letto" "Unresolve" = "Riapri" "Unsaved changes" = "Modifiche non salvate" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "Modifiche non salvate: salva prima ({save}), oppure chiudi la scheda con {alt}+clic per scartarle" -"Unsaved changes: save first, or close again with {key} to discard" = "Modifiche non salvate: salva prima, oppure chiudi di nuovo con {key} per scartarle" "Up" = "Su" "Update plugin" = "Aggiorna plugin" "Update" = "Aggiorna" diff --git a/crates/ui-egui/locales/ja.toml b/crates/ui-egui/locales/ja.toml index 8cf2da2d5..5a8918a20 100644 --- a/crates/ui-egui/locales/ja.toml +++ b/crates/ui-egui/locales/ja.toml @@ -1464,7 +1464,6 @@ status = "draft — needs native review" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "このページは開いている間だけ所有者トークンを保持する。後でファイルを管理するにはコピーしておくこと:このファイルのパスワードにあたり、再表示されない。" "This condition is edited as an expression" = "この条件は式として編集されている" "This file" = "このファイル" -"This file has unsaved changes" = "このファイルには未保存の変更がある" "This file is on {server}, open only to you. Share it to let others in with a new code." = "このファイルは {server} にあり、開けるのはあなただけ。共有すると、新しいコードで他の人が参加可能。" "This frame is new on the branch." = "このフレームはブランチで新規作成。" "This frame isn't on the branch." = "このフレームはブランチにない。" @@ -1519,8 +1518,6 @@ status = "draft — needs native review" "Unresolve" = "未解決に戻す" "Unsaved changes" = "未保存の変更" "Unsaved changes in {names}. Save them before closing?" = "{names} に未保存の変更がある。閉じる前に保存する?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "未保存の変更:先に保存する({save})か、{alt}-クリックでタブを閉じて破棄" -"Unsaved changes: save first, or close again with {key} to discard" = "未保存の変更:先に保存するか、もう一度 {key} で閉じて破棄" "Up" = "上" "Update" = "更新" "Update from main" = "メインから更新" diff --git a/crates/ui-egui/locales/ka.toml b/crates/ui-egui/locales/ka.toml index f634a2e7e..ae514a829 100644 --- a/crates/ui-egui/locales/ka.toml +++ b/crates/ui-egui/locales/ka.toml @@ -1495,7 +1495,6 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "ეს გვერდი მფლობელის ტოკენს მხოლოდ მანამ ინახავს, სანამ ღიაა. ფაილის მოგვიანებით სამართავად დააკოპირეთ ის: ეს ამ ფაილის პაროლია და აღარ გამოჩნდება." "This condition is edited as an expression" = "ეს პირობა ექსპრესიად რედაქტირდება" "This file" = "ეს ფაილი" -"This file has unsaved changes" = "ამ ფაილს შეუნახავი ცვლილებები აქვს" "This file is too large to join here (up to {mb} MB)" = "ეს ფაილი აქ შესაერთებლად ძალიან დიდია (მაქსიმუმ {mb} მბ)" "This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "ეს ფაილი იყენებს შრიფტებს, რომლებიც ამ კომპიუტერზე დაინსტალირებული არ არის. მათი ტექსტი სათადარიგო შრიფტით გამოისახება, სანამ მათ არ დააინსტალირებთ." "This file is on {server}, open only to you. Share it to let others in with a new code." = "ეს ფაილი {server}-ზეა და მხოლოდ თქვენთვისაა ღია. გააზიარეთ, რომ სხვები ახალი კოდით შემოუშვათ." @@ -1554,8 +1553,6 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv "Unresolve" = "ხელახლა გახსნა" "Unsaved changes" = "შეუნახავი ცვლილებები" "Unsaved changes in {names}. Save them before closing?" = "შეუნახავი ცვლილებები: {names}. შევინახოთ დახურვამდე?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "შეუნახავი ცვლილებები: ჯერ შეინახეთ ({save}) ან გასაუქმებლად დახურეთ ჩანართი {alt}+დაწკაპუნებით" -"Unsaved changes: save first, or close again with {key} to discard" = "შეუნახავი ცვლილებები: ჯერ შეინახეთ ან გასაუქმებლად ხელახლა დახურეთ {key}-ით" "Up" = "ზემოთ" "Update plugin" = "პლაგინის განახლება" "Update" = "განახლება" diff --git a/crates/ui-egui/locales/ko.toml b/crates/ui-egui/locales/ko.toml index d52310997..ebea678d1 100644 --- a/crates/ui-egui/locales/ko.toml +++ b/crates/ui-egui/locales/ko.toml @@ -1399,7 +1399,6 @@ status = "draft — needs native review" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "이 페이지는 열려 있는 동안에만 소유자 토큰을 보관함. 나중에 파일을 관리하려면 복사해 두세요: 이 파일의 비밀번호와 같으며 다시 표시되지 않음." "This condition is edited as an expression" = "이 조건은 수식으로 편집됨" "This file" = "이 파일" -"This file has unsaved changes" = "이 파일에 저장되지 않은 변경 사항이 있음" "This file is on {server}, open only to you. Share it to let others in with a new code." = "이 파일은 {server}에 있으며 나만 열 수 있음. 공유하면 다른 사람들이 새 코드로 참여할 수 있음." "This frame is new on the branch." = "이 프레임은 브랜치에서 새로 만들어졌음." "This frame isn't on the branch." = "이 프레임은 브랜치에 없음." @@ -1452,8 +1451,6 @@ status = "draft — needs native review" "Unresolve" = "미해결로 되돌리기" "Unsaved changes" = "저장되지 않은 변경 사항" "Unsaved changes in {names}. Save them before closing?" = "{names}에 저장되지 않은 변경 사항이 있음. 닫기 전에 저장할까요?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "저장되지 않은 변경 사항: 먼저 저장({save})하거나 {alt}-클릭으로 탭을 닫아 버리세요" -"Unsaved changes: save first, or close again with {key} to discard" = "저장되지 않은 변경 사항: 먼저 저장하거나 {key}로 다시 닫아 버리세요" "Up" = "위" "Update" = "업데이트" "Update from main" = "메인에서 업데이트" diff --git a/crates/ui-egui/locales/nl.toml b/crates/ui-egui/locales/nl.toml index 070ca4bb4..e43d40b5e 100644 --- a/crates/ui-egui/locales/nl.toml +++ b/crates/ui-egui/locales/nl.toml @@ -1481,7 +1481,6 @@ status = "draft — needs native review" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "Deze pagina bewaart het eigenaartoken alleen zolang ze open is. Kopieer het om het bestand later te beheren: het is het wachtwoord voor dit bestand en wordt niet opnieuw weergegeven." "This condition is edited as an expression" = "Deze voorwaarde wordt als expressie bewerkt" "This file" = "Dit bestand" -"This file has unsaved changes" = "Dit bestand heeft niet-opgeslagen wijzigingen" "This file is on {server}, open only to you. Share it to let others in with a new code." = "Dit bestand staat op {server}, alleen toegankelijk voor jou. Deel het om anderen binnen te laten met een nieuwe code." "This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "Dit bestand gebruikt lettertypen die niet op deze computer zijn geïnstalleerd. Hun tekst wordt in een vervangend lettertype getoond tot je ze installeert." "This frame is new on the branch." = "Dit frame is nieuw op de branch." @@ -1536,8 +1535,6 @@ status = "draft — needs native review" "Unresolve" = "Oplossing ongedaan maken" "Unsaved changes" = "Niet-opgeslagen wijzigingen" "Unsaved changes in {names}. Save them before closing?" = "Niet-opgeslagen wijzigingen in {names}. Opslaan voor het sluiten?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "Niet-opgeslagen wijzigingen: sla eerst op ({save}), of sluit het tabblad met {alt}-klik om ze te verwerpen" -"Unsaved changes: save first, or close again with {key} to discard" = "Niet-opgeslagen wijzigingen: sla eerst op, of sluit nogmaals met {key} om te verwerpen" "Up" = "Omhoog" "Update" = "Bijwerken" "Update from main" = "Bijwerken vanaf main" diff --git a/crates/ui-egui/locales/pl.toml b/crates/ui-egui/locales/pl.toml index 05d9b60f8..68fe136d7 100644 --- a/crates/ui-egui/locales/pl.toml +++ b/crates/ui-egui/locales/pl.toml @@ -1488,7 +1488,6 @@ name = "Polski" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "Ta strona przechowuje token właściciela tylko, dopóki jest otwarta. Skopiuj go, aby zarządzać plikiem później: jest to hasło do tego pliku i nie zostanie ponownie wyświetlone." "This condition is edited as an expression" = "Ten warunek jest edytowany jako wyrażenie" "This file" = "Ten plik" -"This file has unsaved changes" = "Ten plik ma niezapisane zmiany" "This file is too large to join here (up to {mb} MB)" = "Ten plik jest zbyt duży, aby do niego dołączyć (maksymalnie {mb} MB)" "This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "Ten plik używa czcionek, które nie są zainstalowane na tym komputerze. Do czasu ich zainstalowania tekst jest wyświetlany czcionką zastępczą." "This file is on {server}, open only to you. Share it to let others in with a new code." = "Ten plik znajduje się na {server}, otwarty tylko dla Ciebie. Udostępnij go, aby wpuścić innych nowym kodem." @@ -1545,8 +1544,6 @@ name = "Polski" "Unresolve" = "Cofnij rozwiązanie" "Unsaved changes" = "Niezapisane zmiany" "Unsaved changes in {names}. Save them before closing?" = "Niezapisane zmiany w: {names}. Zapisać je przed zamknięciem?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "Niezapisane zmiany: najpierw zapisz ({save}) lub zamknij kartę z {alt}-kliknięciem, aby odrzucić" -"Unsaved changes: save first, or close again with {key} to discard" = "Niezapisane zmiany: najpierw zapisz lub naciśnij ponownie {key}, aby odrzucić" "Up" = "W górę" "Update plugin" = "Zaktualizuj wtyczkę" "Update" = "Aktualizuj" diff --git a/crates/ui-egui/locales/pt-BR.toml b/crates/ui-egui/locales/pt-BR.toml index 1b00ce28c..c2ccba835 100644 --- a/crates/ui-egui/locales/pt-BR.toml +++ b/crates/ui-egui/locales/pt-BR.toml @@ -1397,7 +1397,6 @@ status = "draft — needs native review" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "Esta página guarda o token de proprietário só enquanto estiver aberta. Copie-o para gerenciar o arquivo depois: ele é uma senha para este arquivo e não será mostrado de novo." "This condition is edited as an expression" = "Esta condição é editada como expressão" "This file" = "Este arquivo" -"This file has unsaved changes" = "Este arquivo tem alterações não salvas" "This file is on {server}, open only to you. Share it to let others in with a new code." = "Este arquivo está em {server}, aberto somente para você. Compartilhe-o para deixar outras pessoas entrarem com um novo código." "This frame is new on the branch." = "Este quadro é novo na branch." "This frame isn't on the branch." = "Este quadro não está na branch." @@ -1450,8 +1449,6 @@ status = "draft — needs native review" "Unresolve" = "Reabrir" "Unsaved changes" = "Alterações não salvas" "Unsaved changes in {names}. Save them before closing?" = "Há alterações não salvas em {names}. Salvá-las antes de fechar?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "Alterações não salvas: salve primeiro ({save}) ou feche a aba com {alt}+clique para descartá-las" -"Unsaved changes: save first, or close again with {key} to discard" = "Alterações não salvas: salve primeiro ou feche de novo com {key} para descartá-las" "Up" = "Para cima" "Update" = "Atualizar" "Update from main" = "Atualizar a partir do principal" diff --git a/crates/ui-egui/locales/ru.toml b/crates/ui-egui/locales/ru.toml index a9a155818..01e1d86ac 100644 --- a/crates/ui-egui/locales/ru.toml +++ b/crates/ui-egui/locales/ru.toml @@ -1488,7 +1488,6 @@ name = "Русский" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "Эта страница хранит токен владельца, только пока она открыта. Скопируйте токен, чтобы управлять файлом позже: это пароль к файлу, он больше не будет показан." "This condition is edited as an expression" = "Это условие редактируется как выражение" "This file" = "Этот файл" -"This file has unsaved changes" = "В файле есть несохранённые изменения" "This file is on {server}, open only to you. Share it to let others in with a new code." = "Файл находится на {server} и доступен только вам. Включите общий доступ, чтобы пригласить других по новому коду." "This file is too large to join here (up to {mb} MB)" = "Этот файл слишком большой, чтобы подключиться здесь (до {mb} МБ)" "This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "В этом файле используются шрифты, не установленные на этом компьютере. Их текст отрисовывается запасным шрифтом, пока вы их не установите." @@ -1545,8 +1544,6 @@ name = "Русский" "Unresolve" = "Снова открыть" "Unsaved changes" = "Несохранённые изменения" "Unsaved changes in {names}. Save them before closing?" = "Несохранённые изменения в {names}. Сохранить их перед закрытием?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "Есть несохранённые изменения: сохраните ({save}) или закройте вкладку нажатием с {alt}, чтобы отбросить их" -"Unsaved changes: save first, or close again with {key} to discard" = "Есть несохранённые изменения: сохраните или закройте ещё раз с {key}, чтобы отбросить их" "Up" = "Вверх" "Update plugin" = "Обновить плагин" "Update" = "Обновить" diff --git a/crates/ui-egui/locales/sv.toml b/crates/ui-egui/locales/sv.toml index 9384ba152..a94feb2a9 100644 --- a/crates/ui-egui/locales/sv.toml +++ b/crates/ui-egui/locales/sv.toml @@ -1561,7 +1561,6 @@ name = "Svenska" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "Den här sidan behåller ägartoken bara så länge den är öppen. Kopiera den om du vill hantera filen senare: den fungerar som ett lösenord för filen och visas inte igen." "This condition is edited as an expression" = "Det här villkoret redigeras som ett uttryck" "This file" = "Den här filen" -"This file has unsaved changes" = "Filen har osparade ändringar" "This file is too large to join here (up to {mb} MB)" = "Den här filen är för stor för att ansluta till här (högst {mb} MB)" "This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "Den här filen använder typsnitt som inte är installerade på den här datorn. Deras text ritas med ett reservtypsnitt tills du installerar dem." "This file is on {server}, open only to you. Share it to let others in with a new code." = "Filen ligger på {server} och är bara öppen för dig. Dela den för att släppa in andra med en ny kod." @@ -1623,8 +1622,6 @@ name = "Svenska" "Unresolve" = "Markera som olöst" "Unsaved changes" = "Osparade ändringar" "Unsaved changes in {names}. Save them before closing?" = "Osparade ändringar i {names}. Vill du spara dem innan du stänger?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "Osparade ändringar: spara först ({save}), eller stäng fliken med {alt}-klick för att slänga dem" -"Unsaved changes: save first, or close again with {key} to discard" = "Osparade ändringar: spara först, eller stäng igen med {key} för att slänga dem" "Up" = "Upp" "Update check is not supported in the web browser." = "Sökning efter uppdateringar stöds inte i webbläsaren." "Update plugin" = "Uppdatera plugin" diff --git a/crates/ui-egui/locales/th.toml b/crates/ui-egui/locales/th.toml index 45de7b858..81b581ce0 100644 --- a/crates/ui-egui/locales/th.toml +++ b/crates/ui-egui/locales/th.toml @@ -1470,7 +1470,6 @@ status = "draft — needs native review" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "หน้านี้เก็บโทเคนเจ้าของไว้เฉพาะตอนที่เปิดอยู่ คัดลอกไว้เพื่อจัดการไฟล์ภายหลัง: โทเคนนี้เป็นรหัสผ่านของไฟล์นี้และจะไม่แสดงอีก" "This condition is edited as an expression" = "เงื่อนไขนี้แก้ไขเป็นนิพจน์" "This file" = "ไฟล์นี้" -"This file has unsaved changes" = "ไฟล์นี้มีการเปลี่ยนแปลงที่ยังไม่ได้บันทึก" "This file is too large to join here (up to {mb} MB)" = "ไฟล์นี้ใหญ่เกินกว่าจะเข้าร่วมที่นี่ (สูงสุด {mb} MB)" "This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "ไฟล์นี้ใช้ฟอนต์ที่ยังไม่ได้ติดตั้งในคอมพิวเตอร์เครื่องนี้ ข้อความจะแสดงด้วยฟอนต์สำรองจนกว่าคุณจะติดตั้ง" "This file is on {server}, open only to you. Share it to let others in with a new code." = "ไฟล์นี้อยู่บน {server} เปิดได้เฉพาะคุณ แชร์เพื่อให้คนอื่นเข้าได้ด้วยรหัสใหม่" @@ -1527,8 +1526,6 @@ status = "draft — needs native review" "Unresolve" = "ยกเลิกสถานะแก้ไขแล้ว" "Unsaved changes" = "การเปลี่ยนแปลงที่ยังไม่ได้บันทึก" "Unsaved changes in {names}. Save them before closing?" = "{names} มีการเปลี่ยนแปลงที่ยังไม่ได้บันทึก บันทึกก่อนปิดหรือไม่" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "มีการเปลี่ยนแปลงที่ยังไม่ได้บันทึก: บันทึกก่อน ({save}) หรือปิดแท็บด้วย {alt}+คลิกเพื่อทิ้งการเปลี่ยนแปลง" -"Unsaved changes: save first, or close again with {key} to discard" = "มีการเปลี่ยนแปลงที่ยังไม่ได้บันทึก: บันทึกก่อน หรือปิดอีกครั้งด้วย {key} เพื่อทิ้งการเปลี่ยนแปลง" "Up" = "ขึ้น" "Update plugin" = "อัปเดตปลั๊กอิน" "Update" = "อัปเดต" diff --git a/crates/ui-egui/locales/tr.toml b/crates/ui-egui/locales/tr.toml index db05d1c93..b07d25462 100644 --- a/crates/ui-egui/locales/tr.toml +++ b/crates/ui-egui/locales/tr.toml @@ -1452,7 +1452,6 @@ name = "Türkçe" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "Bu sayfa sahip belirtecini yalnızca açık kaldığı sürece tutar. Dosyayı daha sonra yönetmek için kopyalayın: bu, dosyanın parolasıdır ve bir daha gösterilmez." "This condition is edited as an expression" = "Bu koşul bir ifade olarak düzenleniyor" "This file" = "Bu dosya" -"This file has unsaved changes" = "Bu dosyada kaydedilmemiş değişiklikler var" "This file is on {server}, open only to you. Share it to let others in with a new code." = "Bu dosya {server} üzerinde ve yalnızca size açık. Başkalarını yeni bir kodla almak için paylaşın." "This frame is new on the branch." = "Bu çerçeve dalda yeni." "This frame isn't on the branch." = "Bu çerçeve dalda yok." @@ -1505,8 +1504,6 @@ name = "Türkçe" "Unresolve" = "Çözülmedi yap" "Unsaved changes" = "Kaydedilmemiş değişiklikler" "Unsaved changes in {names}. Save them before closing?" = "{names} içinde kaydedilmemiş değişiklikler var. Kapatmadan önce kaydedilsin mi?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "Kaydedilmemiş değişiklikler: önce kaydedin ({save}) veya atmak için sekmeyi {alt}-tıklamayla kapatın" -"Unsaved changes: save first, or close again with {key} to discard" = "Kaydedilmemiş değişiklikler: önce kaydedin veya atmak için {key} ile yeniden kapatın" "Up" = "Yukarı" "Update plugin" = "Eklentiyi güncelle" "Update" = "Güncelle" diff --git a/crates/ui-egui/locales/vi.toml b/crates/ui-egui/locales/vi.toml index 8b58fc67e..9a4d600fe 100644 --- a/crates/ui-egui/locales/vi.toml +++ b/crates/ui-egui/locales/vi.toml @@ -1414,7 +1414,6 @@ status = "draft — needs native review" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "Trang này chỉ giữ mã thông báo chủ sở hữu khi còn mở. Hãy sao chép mã này để quản lý tệp sau: đây là mật khẩu của tệp và sẽ không hiển thị lại." "This condition is edited as an expression" = "Điều kiện này được chỉnh sửa dưới dạng biểu thức" "This file" = "Tệp này" -"This file has unsaved changes" = "Tệp này có thay đổi chưa lưu" "This file is on {server}, open only to you. Share it to let others in with a new code." = "Tệp này đang ở trên {server} và chỉ mình bạn mở được. Hãy chia sẻ để người khác tham gia bằng mã mới." "This file is too large to join here (up to {mb} MB)" = "Tệp này quá lớn để tham gia tại đây (tối đa {mb} MB)" "This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "Tệp này sử dụng phông chữ chưa được cài đặt trên máy tính này. Văn bản sẽ hiển thị bằng phông chữ dự phòng cho đến khi bạn cài đặt chúng." @@ -1465,8 +1464,6 @@ status = "draft — needs native review" "Unread" = "Chưa đọc" "Unresolve" = "Mở lại bình luận" "Unsaved changes" = "Thay đổi chưa lưu" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "Có thay đổi chưa lưu: hãy lưu trước ({save}), hoặc giữ {alt} khi nhấp đóng thẻ để hủy bỏ" -"Unsaved changes: save first, or close again with {key} to discard" = "Có thay đổi chưa lưu: hãy lưu trước, hoặc đóng lại lần nữa bằng {key} để hủy bỏ" "Up" = "Lên" "Update" = "Cập nhật" "Update from main" = "Cập nhật từ nhánh chính" diff --git a/crates/ui-egui/locales/zh-Hans.toml b/crates/ui-egui/locales/zh-Hans.toml index a6ecb8ab3..b48345acc 100644 --- a/crates/ui-egui/locales/zh-Hans.toml +++ b/crates/ui-egui/locales/zh-Hans.toml @@ -1407,7 +1407,6 @@ status = "draft — needs native review" "This page keeps the owner token only while it is open. Copy it to manage the file later: it is a password for this file and won't be shown again." = "此页面仅在打开期间保留所有者令牌。如需稍后管理此文件,请复制它:它相当于此文件的密码,且不会再次显示。" "This condition is edited as an expression" = "此条件以表达式编辑" "This file" = "此文件" -"This file has unsaved changes" = "此文件有未保存的更改" "This file is on {server}, open only to you. Share it to let others in with a new code." = "此文件在 {server} 上,只有你能打开。分享后,其他人可以用新代码加入。" "This frame is new on the branch." = "此画框是分支上新增的。" "This frame isn't on the branch." = "此画框不在分支上。" @@ -1460,8 +1459,6 @@ status = "draft — needs native review" "Unresolve" = "取消解决" "Unsaved changes" = "未保存的更改" "Unsaved changes in {names}. Save them before closing?" = "{names} 中有未保存的更改。关闭前要保存吗?" -"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "有未保存的更改:请先保存({save}),或按住 {alt} 点击关闭标签页以丢弃" -"Unsaved changes: save first, or close again with {key} to discard" = "有未保存的更改:请先保存,或再次按 {key} 关闭以丢弃" "Up" = "向上" "Update" = "更新" "Update from main" = "从主文件更新" diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 93762e579..061084f9b 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -1,6 +1,6 @@ use super::{ - Done, FigApp, LeftTab, MobilePanel, NodeId, PANEL_DEFAULT, RightTab, Value, comments, dev_compare, dialogs, home, i18n, import_report, json, - layers, live, menus, missing_fonts, plugins_ui, present, tabs, updates_ui, versions, + Done, FigApp, LeftTab, MobilePanel, NodeId, PANEL_DEFAULT, RightTab, Value, comments, dev_compare, dialogs, home, import_report, json, layers, + live, menus, missing_fonts, plugins_ui, present, tabs, updates_ui, versions, }; impl FigApp { @@ -270,7 +270,13 @@ impl FigApp { let y = r.data.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0); comments::start_draft(self, x, y); } - "dialog.unsaved" => self.toast(i18n::tr("This file has unsaved changes")), + "dialog.unsaved" => { + // `file.close` refused a file with unsaved changes: ask about it. + let i = r.data.get("index").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).unwrap_or(self.session.active); + if let Some(d) = self.session.docs.get(i) { + self.ui.close_tab = Some(crate::windows::TabClose::Ask(d.uid)); + } + } "dialog.plugins" => self.ui.plugins_window = true, "dialog.pluginSave" => plugins_ui::save_file(self, &r.data), "dialog.cursorChat" => live::open_chat(self), diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a1df8e750..52170af44 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -178,6 +178,7 @@ pub fn keys(app: &mut FigApp, ctx: &Context) { || u.import_report.is_some() || u.missing_fonts.is_some() || u.confirm_close + || matches!(u.close_tab, Some(crate::windows::TabClose::Ask(_))) || u.export_preview || u.shortcuts_panel || u.preferences @@ -194,6 +195,10 @@ pub fn keys(app: &mut FigApp, ctx: &Context) { { return; } + if matches!(u.close_tab, Some(crate::windows::TabClose::Ask(_))) { + u.close_tab = None; + return; + } for flag in [&mut u.confirm_close, &mut u.export_preview, &mut u.shortcuts_panel, &mut u.preferences, &mut u.about] { if std::mem::take(flag) { return; @@ -405,6 +410,7 @@ pub fn show(app: &mut FigApp, ctx: &Context) { crate::live::publish_dialog(app, ctx); crate::online::dialogs(app, ctx); crate::windows::confirm_close(app, ctx); + crate::windows::confirm_close_tab(app, ctx); } /// Preferences ▸ Interface size: a size relative to the system's display scale (100 % is the diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a7397cee4..a2d1c34f3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -592,6 +592,8 @@ pub struct UiState { pub online: online::OnlineUi, /// The window was asked to close with unsaved changes: the question shows. pub confirm_close: bool, + /// A tab was asked to close with unsaved changes: the question for it, then its save. + pub close_tab: Option, /// The file a Save as started from the unsaved-changes question is saving: the window closes /// once it is saved, and stays open if the dialog is cancelled or the save fails. pub close_after_save_as: Option, @@ -715,6 +717,7 @@ impl Default for UiState { live: live::LiveUi::default(), online: online::OnlineUi::default(), confirm_close: false, + close_tab: None, close_after_save_as: None, save_on_close: false, } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 299d2a20f..98fd881d1 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -212,11 +212,7 @@ pub fn invoke(app: &mut FigApp, id: &str) { } "edit.paste" => paste(app, None, None), "file.close" if app.session.ds().is_ok_and(|d| d.is_dirty() && d.branch_of.is_none()) => { - let save = pretty_shortcut(crate::shortcuts::shortcut("file.save").unwrap_or("")); - app.toast(trf( - "Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard", - &[("save", &save), ("alt", &pretty_shortcut("Alt"))], - )); + crate::windows::ask_close_tab(app, app.session.active); } _ => { app.run(id, json!({})); diff --git a/crates/ui-egui/src/tabs.rs b/crates/ui-egui/src/tabs.rs index e59552d12..558792d08 100644 --- a/crates/ui-egui/src/tabs.rs +++ b/crates/ui-egui/src/tabs.rs @@ -303,18 +303,15 @@ fn drag_free_space(ui: &mut Ui, rect: Rect, from_x: f32, to_x: f32) { } } -/// Closes tab `i`; unsaved changes need a second close with Alt held. +/// Closes tab `i`: with unsaved changes it asks first (Don't Save / Cancel / Save), and Alt held +/// drops them without asking. fn close_tab(app: &mut FigApp, ui: &Ui, i: usize) { // A branch tab's edits live on in its main file: closing it loses nothing. let dirty = app.session.docs.get(i).is_some_and(|d| d.is_dirty() && d.branch_of.is_none()); - if dirty { - app.ui.find = None; - app.toast(trf("Unsaved changes: save first, or close again with {key} to discard", &[("key", &crate::toolbar::pretty_shortcut("Alt"))])); - if ui.input(|inp| inp.modifiers.alt) { - app.run("file.close", json!({"index": i, "force": true})); - } + if dirty && ui.input(|inp| inp.modifiers.alt) { + app.run("file.close", json!({"index": i, "force": true})); } else { - app.run("file.close", json!({"index": i})); + crate::windows::ask_close_tab(app, i); } } diff --git a/crates/ui-egui/src/titlebar_tests.rs b/crates/ui-egui/src/titlebar_tests.rs index e329c7417..c36a05c23 100644 --- a/crates/ui-egui/src/titlebar_tests.rs +++ b/crates/ui-egui/src/titlebar_tests.rs @@ -16,13 +16,15 @@ struct Ui { time: f64, /// What the system reports about the window. maximized: bool, + /// Modifier keys held during the next frames. + modifiers: egui::Modifiers, } impl Ui { fn new(title_bar: TitleBar) -> Self { let mut app = FigApp::new(Session::new(), Box::new(NoServices)); app.ui.title_bar = title_bar; - let mut u = Self { ctx: egui::Context::default(), app, time: 0.0, maximized: false }; + let mut u = Self { ctx: egui::Context::default(), app, time: 0.0, maximized: false, modifiers: egui::Modifiers::NONE }; for _ in 0..3 { u.frame(vec![]); } @@ -30,8 +32,9 @@ impl Ui { } /// Run one frame; returns the window commands it sent. - fn frame(&mut self, events: Vec) -> Vec { + fn frame(&mut self, mut events: Vec) -> Vec { self.time += 1.0 / 60.0; + events.insert(0, Event::ModifiersChanged(self.modifiers)); let mut input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, SIZE)), time: Some(self.time), events, ..Default::default() }; input.viewports.entry(ViewportId::ROOT).or_default().maximized = Some(self.maximized); let app = &mut self.app; @@ -242,3 +245,107 @@ fn a_system_title_bar_leaves_the_window_alone() { assert!(u.drag(EMPTY, vec2(40.0, 10.0)).is_empty()); assert!(u.drag(pos2(SIZE.x - 2.0, SIZE.y - 2.0), vec2(-30.0, -30.0)).iter().all(|c| !matches!(c, ViewportCommand::BeginResize(_)))); } + +/// The main window's first tab closing: (its file's uid, the close button of the first tab). +fn first_tab(u: &Ui) -> (u64, Pos2) { + (u.app.session.docs[0].uid, pos2(156.0, 20.0)) +} + +/// Whether file `uid` is still open in a tab. +fn open(u: &Ui, uid: u64) -> bool { + u.app.session.docs.iter().any(|d| d.uid == uid) +} + +/// Whether the unsaved-changes question is on screen. +fn asking(u: &Ui) -> bool { + u.ctx.memory(|memory| memory.area_rect(egui::Id::unique(Some(crate::i18n::tr("Unsaved changes")))).is_some()) +} + +/// #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. Escape (or Cancel) keeps the +/// tab, Don't Save closes it, Alt+click closes it without asking, and File ▸ Close tab asks too. +#[test] +fn closing_a_tab_with_unsaved_changes_asks() { + use crate::windows::{CloseAnswer, TabClose, answer_close_tab}; + let mut u = Ui::new(TitleBar::Custom); + u.app.session.execute("file.new", &json!({})).unwrap(); + u.app.session.execute("doc.switch", &json!({"index": 0})).unwrap(); + u.app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + let (uid, close) = first_tab(&u); + u.frame(vec![Event::PointerMoved(close)]); + u.click(close); + u.frame(vec![]); + assert!(open(&u, uid), "the tab waits for an answer"); + assert_eq!(u.app.ui.close_tab, Some(TabClose::Ask(uid))); + assert!(asking(&u), "the question is on screen"); + // Escape is Cancel: the tab stays, with its changes. + u.frame(vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }]); + u.frame(vec![]); + assert!(open(&u, uid), "Escape keeps the tab"); + assert!(u.app.ui.close_tab.is_none(), "and ends the question"); + // Don't Save closes it. + u.click(close); + assert_eq!(u.app.ui.close_tab, Some(TabClose::Ask(uid))); + let ctx = u.ctx.clone(); + answer_close_tab(&mut u.app, &ctx, CloseAnswer::DontSave); + assert!(!open(&u, uid), "Don't Save closes the tab"); + // Alt+click drops the changes without asking. + u.app.session.execute("doc.switch", &json!({"index": 0})).unwrap(); + u.app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + u.app.session.execute("file.new", &json!({})).unwrap(); + let (uid, close) = first_tab(&u); + u.frame(vec![Event::PointerMoved(close)]); + u.modifiers = egui::Modifiers::ALT; + u.click(close); + u.modifiers = egui::Modifiers::NONE; + assert!(!open(&u, uid), "Alt+click closes without asking"); + assert!(u.app.ui.close_tab.is_none()); + // File ▸ Close tab (and its shortcut) asks about the file shown. + u.app.session.execute("doc.switch", &json!({"index": 0})).unwrap(); + u.app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + let uid = u.app.session.docs[0].uid; + crate::menus::invoke(&mut u.app, "file.close"); + assert_eq!(u.app.ui.close_tab, Some(TabClose::Ask(uid))); + assert!(open(&u, uid)); +} + +/// #2032: Save in the question saves the file, then closes its tab; a file without a path asks +/// where with Save as first and the tab stays open until it is saved. +#[test] +fn save_in_the_tab_question_saves_then_closes() { + let dir = std::env::temp_dir().join(format!("figcraft-tab-close-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("kept.figcraft"); + let mut u = Ui::new(TitleBar::Custom); + u.app.session.execute("file.new", &json!({})).unwrap(); + u.app.session.execute("doc.switch", &json!({"index": 0})).unwrap(); + u.app.session.execute("file.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let saved = std::fs::metadata(&path).unwrap().len(); + u.app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap(); + let (uid, close) = first_tab(&u); + u.frame(vec![Event::PointerMoved(close)]); + u.click(close); + u.frame(vec![]); + assert!(asking(&u)); + // Enter answers Save. + u.frame(vec![Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }]); + for _ in 0..3 { + u.frame(vec![]); + } + assert!(!open(&u, uid), "saved, then closed"); + assert!(std::fs::metadata(&path).unwrap().len() > saved, "the rectangle was saved"); + // No path: Save as starts (headless: no dialog can open), and the tab stays open. + u.app.session.execute("doc.switch", &json!({"index": 0})).unwrap(); + u.app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap(); + let (uid, close) = first_tab(&u); + u.frame(vec![Event::PointerMoved(close)]); + u.click(close); + let ctx = u.ctx.clone(); + crate::windows::answer_close_tab(&mut u.app, &ctx, crate::windows::CloseAnswer::Save); + for _ in 0..3 { + u.frame(vec![]); + } + assert!(open(&u, uid), "nothing saved it: the tab stays"); + assert!(u.app.ui.close_tab.is_none()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index f9f6067d7..3397e00de 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -445,6 +445,15 @@ pub(crate) fn confirm_close(app: &mut FigApp, ctx: &Context) { app.ui.confirm_close = false; return; } + if let Some(a) = unsaved_question(ctx, &names) { + answer_close(app, ctx, a); + } +} + +/// The unsaved-changes question about files `names` (Don't Save / Cancel / Save, as the other +/// Craft apps ask it; Enter answers Save, the dialog's close button Cancel): `None` while it is +/// unanswered. +fn unsaved_question(ctx: &Context, names: &[String]) -> Option { let t = crate::theme::Tokens::get(ctx); let mut open = true; let mut answer = None; @@ -471,8 +480,114 @@ pub(crate) fn confirm_close(app: &mut FigApp, ctx: &Context) { if !open { answer = Some(CloseAnswer::Cancel); } - if let Some(a) = answer { - answer_close(app, ctx, a); + answer +} + +/// Where closing a tab whose file has unsaved changes is (each step names the file's uid). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TabClose { + /// The unsaved-changes question shows for it. + Ask(u64), + /// Save was answered: it saves next frame, once a panel field the click took the keyboard + /// from has committed what was typed, then the tab closes. + Save(u64), + /// Its Save as dialog (a file without a path, or a .fig) is open: the tab closes once the file + /// is saved, and stays open if the dialog is cancelled or the save fails. + AfterSaveAs(u64), +} + +/// Close tab `i` (its X, a middle click, File ▸ Close tab): at once when its file has no unsaved +/// changes (a branch tab's edits are in its main file already), else after the unsaved-changes +/// question ([`confirm_close_tab`]). +pub(crate) fn ask_close_tab(app: &mut FigApp, i: usize) { + let Some(d) = app.session.docs.get(i) else { return }; + if d.is_dirty() && d.branch_of.is_none() { + app.ui.find = None; + app.ui.close_tab = Some(TabClose::Ask(d.uid)); + } else { + app.run("file.close", json!({"index": i})); + } +} + +/// Act on the unsaved-changes question's answer for the tab it asks about: Cancel keeps the tab, +/// Don't Save closes it and drops the changes, Save saves the file next frame, then closes it. +pub(crate) fn answer_close_tab(app: &mut FigApp, ctx: &Context, answer: CloseAnswer) { + let Some(TabClose::Ask(uid)) = app.ui.close_tab else { return }; + app.ui.close_tab = None; + match answer { + CloseAnswer::Cancel => {} + CloseAnswer::DontSave => { + if let Some(i) = tab_of(app, uid) { + app.run("file.close", json!({"index": i, "force": true})); + } + } + CloseAnswer::Save => { + app.ui.close_tab = Some(TabClose::Save(uid)); + ctx.request_repaint(); + } + } +} + +/// Tab `i` of the session whose file has uid `uid`, if it is still open. +fn tab_of(app: &FigApp, uid: u64) -> Option { + app.session.docs.iter().position(|d| d.uid == uid) +} + +/// The unsaved-changes question for a closing tab and what its answer starts: Don't Save closes +/// the tab and drops the changes, Cancel keeps it, Save saves the file (Save as for one without a +/// path or saved as .fig) and closes the tab once it is saved. +pub(crate) fn confirm_close_tab(app: &mut FigApp, ctx: &Context) { + let Some(step) = app.ui.close_tab else { return }; + let (TabClose::Ask(uid) | TabClose::Save(uid) | TabClose::AfterSaveAs(uid)) = step; + let Some(i) = tab_of(app, uid) else { + app.ui.close_tab = None; + return; + }; + let dirty = app.session.docs.get(i).is_some_and(DocState::is_dirty); + match step { + TabClose::Ask(_) if !dirty => { + // Saved meanwhile: nothing is lost by closing. + app.ui.close_tab = None; + app.run("file.close", json!({"index": i})); + } + TabClose::Ask(_) => { + let names: Vec = app.session.docs.get(i).map(|d| d.doc.name.clone()).into_iter().collect(); + if let Some(a) = unsaved_question(ctx, &names) { + answer_close_tab(app, ctx, a); + } + } + TabClose::Save(_) => { + app.ui.close_tab = None; + // Saving acts on the file shown. + app.session.active = i; + let native = app.session.docs.get(i).and_then(|d| d.path.as_deref()).is_some_and(|p| { + !std::path::Path::new(p).extension().and_then(std::ffi::OsStr::to_str).is_some_and(|e| e.eq_ignore_ascii_case("fig")) + }); + if !native { + app.ui.close_tab = Some(TabClose::AfterSaveAs(uid)); + app.save_as_dialog(); + if app.pending_dialog.is_none() { + // No dialog could start: the tab stays open. + app.ui.close_tab = None; + } + ctx.request_repaint(); + return; + } + if app.run("file.save", json!({})).is_some() + && let Some(i) = tab_of(app, uid) + { + app.run("file.close", json!({"index": i})); + } + } + TabClose::AfterSaveAs(_) => { + if app.pending_dialog.is_some() { + return; + } + app.ui.close_tab = None; + if !dirty { + app.run("file.close", json!({"index": i})); + } + } } } diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d98a6ed73..611c3f400 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** patch (a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** patch (closing a tab whose file has unsaved changes (its X, a middle click, File ▸ Close tab) asks Don't Save / Cancel / Save as closing the window does, instead of a toast that left it open (#2032); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -15,7 +15,7 @@ interaction feel not yet compared. | Item | Status | Notes | |---|---|---| -| UI3 layout: tab strip as title bar, icon rail, file header, pages + layers, floating bottom toolbar with flyouts, Design / Prototype / Inspect panels | done | frameless window on Windows/Linux with drawn buttons; on a Wayland compositor that offers no server-side decorations (GNOME) the window gets winit's Adwaita controls instead (#592; checked by its author on GNOME, KDE not run) | +| UI3 layout: tab strip as title bar, icon rail, file header, pages + layers, floating bottom toolbar with flyouts, Design / Prototype / Inspect panels | done | frameless window on Windows/Linux with drawn buttons; tabs reorder by dragging along the strip, and closing one whose file has unsaved changes asks Don't Save / Cancel / Save (Alt+close drops the changes at once, #2032); on a Wayland compositor that offers no server-side decorations (GNOME) the window gets winit's Adwaita controls instead (#592; checked by its author on GNOME, KDE not run) | | Light and dark themes | done | colours from `theme::Tokens`; a file or a page made while the dark theme shows gets a `#1E1E1E` page (`#F5F5F5` in the light theme), its own from then on: changing the theme repaints no page and opened files keep theirs; the file the app opens with takes the theme once it is known; the CLI, MCP and exports have no theme and keep `#F5F5F5`; text drawn with the Text tool is white on a dark page and black on a light one (so is text a command makes in the app without naming a fill; headless sessions keep black) (`theme_pages_tests`, `dark_page_text_tests`) | | Minimize UI (Shift+Cmd/Ctrl+\\, the Minimize button by the file name) and Show/Hide UI (Cmd/Ctrl+\\) | done | Minimize collapses the navigation bar and both sidebars and keeps the toolbar and the panel widths; "If you select an object while the panels are minimized, the left sidebar remains minimized while the right sidebar expands [...] Once all objects are deselected, the right panel minimizes again" (Explore the navigation bar and left sidebar); a small Expand button at the top left of the canvas puts them back (FigCraft's own, the article names no control for it). Hide UI takes the toolbar too (`panel_width_tests`, `shortcuts_tests`; #1835) | | Resizable panels | done | each panel's edge drags its width (left 200–480, right 240–480, 240 by default; a double-click on the edge or View ▸ Panels ▸ Reset panel widths puts the default back); the widths are each window's own, the main window's are kept in the preferences when a drag ends and come back at the next start, a new window opens with those of the window it comes from; Minimize UI hides the panels and brings them back as they were; the view keeps its centre and zoom while a panel is resized; in a window too small for them the panels give way so the canvas keeps 160 px (the left one first), down to the smallest window (800×500) (`panel_width_tests`). Not compared with Figma's widths; no snap points | @@ -178,6 +178,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-06 | patch | M7, #2032: closing a tab whose file has unsaved changes, by its X, a middle click, File ▸ Close tab or its shortcut, only showed a toast ("save first, or close again with Alt to discard") and left the tab open, so closing seemed not to work. It now asks the unsaved-changes question the window asks (`windows::TabClose`): Don't Save closes the tab, Cancel or Escape keeps it, Save saves the file and then closes it (a file without a path, or saved as .fig, asks where with Save as first and stays open if that is cancelled); Alt+close still drops the changes at once, and `file.close`'s `dialog.unsaved` request asks too. The three toasts left the catalogs. Tests: `titlebar_tests::closing_a_tab_with_unsaved_changes_asks`, `titlebar_tests::save_in_the_tab_question_saves_then_closes`. Reordering tabs by dragging, the issue's other half, landed on 2026-10-19 (`dragging_a_tab_along_the_bar_reorders_it_without_detaching`) | | 2026-11-04 | patch | M1, #1852: a press on one of the open gradient's handles or stops on the canvas is the colour picker's own, not a press outside it (Figma keeps the picker and the handles up while a handle or stop is dragged; the stops are made to be dragged: "You can click and drag a stop to change its placement on the gradient", Use gradients as a fill or stroke). The canvas took the press and began the drag, then the picker, drawn later in the same frame, saw a press outside its card and closed, committing the drag's interaction at once; the handles vanished with it and the drag went on without an undo step of its own. Now the picker stays while a gradient handle or stop drags, and the drag is one undo step; a press elsewhere on the canvas still closes it. A handle drag whose button goes up off the canvas (over a panel or the picker) ends there too, instead of waiting, uncommitted, to move the handle to the next press on the canvas. Tests: `colorpicker_selection_tests::dragging_a_gradient_handle_on_the_canvas_keeps_the_picker_open`, `colorpicker_selection_tests::a_gradient_drag_released_off_the_canvas_ends_there`. | | 2026-11-02 | patch | M8, #1875: a click with the Bend tool on a sharp point between two segments gives it handles along the line between its neighbours, a third of the way to each ("Click on a point or path where you want to add a curve", Edit vector layers); a click on a curved point still makes it sharp, a drag still sets the handles by hand, an endpoint is left alone. Between a handle's end and a point both within reach of the pointer, the nearer one on the page is hit (the handle on a tie), so a short path's point (its handles a few pixels long) can be clicked again. Before, only a drag curved a point, and a short one left two tiny handles in its direction. Tests: `vectoredit::tests::short_handles_leave_their_point_clickable`, `vectoredit::tests::a_bend_click_curves_a_sharp_point_between_its_neighbours`, `bend_tool_smooths_and_sharpens_points`. Numbers unchanged. | | 2026-11-02 | minor | M4, #1827: wrap style on a text layer (`WrapStyle`: Auto, Balance, Pretty): Balance re-breaks each paragraph at the narrowest width that keeps its line count (bisection over the greedy breaker, as browsers balance), Pretty narrows one of the last four lines just enough so the last line isn't one word; `text.wrapStyle`, `node.set wrapStyle` (`textWrap` too), inspect `wrapStyle`, Dev Mode CSS `text-wrap` (Tailwind `text-balance` / `text-pretty`), the Type settings control under Vertical trim. Per-paragraph settings, text-style support and the `.fig` import/export mapping stay open. Test: `text_behaviour_tests::balance_and_pretty_wrap_styles_break_lines_as_documented`. | From 7f62fc141691fce771c4bc4f5dd2b43029361106 Mon Sep 17 00:00:00 2001 From: Filip Strajnar Date: Fri, 6 Nov 2026 12:44:01 +0100 Subject: [PATCH 093/102] M5: proto.settings refuses an unknown device and answers the settings (#2027) `proto.settings` took any string as the device ("Pixel Nonexistent", "iphone 16") and saved it in the file: the presenter then drew no device frame while its picker showed the name as if it were one. An unknown colour was already refused with the device's colours, but a typo in the device went unnoticed, and an agent couldn't read the settings back (`proto.settings {}` answered `{ok: true}`, and neither `inspect_document` nor `get_node` shows a page's prototype settings). An unknown name, or a value that isn't a string, is now refused with every name the picker offers ("None", "Custom size" and the devices), and nothing changes. A known name is taken in any case and with spaces around it, and stored as the picker spells it (`known_device`). Every call answers the page's settings as they are after it (`settings_json`): device, background, rotation, the colour shown, the screen as presented (null without a device), the custom size and responsive, beside the `ok: true` it answered before; `proto.settings {}` reads them. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back`. Docs: mcp.md, prototyping-parity.md, ROADMAP.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LvG6E2LxvJ6MuFmiLA6Zqm --- ROADMAP.md | 3 +- crates/engine/src/cmd/proto.rs | 48 ++++++++++++++++++++++-- crates/engine/src/proto_present_tests.rs | 28 ++++++++++++++ docs/mcp.md | 8 +++- docs/prototyping-parity.md | 3 +- 5 files changed, 82 insertions(+), 8 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 60f5962d2..706f49788 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** patch (`proto.settings` refuses an unknown device with the list of devices instead of saving it, takes a known one in any case, and answers the page's settings, so `proto.settings {}` reads them (#2027); glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -358,6 +358,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-06 | patch | M5, #2027: `proto.settings` refuses an unknown device name with the list of devices (it saved any string, and the presenter showed no device), takes known names in any case, and answers the page's prototype settings, so `proto.settings {}` reads them back over MCP. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back`. 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 | | 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 and 0.6 as much on the opposite side, with a faint gradient across the curve, 5% darker facing the light and lighter opposite (it was a glow mixed towards white, as deep as `splay` made it). `splay` turns the bend from along the edge's normal towards the way away from the layer's centre, as the reference tool's does, and no longer widens the light: files with a splay above 0 look different. The direction to the centre is worked out in the shape's own frame, so cut renders match. 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`. Numbers unchanged | diff --git a/crates/engine/src/cmd/proto.rs b/crates/engine/src/cmd/proto.rs index a39f7d036..acdf1729f 100644 --- a/crates/engine/src/cmd/proto.rs +++ b/crates/engine/src/cmd/proto.rs @@ -112,7 +112,7 @@ pub fn specs() -> Vec { spec!( "proto.settings", "Prototype settings", - "{device? (a device name, \"Custom size\" or \"None\"), background?, rotation? portrait|landscape (or 0|90; phones and tablets turn), color? (one of the device's colours by name), width?, height? (the custom size's screen, 1–10000 points; picks \"Custom size\"), responsive? bool (frames resize to the screen and their constraints and auto layout respond)}", + "{device? (a device name, \"Custom size\" or \"None\"; any case; another name is refused with the list), background?, rotation? portrait|landscape (or 0|90; phones and tablets turn), color? (one of the device's colours by name), width?, height? (the custom size's screen, 1–10000 points; picks \"Custom size\"), responsive? bool (frames resize to the screen and their constraints and auto layout respond)} → the page's settings after the call (none given: reads them)", true, settings ), @@ -173,12 +173,51 @@ pub fn specs() -> Vec { ] } -/// `proto.settings`: everything is checked before anything changes. +/// The device setting `name` stands for, as the device picker names it: "None", "Custom size" or a +/// model of [`PrototypeSettings::DEVICES`], whatever its case and the spaces around it. +fn known_device(name: &str) -> Option<&'static str> { + let name = name.trim(); + ["None", PrototypeSettings::CUSTOM_DEVICE] + .into_iter() + .chain(PrototypeSettings::DEVICES.iter().map(|d| d.name)) + .find(|d| d.eq_ignore_ascii_case(name)) +} + +/// What `proto.settings` answers: the page's prototype settings (the device as the picker names it, +/// the colour shown, the screen as presented, `null` without a device). +fn settings_json(ps: &PrototypeSettings) -> Value { + let screen = ps.device().map(|d| json!({"width": d.width, "height": d.height})); + json!({ + "ok": true, + "device": ps.device, + "background": format!("#{}", ps.background.to_hex()), + "rotation": ps.rotation, + "color": ps.device_color().map(|c| c.name), + "screen": screen, + "customSize": {"width": ps.custom_size[0], "height": ps.custom_size[1]}, + "responsive": ps.responsive, + }) +} + +/// `proto.settings`: everything is checked before anything changes; an unknown device is refused +/// with the devices to pick from, as an unknown colour is. Answers the settings as they are after +/// the call, so a call without parameters reads them. fn settings(s: &mut Session, p: &Value) -> Result { let cmd = "proto.settings"; let page = s.page()?; let bg = color(p, "background"); - let dev = string(p, "device"); + let dev = match p.get("device") { + None | Some(Value::Null) => None, + Some(v) => { + let name = v.as_str().unwrap_or_default(); + let found = known_device(name).ok_or_else(|| { + let names: Vec<&str> = + ["None", PrototypeSettings::CUSTOM_DEVICE].into_iter().chain(PrototypeSettings::DEVICES.iter().map(|d| d.name)).collect(); + bad(cmd, format!("unknown device {}: device is one of {}", figcraft_format::clip(&v.to_string(), 60), names.join("|"))) + })?; + Some(found.to_string()) + } + }; let rot = match p.get("rotation") { None | Some(Value::Null) => None, Some(v) => Some(rotation_of(v).ok_or_else(|| bad(cmd, "rotation: portrait|landscape"))?), @@ -231,12 +270,13 @@ fn settings(s: &mut Session, p: &Value) -> Result { None if !colors.iter().any(|x| x.name == next.color) => next.color.clear(), None => {} } + let answer = settings_json(&next); if next != *prototype && let NodeKind::Page { prototype, .. } = &mut s.doc_mut()?.get_mut(page)?.kind { *prototype = next; } - ok() + Ok(answer) } /// Resize top-level `frame` to a screen of `(w, h)` as a responsive prototype does: its children diff --git a/crates/engine/src/proto_present_tests.rs b/crates/engine/src/proto_present_tests.rs index 9d2bc48ba..9bb94313f 100644 --- a/crates/engine/src/proto_present_tests.rs +++ b/crates/engine/src/proto_present_tests.rs @@ -97,3 +97,31 @@ fn explicit_variable_modes_go_back_to_auto() { assert!(s.execute("variable.setMode", &json!({"ids": [f], "collection": "Tokens", "mode": "Dusk"})).is_err()); assert!(s.execute("variable.setMode", &json!({"ids": [f], "collection": "Tokens"})).is_err(), "a mode, or null for Auto"); } + +/// #2027: an unknown device is refused with the devices to pick from, as an unknown colour is, and +/// nothing changes; a known one is taken whatever its case and stored as the picker names it; the +/// settings read back from `proto.settings` without parameters. +#[test] +fn unknown_devices_are_refused_and_settings_read_back() { + let mut s = Session::new(); + let before = settings(&s); + for junk in [json!("Pixel Nonexistent"), json!(""), json!(42), json!(["iPhone 16"])] { + let err = s.execute("proto.settings", &json!({"device": junk, "responsive": true})).unwrap_err().to_string(); + assert!(err.contains("unknown device") && err.contains("iPhone 17|") && err.contains("Custom size"), "{junk}: {err}"); + assert_eq!(settings(&s), before, "{junk}: nothing changes"); + } + let set = s.execute("proto.settings", &json!({"device": " iphone 16 ", "color": "black"})).unwrap(); + assert_eq!(settings(&s).device, "iPhone 16", "stored as the picker names it"); + assert_eq!((&set["device"], &set["color"]), (&json!("iPhone 16"), &json!("Black"))); + let read = s.execute("proto.settings", &json!({})).unwrap(); + assert_eq!(read, set, "a call without parameters reads the settings"); + assert_eq!((&read["ok"], &read["rotation"], &read["responsive"]), (&json!(true), &json!("portrait"), &json!(false))); + assert_eq!(read["screen"], json!({"width": 393.0, "height": 852.0})); + assert!(read["background"].as_str().is_some_and(|c| c.starts_with('#')), "{read}"); + // "None" and "Custom size" in any case; no device has no screen or colour. + s.execute("proto.settings", &json!({"device": "custom SIZE", "width": 800, "height": 600})).unwrap(); + assert_eq!(settings(&s).device, PrototypeSettings::CUSTOM_DEVICE); + let none = s.execute("proto.settings", &json!({"device": "none"})).unwrap(); + assert_eq!((&none["device"], &none["screen"], &none["color"]), (&json!("None"), &json!(null), &json!(null))); + assert_eq!(none["customSize"], json!({"width": 800.0, "height": 600.0})); +} diff --git a/docs/mcp.md b/docs/mcp.md index b5e49e749..7ec3f8bb8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -847,11 +847,15 @@ removes the whole conditional). Every one is an undo step and applies to all `id with the same interactions). Flows `proto.flow.add` / `rename` / `remove`, and the device, its rotation and the background `proto.settings {device?, background?, rotation?, color?, width?, height?, responsive?}` (`None`, `iPhone 16`, `iPhone 16 Pro Max`, -`Android Compact`, `iPad mini`, `MacBook Air`, `Desktop` or `Custom size`; `rotation` `portrait` or +`Android Compact`, `iPad mini`, `MacBook Air`, `Desktop` or `Custom size`, in any case; another +name is an error that lists the devices, and nothing changes; `rotation` `portrait` or `landscape`, which turns phones and tablets; `color` one of the device's colours by name, e.g. `Black`, `White`, `Pink`, `Teal`, `Blue` for the iPhone 16 (an error lists them), `""` for the default; `width` / `height` set the custom size's screen, 1–10000 points, and pick `Custom size`, -which is a bare screen without a body). On a device the presented frame is sized to the device's +which is a bare screen without a body). Every call answers the page's settings as they are after +it, so `proto.settings {}` reads them: `{device, background, rotation, color (the colour shown, null +without a body), screen ({width, height} as presented, null without a device), customSize, +responsive}`. On a device the presented frame is sized to the device's screen: a frame bigger than the screen scrolls through its whole size whatever its `overflow`, content past the frame's own edges scrolls only as its `overflow` allows (else it's clipped), and `fixed` layers stay on screen (pinned to the edges their constraints name). With `responsive: true` (saved diff --git a/docs/prototyping-parity.md b/docs/prototyping-parity.md index 826b6780d..7c216bcae 100644 --- a/docs/prototyping-parity.md +++ b/docs/prototyping-parity.md @@ -1,6 +1,6 @@ # Prototyping parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-01 · **Change:** minor (Hide UI in the presenter's Options menu, and Cmd/Ctrl+\ as in the editor: the bar above the prototype and the navigation bar under it go away, a toast names the key that brings them back, `proto.presentOptions {hideUi}` (#1820); the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-06 · **Change:** patch (`proto.settings` refuses an unknown device with the list of devices instead of saving it, takes a known one in any case, and answers the page's settings, so `proto.settings {}` reads them (#2027); Hide UI in the presenter's Options menu, and Cmd/Ctrl+\ as in the editor: the bar above the prototype and the navigation bar under it go away, a toast names the key that brings them back, `proto.presentOptions {hideUi}` (#1820); the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7) **Breadth ~92%, ready ~74% (estimated).** Every Figma trigger except media, every action except media control, every transition and easing exist; key/gamepad triggers take controller buttons, @@ -107,6 +107,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Date | Change | Summary | |---|---|---| +| 2026-11-06 | patch | M5, #2027: `proto.settings` took any string as the device (`"Pixel Nonexistent"`, `"iphone 16"`) and saved it in the file; the presenter then drew no device while its picker showed the name as if it were one, and the settings couldn't be read back over MCP (`proto.settings {}` answered `{ok: true}`). An unknown name (or a non-string) is now refused with every name the picker offers (`None`, `Custom size` and the devices), as an unknown colour is refused with the device's colours, and nothing changes; a known name is taken in any case and stored as the picker spells it. Every call answers the page's settings after it: device, background, rotation, the colour shown, the screen as presented, the custom size and responsive. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back` | | 2026-10-31 | minor | Gap 15: the Controller menu names buttons as PlayStation and Switch controllers do; that item leaves the missing list. Estimate unchanged. Test: `present::tail_tests`. | | 2026-10-30 | minor | Opening a link in place: Open link has "Open in new tab", on by default; off, the web build's own tab goes to the link after the notice (or at once with it skipped); the desktop app has no tab of its own and opens the browser either way. Saved in files only when off (`openInNewTab`) and read from REST files. | | 2026-10-30 | patch | A manual overlay can be placed on the canvas (#405): while the interaction editor has an Open overlay action with Manual position open, the overlay frame shows dimmed, outlined, where it opens from the top-left of the layer that opens it (right below that layer without an offset), and dragging it moves it there. The X and Y fields follow while dragging, and the drag is one undo step (`crates/ui-egui/src/canvas/proto_canvas/overlay_ghost.rs`). Numbers unchanged | From 20f1219fbcd7550c01ff8ef668d7b4ff98bb06da Mon Sep 17 00:00:00 2001 From: Filip Strajnar Date: Fri, 6 Nov 2026 12:55:21 +0100 Subject: [PATCH 094/102] M1: Set default properties gives new shapes and text the layer's properties (#2028) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Edit ▸ Set default properties put the selected layer's properties into the Paste properties clipboard and did nothing else: a rectangle drawn afterwards was still the default grey, and what Copy properties had copied was replaced. The defaults are now kept apart (`Session::default_props`: one set for shapes, set from any layer but text, and one for text). Rectangles, ellipses, polygons and stars drawn or clicked with their tools take the shape defaults: fills, strokes and their settings, effects, opacity, blend and corners (only where the shape has corners), through `apply_copied_props`, the rules Paste properties already used (now shared). New text from the Text tool takes a text layer's fills and font and is laid out at that size. Frames, sections, slices, lines, arrows, vectors and layers made by commands keep their own look; the help center is silent on those. `edit.setDefaultProperties` answers `{for: shapes|text, properties}`. Tests: `default_props_tests::new_shapes_drawn_with_the_tools_take_the_default_properties`, `setting_defaults_leaves_the_copied_properties_alone`, `new_text_takes_a_text_layers_defaults_and_shapes_keep_theirs`. Docs: ui-parity.md, ROADMAP.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LvG6E2LxvJ6MuFmiLA6Zqm --- ROADMAP.md | 3 +- crates/engine/src/canvas/tools/click.rs | 17 +++- crates/engine/src/canvas/tools/draw.rs | 11 +++ crates/engine/src/cmd/edit.rs | 27 ++++-- crates/engine/src/cmd/edit/clipboard.rs | 26 +++-- crates/engine/src/default_props_tests.rs | 117 +++++++++++++++++++++++ crates/engine/src/lib.rs | 6 +- crates/engine/src/prefs.rs | 12 +++ crates/engine/src/session/new.rs | 1 + docs/ui-parity.md | 4 +- 10 files changed, 200 insertions(+), 24 deletions(-) create mode 100644 crates/engine/src/default_props_tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 60f5962d2..29926e0c5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** patch (Edit ▸ Set default properties now gives new shapes and text drawn with the tools the selected layer's fills, strokes, effects, opacity and corners (text: its font) instead of only copying them for Paste properties (#2028); glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -358,6 +358,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-06 | patch | M1, #2028: Edit ▸ Set default properties gives new rectangles, ellipses, polygons and stars drawn with the tools (and, set from a text layer, new text) the selected layer's properties; it only copied them for Paste properties. Tests: `default_props_tests` (3). 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 | | 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 and 0.6 as much on the opposite side, with a faint gradient across the curve, 5% darker facing the light and lighter opposite (it was a glow mixed towards white, as deep as `splay` made it). `splay` turns the bend from along the edge's normal towards the way away from the layer's centre, as the reference tool's does, and no longer widens the light: files with a splay above 0 look different. The direction to the centre is worked out in the shape's own frame, so cut renders match. 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`. Numbers unchanged | diff --git a/crates/engine/src/canvas/tools/click.rs b/crates/engine/src/canvas/tools/click.rs index a48b215bc..35a97a77a 100644 --- a/crates/engine/src/canvas/tools/click.rs +++ b/crates/engine/src/canvas/tools/click.rs @@ -193,6 +193,7 @@ impl Session { } // New text at the click (Figma puts the baseline-ish top-left there). let parent = frame_at(&doc, page, ev.p(), &[]).unwrap_or(page); + let defaults = self.default_props.text.clone(); let ds = self.ds_mut()?; let d = ds.doc_mut(); let id = d.alloc_id(); @@ -204,12 +205,18 @@ impl Session { if let Some(fills) = readable_text_fills(d, parent) { n.fills = fills; } - if let Some((w, h)) = figcraft_text::auto_size(&n) { - n.width = w.max(1.0); - n.height = h; - } - let line = n.height; d.insert(n, parent, None)?; + // Edit ▸ Set default properties from a text layer: its fills and font (best effort). + if let Some(defaults) = &defaults { + let _ = crate::cmd::edit::apply_copied_props("edit.setDefaultProperties", d, id, defaults); + } + let line = d.node_mut(id).map_or(14.0, |n| { + if let Some((w, h)) = figcraft_text::auto_size(n) { + n.width = w.max(1.0); + n.height = h; + } + n.height + }); ds.selection = vec![id]; textedit::begin(self, id, Some(0), true)?; self.tool.gesture = Gesture::TextBox { id, start: ev.p(), line }; diff --git a/crates/engine/src/canvas/tools/draw.rs b/crates/engine/src/canvas/tools/draw.rs index d59a2b904..499bfce89 100644 --- a/crates/engine/src/canvas/tools/draw.rs +++ b/crates/engine/src/canvas/tools/draw.rs @@ -38,6 +38,13 @@ impl Session { let pixel = self.ds().map(|d| d.view.snap_pixel).unwrap_or(true); let mut created = id; let page = self.page()?; + // Edit ▸ Set default properties: what new shapes take (not frames, sections, slices, lines + // or arrows, which keep their own look). + let defaults = if matches!(tool, ToolId::Rectangle | ToolId::Ellipse | ToolId::Polygon | ToolId::Star) { + self.default_props.shape.clone() + } else { + None + }; self.preview(|doc, sel| { let (mut a, mut b) = (start, p); if pixel { @@ -89,6 +96,10 @@ impl Session { n.transform = pw.inverse() * Affine::translate((r.x0, r.y0)); } doc.insert(n, parent, None)?; + if let Some(d) = &defaults { + // Best effort: a default the shape can't take leaves it as drawn. + let _ = crate::cmd::edit::apply_copied_props("edit.setDefaultProperties", doc, nid, d); + } *sel = vec![nid]; created = Some(nid); let _ = page; diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 700fa7414..a0652e4c0 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -17,6 +17,7 @@ mod clipboard; mod props; mod select; +pub(crate) use clipboard::apply_copied_props; pub use clipboard::{CLIP_CLOSE, CLIP_OPEN, copy_to_clipboard, design_clipboard_buffer, paste_into}; use clipboard::{copy, copy_props, copy_props_of, cut, paste, paste_design_layers, paste_over, paste_props, paste_replace}; use props::{ @@ -142,12 +143,26 @@ pub fn specs() -> Vec { true, find_replace ), - spec!("edit.setDefaultProperties", "Set default properties", "{id?}", false, |s, p| { - let id = targets(s, p).first().copied().ok_or_else(|| bad("edit.setDefaultProperties", "select a layer"))?; - let v = copy_props_of(s.doc()?, id); - s.clipboard.props = Some(v); - ok() - }), + spec!( + "edit.setDefaultProperties", + "Set default properties", + "{id?} the layer's fills, strokes, effects, opacity and corners (a text layer's: also its font) become what new rectangles, ellipses, polygons and stars (or, from a text layer, new text) drawn with the tools take → {for: shapes|text, properties}", + false, + |s, p| { + let id = targets(s, p).first().copied().ok_or_else(|| bad("edit.setDefaultProperties", "select a layer"))?; + let doc = s.doc()?; + let text = matches!(doc.get(id)?.kind, NodeKind::Text(_)); + let v = copy_props_of(doc, id); + let kind = if text { + s.default_props.text = Some(v.clone()); + "text" + } else { + s.default_props.shape = Some(v.clone()); + "shapes" + }; + Ok(json!({"for": kind, "properties": v})) + } + ), spec!("select.set", "Select", "{ids: [..]} (replace the selection)", false, |s, p| { let ids = match get(p, "ids") { Some(Value::Array(a)) => a.iter().filter_map(id_of).collect(), diff --git a/crates/engine/src/cmd/edit/clipboard.rs b/crates/engine/src/cmd/edit/clipboard.rs index 546aa863c..150a3b577 100644 --- a/crates/engine/src/cmd/edit/clipboard.rs +++ b/crates/engine/src/cmd/edit/clipboard.rs @@ -357,21 +357,27 @@ pub(super) fn copy_props(s: &mut Session, p: &Value) -> Result { Ok(v) } +/// Give layer `id` the properties [`copy_props_of`] copied (`props`), those it can take: the text +/// properties only to text, the corners only to a layer with corners. +pub(crate) fn apply_copied_props(cmd: &str, doc: &mut Document, id: NodeId, props: &Value) -> Result<()> { + let mut m = props.as_object().cloned().unwrap_or_default(); + let is_text = matches!(doc.get(id)?.kind, NodeKind::Text(_)); + if !is_text { + m.retain(|k, _| !k.starts_with("font") && k != "lineHeight" && k != "letterSpacing"); + } + if !doc.get(id)?.kind.has_corner_radius() { + m.remove("cornerRadius"); + m.remove("cornerSmoothing"); + } + crate::cmd::props::apply(cmd, doc, id, &m) +} + pub(super) fn paste_props(s: &mut Session, p: &Value) -> Result { let props = s.clipboard.props.clone().ok_or_else(|| EngineError::Disabled("edit.pasteProperties".into(), "no copied properties".into()))?; let ids = req_targets("edit.pasteProperties", s, p)?; let doc = s.doc_mut()?; for i in ids { - let mut m = props.as_object().cloned().unwrap_or_default(); - let is_text = matches!(doc.get(i)?.kind, NodeKind::Text(_)); - if !is_text { - m.retain(|k, _| !k.starts_with("font") && k != "lineHeight" && k != "letterSpacing"); - } - if !doc.get(i)?.kind.has_corner_radius() { - m.remove("cornerRadius"); - m.remove("cornerSmoothing"); - } - crate::cmd::props::apply("edit.pasteProperties", doc, i, &m)?; + apply_copied_props("edit.pasteProperties", doc, i, &props)?; } ok() } diff --git a/crates/engine/src/default_props_tests.rs b/crates/engine/src/default_props_tests.rs new file mode 100644 index 000000000..ea5d16293 --- /dev/null +++ b/crates/engine/src/default_props_tests.rs @@ -0,0 +1,117 @@ +//! Edit ▸ Set default properties (#2028): new rectangles, ellipses, polygons and stars drawn with +//! the tools take the properties of the layer it was set from, and new text takes a text layer's; +//! it no longer only copied them for Paste properties. + +use figcraft_color::Color; +use figcraft_doc::{Node, NodeId, NodeKind}; +use serde_json::{Value, json}; + +use crate::Session; +use crate::params::id_of; +use crate::tools::{PointerEvent, PointerKind, ToolId}; + +/// Run `cmd`, failing the test on an error. +fn ex(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +/// The layer `id` as it is now. +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().node(id).unwrap().clone() +} + +/// Draw with `tool` from `a` to `b` (a click when they're equal); the new layer. +fn draw(s: &mut Session, tool: ToolId, a: (f64, f64), b: (f64, f64)) -> NodeId { + s.set_tool(tool); + s.pointer(&PointerEvent::at(PointerKind::Down, a.0, a.1, 1.0)).unwrap(); + if a != b { + s.pointer(&PointerEvent::at(PointerKind::Move, (a.0 + b.0) / 2.0, (a.1 + b.1) / 2.0, 1.0)).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::Move, b.0, b.1, 1.0)).unwrap(); + } + s.pointer(&PointerEvent::at(PointerKind::Up, b.0, b.1, 1.0)).unwrap(); + *s.selection().first().unwrap() +} + +/// The first solid fill's colour of layer `n`. +fn fill(n: &Node) -> Option { + n.fills.first().and_then(|p| p.solid_color()) +} + +/// A red, half-transparent rectangle with a 4 pt blue stroke and 12 pt corners. +fn styled(s: &mut Session) -> NodeId { + let id = id_of(&ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"]).unwrap(); + ex(s, "node.set", json!({"id": id, "props": {"fill": "#FF0000", "stroke": "#0000FF", "strokeWeight": 4, "opacity": 0.5, "cornerRadius": 12}})); + id +} + +/// Rectangles, ellipses, polygons and stars drawn or clicked with their tools take the shape +/// defaults (corners only where a shape has them, its own drawn size); frames, lines and layers made +/// by commands keep their own look; undo takes a drawn shape away whole. +#[test] +fn new_shapes_drawn_with_the_tools_take_the_default_properties() { + let mut s = Session::new(); + let source = styled(&mut s); + let set = ex(&mut s, "edit.setDefaultProperties", json!({"id": source})); + assert_eq!(set["for"], "shapes"); + let red = Some(Color::from_hex("#FF0000").unwrap()); + // Dragged and clicked (a click places a 100×100 shape) alike. + for (tool, a, b) in + [(ToolId::Rectangle, (200.0, 0.0), (300.0, 80.0)), (ToolId::Ellipse, (400.0, 0.0), (400.0, 0.0)), (ToolId::Star, (600.0, 0.0), (660.0, 60.0))] + { + let id = draw(&mut s, tool, a, b); + let n = node(&s, id); + assert_eq!(fill(&n), red, "{tool:?}"); + assert_eq!((n.stroke.weight, n.opacity), (4.0, 0.5), "{tool:?}"); + assert_eq!(n.strokes.first().and_then(|p| p.solid_color()), Some(Color::from_hex("#0000FF").unwrap()), "{tool:?}"); + } + let rect = draw(&mut s, ToolId::Rectangle, (0.0, 200.0), (80.0, 260.0)); + assert_eq!(node(&s, rect).corners.radii, [12.0; 4], "corners go to layers with corners"); + assert_eq!((node(&s, rect).width, node(&s, rect).height), (80.0, 60.0), "the drawn size, not the source's"); + // Frames and lines keep their own look; a shape made by a command too. + let frame = draw(&mut s, ToolId::Frame, (0.0, 400.0), (100.0, 500.0)); + assert_ne!(fill(&node(&s, frame)), red); + let line = draw(&mut s, ToolId::Line, (0.0, 600.0), (100.0, 600.0)); + assert_ne!(node(&s, line).stroke.weight, 4.0); + let made = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 700, "width": 10, "height": 10}))["id"]).unwrap(); + assert_ne!(fill(&node(&s, made)), red); + // Undo takes a drawn shape away whole, defaults included. + let drawn = draw(&mut s, ToolId::Polygon, (800.0, 0.0), (860.0, 60.0)); + ex(&mut s, "edit.undo", json!({})); + assert!(s.doc().unwrap().node(drawn).is_none()); +} + +/// Setting defaults no longer overwrites what Copy properties copied. +#[test] +fn setting_defaults_leaves_the_copied_properties_alone() { + let mut s = Session::new(); + let copied = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"]).unwrap(); + ex(&mut s, "node.set", json!({"id": copied, "props": {"fill": "#00FF00"}})); + ex(&mut s, "edit.copyProperties", json!({"id": copied})); + let source = styled(&mut s); + ex(&mut s, "edit.setDefaultProperties", json!({"id": source})); + let target = id_of(&ex(&mut s, "shape.ellipse", json!({"x": 0, "y": 100, "width": 50, "height": 50}))["id"]).unwrap(); + ex(&mut s, "edit.pasteProperties", json!({"ids": [target]})); + assert_eq!(fill(&node(&s, target)), Some(Color::from_hex("#00FF00").unwrap()), "Paste properties pastes what was copied"); +} + +/// A text layer sets the defaults of new text (its font and fills, laid out at that size), and the +/// shapes' defaults stay as they were. +#[test] +fn new_text_takes_a_text_layers_defaults_and_shapes_keep_theirs() { + let mut s = Session::new(); + let shape = styled(&mut s); + ex(&mut s, "edit.setDefaultProperties", json!({"id": shape})); + let text = id_of(&ex(&mut s, "text.create", json!({"text": "Title", "x": 0, "y": 200}))["id"]).unwrap(); + ex(&mut s, "node.set", json!({"id": text, "props": {"fontSize": 32, "fill": "#008000"}})); + let set = ex(&mut s, "edit.setDefaultProperties", json!({"id": text})); + assert_eq!(set["for"], "text"); + let id = draw(&mut s, ToolId::Text, (300.0, 300.0), (300.0, 300.0)); + let n = node(&s, id); + let NodeKind::Text(t) = &n.kind else { panic!("a text layer") }; + assert_eq!(t.style.font_size, 32.0); + assert_eq!(fill(&n), Some(Color::from_hex("#008000").unwrap())); + assert!(n.height > 30.0, "laid out at the default size: {}", n.height); + // The shapes' defaults are still the rectangle's. + let rect = draw(&mut s, ToolId::Rectangle, (0.0, 500.0), (80.0, 560.0)); + assert_eq!(fill(&node(&s, rect)), Some(Color::from_hex("#FF0000").unwrap())); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e919444e2..c10de9a23 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -110,7 +110,7 @@ mod view_state; pub use derived::{changed_nodes, normalize}; pub use doc_state::{DocState, History, HistoryEntry, Interaction, PREVIEW_READ_ONLY, Preedit, TextEdit, VersionPreview}; pub use error::{EngineError, Result, bad}; -pub use prefs::{Clipboard, MAX_RECENT_ACTIONS, Prefs, UI_SCALE_MAX, UI_SCALE_MIN, UI_SCALE_SIZES, UiRequest, clamp_ui_scale}; +pub use prefs::{Clipboard, DefaultProps, MAX_RECENT_ACTIONS, Prefs, UI_SCALE_MAX, UI_SCALE_MIN, UI_SCALE_SIZES, UiRequest, clamp_ui_scale}; pub use session::Forward; pub use view_state::ViewState; @@ -119,6 +119,8 @@ pub struct Session { pub docs: Vec, pub active: usize, pub clipboard: Clipboard, + /// Edit ▸ Set default properties: what new shapes and text drawn with the tools take. + pub default_props: DefaultProps, pub prefs: Prefs, /// A command changed a preference that is kept at once (not only when the app quits): the app /// saves the preferences and clears this. @@ -275,6 +277,8 @@ mod dash_cap_tests; #[cfg(test)] mod datafill_tests; #[cfg(test)] +mod default_props_tests; +#[cfg(test)] mod design_paste_tests; #[cfg(test)] mod dev_measurements_tests; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 5c455aa35..48d68a901 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -173,6 +173,18 @@ pub struct UiRequest { pub data: Value, } +/// What Edit ▸ Set default properties keeps: the properties new layers drawn with the tools take, +/// as Copy properties copies them (fills, strokes and their settings, effects, opacity, blend, +/// corners; for text also the font, size, line height and letter spacing). One set for shapes +/// (rectangles, ellipses, polygons and stars), set from any layer but text, and one for text. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct DefaultProps { + /// For new rectangles, ellipses, polygons and stars. + pub shape: Option, + /// For new text. + pub text: Option, +} + /// Clipboard contents (internal; the UI mirrors to the system clipboard). #[derive(Clone, Debug, Default)] pub struct Clipboard { diff --git a/crates/engine/src/session/new.rs b/crates/engine/src/session/new.rs index c7eee09f1..f3b75b630 100644 --- a/crates/engine/src/session/new.rs +++ b/crates/engine/src/session/new.rs @@ -14,6 +14,7 @@ impl Session { docs: Vec::new(), active: 0, clipboard: Clipboard::default(), + default_props: Default::default(), prefs: Prefs::default(), prefs_unsaved: false, tool: tools::ToolState::default(), diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d98a6ed73..5489ecbb3 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** patch (a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** patch (Edit ▸ Set default properties now gives new shapes and text drawn with the tools the selected layer's fills, strokes, effects, opacity and corners (text: its font) instead of only copying them for Paste properties (#2028); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -73,6 +73,7 @@ interaction feel not yet compared. | Numeric fields: arithmetic, scrubbing by dragging the label, mixed values | done | Numeric panels use `widgets::number_field`; Corner smoothing has an original code-drawn icon, a 24 pt drag target and an accessible name, with live changes, fractional values preserved across consecutive drags, Shift/Alt rates, 0–100% clamping and one-step undo/redo (`corner_individual_tests`); Typography line height, letter spacing and paragraph spacing share its leading-icon scrub logic (#373), retaining their existing unit parsing, Auto/Mixed values, variable chips and selected-character targeting (`typography_scrub_tests`). Scrubbing the label: a step a point (1 px; 1% of opacity, 1° of rotation), ten with Shift, a tenth with Alt, each stretch at the rate held while it was dragged, one undo step when let go; past the edge of the screen it goes on where the platform reports the mouse's own motion (desktop), otherwise it stops there. Arrow keys: Up/Down step a pixel field by the small nudge and Shift by the big nudge (the preferences), other fields by their own step and ten of it; they work while typing (from what is typed) and with the keyboard on the field. Typing: `+ - * /`, brackets, units (`px`, `°`, `%`, `x`, `ms`), a decimal comma; `+10`, `*2`, `/4` are relative to the value, and `50%`, `+10%`, `-10%` too in a field that isn't a percentage. Enter, Tab or a click elsewhere commits (Tab and Shift+Tab move to the next and previous control), Escape restores; a field left as it was commits nothing (no undo step, and a rounded display isn't written back). Mixed values show "Mixed": a number sets them all, a relative edit or an arrow key goes to each layer from its own value in one undo step, for X, Y, W, H, rotation, opacity, corner radius and stroke weight (elsewhere `+10` on Mixed sets 10 and `*2` does nothing) (`field_tests`). Left: scrubbing a Mixed field (nothing happens), `x2`-style suffix edits, the pointer isn't wrapped to the other side of the screen; rates not compared with Figma's | | Transform box at small sizes | done | a press inside a layer smaller than its handles moves it, the nearest handle wins, handles answer just outside and are hidden under 16 px on screen; cursors follow each handle and the box's rotation | | Locked layers | done | selectable from the layers panel; no handles, not dragged with the rest of a selection | +| Edit ▸ Set default properties: new layers take the selected layer's properties | done | from a shape (any layer but text): new rectangles, ellipses, polygons and stars drawn or clicked with their tools take its fills, strokes and their settings, effects, opacity, blend and corners; from a text layer: new text from the Text tool takes its fills and font (#2028). Silent in the help center on frames, lines and arrows: they keep their own look, as do layers made by commands; the defaults last for the session | | Smart selection spacing | partial | with layers in a row, a column or an aligned grid selected, the Layout section shows horizontal and vertical spacing ("Mixed" until set; typed, scrubbed, fractional and negative) and pink handles in the gaps on the canvas drag them, one undo step, Escape cancels (`arrange.spacing`; sizes, parents and offsets within each track kept; at most 2,000 layers; flow children, locked layers and layers inside instances left out). A ring at each layer's centre drags it to another place in a regular row, column or complete top-left-aligned grid: the others close up and make room around it with the gaps kept, and with Cmd/Ctrl held the two layers swap places instead, previewed live while dragging (`selection_reorder_tests`; no ring on a layer under 16 px on screen). Not covered: reordering irregular grids, and several marked layers moved together. Checked by its author on macOS and in the app on Windows (#402) | | Selection colors | partial | for a mixed selection the Design panel lists their solid and gradient paints (children and text ranges included; hidden paints, masks, images, patterns and boolean operands left out; styles and variables listed apart): editing a colour changes every matching fill and stroke in one undo step, a row selects the layers that use it or applies a color style or color variable of the document, and a row linked to a style or variable detaches it, keeping the color (`selection.colors`, `selection.setPaint`, `selection.applyColorStyle`, `selection.bindColorVariable`, `selection.detachColor`, `selection.selectColor`). No library styles or variables from there, and no new style or variable from a row (#403) | | Keyboard box selection | done | Alt+Space on macOS, Ctrl+Space on Windows and Linux, or F8 (`select.area`): a box around the selection or in the middle of the view; arrows move it, Cmd/Ctrl+arrows or Shift+arrows size it (Shift with Cmd/Ctrl: farther), Enter selects like a marquee (Shift+Enter toggles, Cmd/Ctrl+Enter nested), Escape closes | @@ -178,6 +179,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-06 | patch | M1, #2028: Edit ▸ Set default properties copied the selected layer's properties into the Paste properties clipboard and nothing else, so a new rectangle drawn afterwards was still grey (and what Copy properties had copied was lost). The defaults are now kept apart (`Session::default_props`, one set for shapes and one for text): rectangles, ellipses, polygons and stars drawn or clicked with their tools take the shape defaults (`apply_copied_props`, the same rules as Paste properties: corners only where a layer has them), and new text from the Text tool takes a text layer's fills and font and is laid out at that size. Frames, sections, slices, lines, arrows, vectors and layers made by commands keep their own look. `edit.setDefaultProperties` answers `{for: shapes|text, properties}`. Tests: `default_props_tests` (3) | | 2026-11-04 | patch | M1, #1852: a press on one of the open gradient's handles or stops on the canvas is the colour picker's own, not a press outside it (Figma keeps the picker and the handles up while a handle or stop is dragged; the stops are made to be dragged: "You can click and drag a stop to change its placement on the gradient", Use gradients as a fill or stroke). The canvas took the press and began the drag, then the picker, drawn later in the same frame, saw a press outside its card and closed, committing the drag's interaction at once; the handles vanished with it and the drag went on without an undo step of its own. Now the picker stays while a gradient handle or stop drags, and the drag is one undo step; a press elsewhere on the canvas still closes it. A handle drag whose button goes up off the canvas (over a panel or the picker) ends there too, instead of waiting, uncommitted, to move the handle to the next press on the canvas. Tests: `colorpicker_selection_tests::dragging_a_gradient_handle_on_the_canvas_keeps_the_picker_open`, `colorpicker_selection_tests::a_gradient_drag_released_off_the_canvas_ends_there`. | | 2026-11-02 | patch | M8, #1875: a click with the Bend tool on a sharp point between two segments gives it handles along the line between its neighbours, a third of the way to each ("Click on a point or path where you want to add a curve", Edit vector layers); a click on a curved point still makes it sharp, a drag still sets the handles by hand, an endpoint is left alone. Between a handle's end and a point both within reach of the pointer, the nearer one on the page is hit (the handle on a tie), so a short path's point (its handles a few pixels long) can be clicked again. Before, only a drag curved a point, and a short one left two tiny handles in its direction. Tests: `vectoredit::tests::short_handles_leave_their_point_clickable`, `vectoredit::tests::a_bend_click_curves_a_sharp_point_between_its_neighbours`, `bend_tool_smooths_and_sharpens_points`. Numbers unchanged. | | 2026-11-02 | minor | M4, #1827: wrap style on a text layer (`WrapStyle`: Auto, Balance, Pretty): Balance re-breaks each paragraph at the narrowest width that keeps its line count (bisection over the greedy breaker, as browsers balance), Pretty narrows one of the last four lines just enough so the last line isn't one word; `text.wrapStyle`, `node.set wrapStyle` (`textWrap` too), inspect `wrapStyle`, Dev Mode CSS `text-wrap` (Tailwind `text-balance` / `text-pretty`), the Type settings control under Vertical trim. Per-paragraph settings, text-style support and the `.fig` import/export mapping stay open. Test: `text_behaviour_tests::balance_and_pretty_wrap_styles_break_lines_as_documented`. | From bcc3facdceddd5c1296ffd15129eb8bb2a2da4d9 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 7 Nov 2026 07:52:58 +0700 Subject: [PATCH 095/102] Local variables: work out a row's group list only when its menu is open --- crates/ui-egui/src/dialogs/variables_panel.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/variables_panel.rs b/crates/ui-egui/src/dialogs/variables_panel.rs index 4ffcf77d3..d0a0cc6bc 100644 --- a/crates/ui-egui/src/dialogs/variables_panel.rs +++ b/crates/ui-egui/src/dialogs/variables_panel.rs @@ -836,11 +836,10 @@ fn var_row(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, v: &Va if !inherited && resp.double_clicked() && ui.input(|i| i.pointer.interact_pos()).is_some_and(|p| p.x < name_r.max.x) { start_rename(st, target.clone()); } - let bulk = bulk_ids(view, st, v); - let coll_groups = groups(view.in_collection(&coll.id).map(|x| x.name.as_str())); crate::right::context_popup(&resp).show(|ui| { - if let Some(vars) = &bulk { - bulk_menu(app, ui, &coll_groups, vars); + if let Some(vars) = bulk_ids(view, st, v) { + let coll_groups = groups(view.in_collection(&coll.id).map(|x| x.name.as_str())); + bulk_menu(app, ui, &coll_groups, &vars); return; } if menu_item(ui, tr("Edit variable"), "") { From cf1fed3332c2a55bb6fea6d0c68c6836b43b0ce2 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 7 Nov 2026 07:58:49 +0700 Subject: [PATCH 096/102] Spanish labels for the text direction commands --- crates/ui-egui/locales/es.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/ui-egui/locales/es.toml b/crates/ui-egui/locales/es.toml index b9e004dd0..96183d523 100644 --- a/crates/ui-egui/locales/es.toml +++ b/crates/ui-egui/locales/es.toml @@ -2318,6 +2318,10 @@ status = "draft — needs native review" "text.caseUpper" = "Mayúsculas" "text.create" = "Texto" "text.decoration" = "Decoración" +"text.direction" = "Dirección del texto" +"text.directionAuto" = "Dirección del texto: automática" +"text.directionLtr" = "Dirección del texto: de izquierda a derecha" +"text.directionRtl" = "Dirección del texto: de derecha a izquierda" "text.edit.begin" = "Editar texto" "text.edit.caret" = "Colocar el cursor de texto" "text.edit.end" = "Dejar de editar el texto" From 85a11f04094fe72d3ead4812db8db91cb4791b97 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 7 Nov 2026 07:58:55 +0700 Subject: [PATCH 097/102] Spanish label for tool.crosshair --- crates/ui-egui/locales/es.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/locales/es.toml b/crates/ui-egui/locales/es.toml index b9e004dd0..466decb0e 100644 --- a/crates/ui-egui/locales/es.toml +++ b/crates/ui-egui/locales/es.toml @@ -2365,6 +2365,7 @@ status = "draft — needs native review" "tool.arrow" = "Flecha" "tool.comment" = "Comentario" "tool.connector" = "Conector" +"tool.crosshair" = "Mover la cruz de colocación" "tool.ellipse" = "Elipse" "tool.eraser" = "Borrador" "tool.frame" = "Marco" From fb33f78269c06fad868f0d9ebb61347ff63dc358 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 7 Nov 2026 08:17:37 +0700 Subject: [PATCH 098/102] Text styles: a style with no paragraph values keeps a bulleted text linked --- crates/engine/src/cmd/styles.rs | 7 ++++++- crates/engine/src/styles_behaviour_tests.rs | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index ff7838108..61f2c265f 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -782,7 +782,12 @@ pub fn sync_text_styles(doc: &mut Document, ids: &[NodeId]) { let gone: Vec<(usize, usize)> = t2 .spans() .iter() - .filter(|(a, b, s)| s.style_id.as_deref().is_some_and(|sid| paras.get(sid).is_none_or(|ps| !t2.shows_paragraph_style_in(*a, *b, ps)))) + .filter(|(a, b, s)| { + // A style with no paragraph values (every style in older files) asks nothing of them. + s.style_id + .as_deref() + .is_some_and(|sid| paras.get(sid).is_none_or(|ps| **ps != ParagraphStyle::default() && !t2.shows_paragraph_style_in(*a, *b, ps))) + }) .map(|(a, b, _)| (*a, *b)) .collect(); for (a, b) in gone { diff --git a/crates/engine/src/styles_behaviour_tests.rs b/crates/engine/src/styles_behaviour_tests.rs index f1ebd96de..73fe1edef 100644 --- a/crates/engine/src/styles_behaviour_tests.rs +++ b/crates/engine/src/styles_behaviour_tests.rs @@ -473,3 +473,21 @@ fn descriptions_and_library_styles() { run(&mut s, "style.update", json!({"style": st, "description": "Body text"})); assert_eq!(s.doc().unwrap().style(&st).unwrap().description, "Body text"); } + +#[test] +fn a_style_without_paragraph_values_keeps_a_bulleted_text_linked() { + // Styles from older files set no paragraph values, so a list or spacing on their text isn't + // an edit of the style: it stays linked (docs silent, pinned to how such files worked). + let mut s = Session::new(); + let t = text(&mut s, 0.0); + run( + &mut s, + "node.set", + json!({"id": t, "props": {"characters": "A +B"}}), + ); + let st = sid(run(&mut s, "style.create", json!({"type": "text", "name": "Plain", "value": {"fontSize": 11}}))); + run(&mut s, "style.apply", json!({"ids": [t], "style": st})); + run(&mut s, "node.set", json!({"id": t, "props": {"listStyle": "bulleted", "paragraphSpacing": 6}})); + assert_eq!(node(&s, t).styles.text.as_deref(), Some(st.as_str())); +} From acbc988225753c6f7552f6b85884ff71e562e428 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 7 Nov 2026 08:48:40 +0700 Subject: [PATCH 099/102] Schema test: its field ids no longer repeat, now that repeats are refused --- crates/format/src/fig/interop_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/format/src/fig/interop_tests.rs b/crates/format/src/fig/interop_tests.rs index fa95d792b..4ad81cebc 100644 --- a/crates/format/src/fig/interop_tests.rs +++ b/crates/format/src/fig/interop_tests.rs @@ -403,10 +403,10 @@ fn the_schema_numbers_what_the_format_numbers() { #[test] fn schema_text_takes_numbers_and_refuses_bad_ones() { - let s = Schema::parse("enum E A=3 B C=9\nmessage M uint a=7, E b, string c=2").unwrap(); + let s = Schema::parse("enum E A=3 B C=9\nmessage M uint a=7, E b, string c=5").unwrap(); let values = |i: usize| s.defs[i].fields.iter().map(|f| (f.name.as_str(), f.value)).collect::>(); assert_eq!(values(0), [("A", 3), ("B", 1), ("C", 9)]); - assert_eq!(values(1), [("a", 7), ("b", 2), ("c", 2)]); + assert_eq!(values(1), [("a", 7), ("b", 2), ("c", 5)]); for bad in ["enum E A=", "enum E A=x", "enum E A=-1", "message M uint a=1.5", "message M uint a=99999999999", "enum E =", "message M uint ="] { assert!(Schema::parse(bad).is_err() || bad.ends_with('='), "{bad}"); } From bc55ca1463830fe680b8f7e62b1be29e98e681fb Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 6 Nov 2026 20:59:35 -0500 Subject: [PATCH 100/102] Local variables: the bulk menu scrolls when it is taller than the window (#2002) The Move-to-group and Scope rows now sit in a vertical ScrollArea capped at 60% of the screen height, so a collection with many groups no longer pushes rows past the window. The test harness gains a settable screen size. Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/dialogs/variables_panel.rs | 70 ++++++++++--------- crates/ui-egui/src/layers_drag_tests.rs | 6 +- crates/ui-egui/src/variables_select_tests.rs | 58 +++++++++++++++ 3 files changed, 100 insertions(+), 34 deletions(-) diff --git a/crates/ui-egui/src/dialogs/variables_panel.rs b/crates/ui-egui/src/dialogs/variables_panel.rs index d0a0cc6bc..1a2a79151 100644 --- a/crates/ui-egui/src/dialogs/variables_panel.rs +++ b/crates/ui-egui/src/dialogs/variables_panel.rs @@ -119,41 +119,47 @@ fn bulk_menu(app: &mut FigApp, ui: &mut Ui, coll_groups: &[String], vars: &[&Var bulk_run(app, "Delete variables", vars, |v| Some(("variable.delete", json!({"variable": v.id})))); ui.close(); } - let moves = std::iter::once(None).chain(coll_groups.iter().map(|g| Some(g.as_str()))); - for g in moves { - let label = g.map_or_else(|| tr("Move out of any group").to_string(), |g| trf("Move to group {group}", &[("group", &g)])); - if menu_item(ui, &label, "") { - bulk_run(app, "Move variables", vars, |v| { - let short = v.name.rsplit('/').next().unwrap_or(&v.name); - let name = g.map_or_else(|| short.to_string(), |g| format!("{g}/{short}")); - (name != v.name).then(|| ("variable.update", json!({"variable": v.id, "name": name}))) - }); - ui.close(); - } - } - let mut scopes: Vec<(&'static str, &'static str)> = Vec::new(); - for v in vars { - for s in scopes_for(v.kind) { - if !scopes.contains(s) { - scopes.push(*s); + // Many groups make the menu taller than the window: the rows after Delete scroll. + let max_h = ui.ctx().content_rect().height() * 0.6; + egui::ScrollArea::vertical().id_salt("variables_bulk_menu_scroll").max_height(max_h).show(ui, |ui| { + let moves = std::iter::once(None).chain(coll_groups.iter().map(|g| Some(g.as_str()))); + for g in moves { + let label = g.map_or_else(|| tr("Move out of any group").to_string(), |g| trf("Move to group {group}", &[("group", &g)])); + if menu_item(ui, &label, "") { + bulk_run(app, "Move variables", vars, |v| { + let short = v.name.rsplit('/').next().unwrap_or(&v.name); + let name = g.map_or_else(|| short.to_string(), |g| format!("{g}/{short}")); + (name != v.name).then(|| ("variable.update", json!({"variable": v.id, "name": name}))) + }); + ui.close(); } } - } - let set = |app: &mut FigApp, label: &str, value: Option<&'static str>, ui: &mut Ui| { - if menu_item(ui, label, "") { - bulk_run(app, "Change scope", vars, |v| match value { - None => Some(("variable.update", json!({"variable": v.id, "scopes": Value::Null}))), - Some("") => Some(("variable.update", json!({"variable": v.id, "scopes": []}))), - Some(s) => scopes_for(v.kind).iter().any(|(id, _)| *id == s).then(|| ("variable.update", json!({"variable": v.id, "scopes": [s]}))), - }); - ui.close(); + let mut scopes: Vec<(&'static str, &'static str)> = Vec::new(); + for v in vars { + for s in scopes_for(v.kind) { + if !scopes.contains(s) { + scopes.push(*s); + } + } } - }; - set(app, tr("Scope: all supported properties"), None, ui); - set(app, tr("Scope: hidden from pickers"), Some(""), ui); - for (id, label) in scopes { - set(app, &trf("Scope: only {scope}", &[("scope", &tr(label))]), Some(id), ui); - } + let set = |app: &mut FigApp, label: &str, value: Option<&'static str>, ui: &mut Ui| { + if menu_item(ui, label, "") { + bulk_run(app, "Change scope", vars, |v| match value { + None => Some(("variable.update", json!({"variable": v.id, "scopes": Value::Null}))), + Some("") => Some(("variable.update", json!({"variable": v.id, "scopes": []}))), + Some(s) => { + scopes_for(v.kind).iter().any(|(id, _)| *id == s).then(|| ("variable.update", json!({"variable": v.id, "scopes": [s]}))) + } + }); + ui.close(); + } + }; + set(app, tr("Scope: all supported properties"), None, ui); + set(app, tr("Scope: hidden from pickers"), Some(""), ui); + for (id, label) in scopes { + set(app, &trf("Scope: only {scope}", &[("scope", &tr(label))]), Some(id), ui); + } + }); } impl Editor { diff --git a/crates/ui-egui/src/layers_drag_tests.rs b/crates/ui-egui/src/layers_drag_tests.rs index 978a3b236..f1d644778 100644 --- a/crates/ui-egui/src/layers_drag_tests.rs +++ b/crates/ui-egui/src/layers_drag_tests.rs @@ -13,11 +13,13 @@ pub(crate) struct Ui { pub(crate) ctx: egui::Context, pub(crate) app: FigApp, time: f64, + /// The test screen's size (1440 x 900 unless a test shrinks it). + pub(crate) screen: egui::Vec2, } impl Ui { pub(crate) fn new(s: Session) -> Self { - let mut u = Self { ctx: egui::Context::default(), app: FigApp::new(s, Box::new(NoServices)), time: 0.0 }; + let mut u = Self { ctx: egui::Context::default(), app: FigApp::new(s, Box::new(NoServices)), time: 0.0, screen: vec2(1440.0, 900.0) }; for _ in 0..3 { u.frame(vec![]); } @@ -44,7 +46,7 @@ impl Ui { pub(crate) fn frame_raw(&mut self, raw: RawInput) -> egui::FullOutput { self.time += 1.0 / 60.0; self.app.clock.set_test_now(Some(self.time)); - let input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), time: Some(self.time), ..raw }; + let input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, self.screen)), time: Some(self.time), ..raw }; let app = &mut self.app; let mut out = self.ctx.run_ui(input, |ui| app.ui(ui)); out.textures_delta.clear(); diff --git a/crates/ui-egui/src/variables_select_tests.rs b/crates/ui-egui/src/variables_select_tests.rs index 55062db96..b391df326 100644 --- a/crates/ui-egui/src/variables_select_tests.rs +++ b/crates/ui-egui/src/variables_select_tests.rs @@ -192,3 +192,61 @@ fn a_row_outside_the_selection_keeps_the_single_variable_menu() { let menu = flat(&u.frame_output(vec![]).shapes); assert!(has_text(&menu, "Delete variable") && !has_text(&menu, "Delete 2 variables")); } + +/// The bounding rect of every popup layer (the menu's area). +fn popup_rect(u: &Ui) -> egui::Rect { + u.ctx.memory(|m| { + let rects: Vec = + m.areas().visible_layer_ids().into_iter().filter(|l| l.order == egui::Order::Foreground).filter_map(|l| m.area_rect(l.id)).collect(); + assert!(!rects.is_empty(), "no popup open"); + rects.into_iter().reduce(|a, b| a.union(b)).unwrap() + }) +} + +#[test] +fn the_bulk_menu_scrolls_when_forty_groups_make_it_taller_than_the_window() { + let mut u = window(); + for g in 0..40 { + u.app + .session + .execute("variable.create", &json!({"collection": "Theme", "name": format!("g{g:02}/leaf"), "type": "number", "value": 0})) + .unwrap(); + } + u.screen = egui::vec2(1000.0, 500.0); + for _ in 0..5 { + u.frame(vec![]); + } + click_row(&mut u, "bravo", Modifiers::NONE); + click_row(&mut u, "charlie", SHIFT); + let p = row(&mut u, "charlie"); + click(&mut u, p, PointerButton::Secondary, Modifiers::NONE); + let menu = flat(&u.frame_output(vec![]).shapes); + assert!(has_text(&menu, "Delete 2 variables")); + let screen = egui::Rect::from_min_size(Pos2::ZERO, u.screen); + let area = popup_rect(&u); + assert!(screen.contains_rect(area), "the menu area {area:?} runs past the screen {screen:?}"); + let last = "Move to group g39"; + let screen_h = u.screen.y; + let visible = |shapes: &[egui::Shape]| crate::live_tests::texts(shapes).iter().any(|(t, p, s)| t == last && p.y + s.y <= screen_h); + assert!(!visible(&menu), "the last group row should start out of view"); + let at = Pos2::new(area.center().x, area.center().y); + let mut shapes = menu; + for _ in 0..30 { + u.frame(vec![ + Event::PointerMoved(at), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + source: egui::MouseWheelSource::Unknown, + phase: egui::TouchPhase::Move, + delta: egui::vec2(0.0, -400.0), + modifiers: Modifiers::NONE, + }, + ]); + shapes = flat(&u.frame_output(vec![Event::PointerMoved(at)]).shapes); + if visible(&shapes) { + break; + } + } + assert!(visible(&shapes), "scrolling the menu never brought {last:?} into view"); + assert!(screen.contains_rect(popup_rect(&u))); +} From fd1a78bbb8cecbcd7572c2f618d51df940cfa716 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 6 Nov 2026 21:41:58 -0500 Subject: [PATCH 101/102] Local variables: the docs say bulk actions skip inherited variables (#2002) Delete, Move to group and Scope act on the selected local variables; inherited ones are left out and the bulk menu needs two or more local variables selected. Co-Authored-By: Claude Fable 5.1 --- ROADMAP.md | 4 ++-- docs/components-parity.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 8237d3ffa..d0a79f1bc 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on all of them in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; 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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); 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; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -132,7 +132,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). ## Progress log -- **2026-11-05** · M3, #2002: the Local variables window selects several variables with a click, Shift+click (range) and Cmd/Ctrl+click (toggle), cleared by Escape or a click on the empty space; delete, move to a group and scope act on the whole selection as one undo step (`command.batch`). Rename and value edits stay single-row. +- **2026-11-05** · M3, #2002: the Local variables window selects several variables with a click, Shift+click (range) and Cmd/Ctrl+click (toggle), cleared by Escape or a click on the empty space; delete, move to a group and scope act on the selected local variables as one undo step (`command.batch`); inherited variables can be selected but are left out, since they change in their own collection, and the bulk menu needs two or more local variables selected (otherwise the row shows its own menu). Rename and value edits stay single-row. - **2026-11-05** · M10, #2014: the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic (`bidi::script_fallbacks`: one sample letter per script, the system's families for each; Bengali and Thai keep `crate::cjk`'s choice), so a layer name or a String variable's Amharic value draws in the panels instead of boxes. Test: `bidi::tests::other_scripts_take_an_installed_system_face`. - **2026-11-05** · M4, #1830: a paragraph's base direction can be forced (Text ▸ Text direction: Auto, Left to right, Right to left) as Add right-to-left text says ("controls are available to override text direction per paragraph"). `ParaList::direction`, `text.direction {direction, ids?}` and the three menu commands (the edited paragraphs while editing, else the layer's), `node.set textDirection`, the Type settings control once a right-to-left script is in the text, `textDirection` / `lineDirections` in inspect, the CSS `direction`, and the `.fig` lines' `sourceDirectionality` in and out. Layout gives each paragraph its base level (`Bidi::of` per paragraph). Tests: `text_behaviour_tests::text_direction_is_forced_per_paragraph`, `fig::text_direction_tests`. - **2026-11-05** · M1, #2003: the Design panel's Boolean groups menu leads Union, Subtract, Intersect and Exclude with original icons drawn in code from rectangles and polygons (two offset squares, the result filled at reduced alpha); each entry still runs its command. diff --git a/docs/components-parity.md b/docs/components-parity.md index 9551b9eca..d6b1ee5e6 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -1,6 +1,6 @@ # Components, variants, styles and variables parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on all of them in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) Design systems are why teams adopt Figma. **Components: breadth ~96%, ready ~72%. Styles and variables: breadth ~95%, ready ~76% (estimated).** QA'd with a synthetic design system of ~300 @@ -79,7 +79,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| -| 2026-11-05 | minor | M3, #2002: the Local variables window selects several variables, as the Layers panel selects layers. A click selects one row, Shift+click the range from the anchor through the rows shown, Cmd/Ctrl+click toggles a row, Escape or a click on the empty space below the rows clears; selected rows use the sidebar's selected-row colour. Right-clicking a row that is part of a selection of several offers Delete, Move to group and Scope (all supported properties, hidden from pickers, or only one scope) for the whole selection, each sent as one `command.batch`, so one undo step; no engine command changed. Renaming and value edits stay single-row. Tests: `variables_select_tests` (headless UI). Grade unchanged | +| 2026-11-05 | minor | M3, #2002: the Local variables window selects several variables, as the Layers panel selects layers. A click selects one row, Shift+click the range from the anchor through the rows shown, Cmd/Ctrl+click toggles a row, Escape or a click on the empty space below the rows clears; selected rows use the sidebar's selected-row colour. Right-clicking a row that is part of a selection of several offers Delete, Move to group and Scope (all supported properties, hidden from pickers, or only one scope) for the selected local variables, each sent as one `command.batch`, so one undo step; no engine command changed. Renaming and value edits stay single-row. Tests: `variables_select_tests` (headless UI). Grade unchanged | | 2026-11-02 | minor | M3, #1829: text styles carry paragraph spacing and indent, the list style and the OpenType features ("Supported in text styles": "Paragraph spacing and indentation", "Lists", "OpenType features", Create and apply text styles) beside the character properties: `style.create` takes them from the layer (or the selected paragraphs' list) or from a `value` (`paragraphSpacing`, `paragraphIndent`, `listStyle`, `features`), `style.apply` sets them (on a range, the list goes to the paragraphs touched; the rest is the layer's, as in Figma), `style.update` moves them on every linked layer, editing one on a styled text unlinks it as editing its font does, the style editor lists them, and a `.fig` file keeps them with the style (its sample layer). Grade unchanged. | | 2026-11-06 | patch | M3: a glass's light angle bound to a number past ±180 turns round to the same direction (270 is -90), as the angle drawn from it does, instead of stopping at 180. Tests: `effects_tests::a_bound_light_angle_turns_round_instead_of_stopping`. Grade unchanged. | | 2026-11-06 | patch | M3: a layer's effect binding (`variable.bind`, `effects//`) takes only a field its effect has, as an effect style's does: `effects/0/refraction` on a drop shadow, or a binding on an effect the layer doesn't have, is refused instead of being kept and doing nothing (a binding an older file has there still does nothing, and unbinds). Tests: `binding_lists_tests::a_layer_binds_only_fields_its_effects_have`. Grade unchanged. | From 0257f53bb97b36d46a981b8df3987d932949b71c Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 6 Nov 2026 21:55:50 -0500 Subject: [PATCH 102/102] Test: a connector saved with its path starts 4 pt outside its sides, as main's connectors do Co-Authored-By: Claude Fable 5.1 --- crates/format/src/fig/tail_tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/format/src/fig/tail_tests.rs b/crates/format/src/fig/tail_tests.rs index 1255f296d..54ef905e5 100644 --- a/crates/format/src/fig/tail_tests.rs +++ b/crates/format/src/fig/tail_tests.rs @@ -892,7 +892,8 @@ fn an_elbow_connector_saved_with_its_path_keeps_it() { let world = doc.world_transform(named(&doc, "Saved").id); let line: Vec<_> = network_of(&doc, "Saved").vertices.iter().map(|v| world * figcraft_doc::geom::Point::new(v.x, v.y)).map(|p| (p.x, p.y)).collect(); - assert_eq!(line, [(50.0, 700.0), (50.0, 740.0), (200.0, 740.0), (200.0, 850.0), (300.0, 850.0)]); + // Each end starts `END_GAP` (4) outside its side's border. + assert_eq!(line, [(50.0, 704.0), (50.0, 740.0), (200.0, 740.0), (200.0, 850.0), (296.0, 850.0)]); // The fixture's own Link, saved without a path, is routed here: the note counts it alone. let routed: Vec<_> = warnings.iter().filter(|w| w.contains("FigCraft's own routing")).collect(); assert_eq!(routed.len(), 1, "{warnings:?}");