Merge main into #1914

This commit is contained in:
bflatastic committed 2026-11-07 10:57:26 +07:00
commit 4bb57d57ac
91 files changed
+2953 -214

No files matched your search

+4 -1
View File
@@ -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 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 (Line truncated
> **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 lonLine truncated
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 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.
@@ -361,6 +362,8 @@ 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-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-06 | patch | M7, #2032: closing a tab whose file has unsaved changes asks Don't Save / Cancel / Save, as closing the window does, instead of a toast that left the tab open; Alt+close still discards at once. Tests: `titlebar_tests::closing_a_tab_with_unsaved_changes_asks`, `titlebar_tests::save_in_the_tab_question_saves_then_closes`. Numbers unchanged |
| 2026-11-06 | patch | 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-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`. Numbers unchanged |
+3 -1
View File
@@ -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 {
+18
View File
@@ -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");
+17 -11
View File
@@ -217,7 +217,8 @@ impl Recovery {
return false;
}
let _ = match online {
Some(text) => std::fs::write(&note, text),
// The note holds the secret the client resumes with: owner-only, as the copy.
Some(text) => write_private(&note, text.as_bytes()),
None => std::fs::remove_file(&note),
};
true
@@ -326,24 +327,29 @@ fn rejoin_online(file: &Path, s: &mut Session) -> Option<u64> {
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
+34
View File
@@ -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()),
@@ -409,3 +415,31 @@ fn linger(ws: &mut WebSocket<Duplex>) {
}
}
}
#[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();
}
}
+31
View File
@@ -206,7 +206,17 @@ fn send(ws: &mut Ws, msg: &ClientMsg) -> Result<(), String> {
/// The next answer `pick` takes, or why there is none.
fn reply<T>(ws: &mut Ws, limits: &NetLimits, pick: impl Fn(ServerMsg) -> Option<T>) -> Result<T, String> {
// 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.
// 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 {
return Err("no answer from the server (it took too long)".into());
}
return match ws.read() {
Ok(Message::Binary(b)) => match message::decode::<ServerMsg>(&b, limits.max_server_message) {
Ok(ServerMsg::Refused { reason }) => Err(format!("{REFUSED}{reason}")),
@@ -251,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() {
+9 -2
View File
@@ -72,6 +72,12 @@ pub fn attached_sides(from: RouteEnd, to: RouteEnd) -> (Option<Side>, Option<Sid
(attach(from, to.centre()).1, attach(to, from.centre()).1)
}
/// Where a connector's ends attach, as routed now: the points [`ConnectorPath::Runs`] is measured
/// from the middle of.
pub fn attach_points(from: RouteEnd, to: RouteEnd) -> (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)> {
@@ -96,8 +102,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<ConnectorPath> {
+12 -8
View File
@@ -27,7 +27,7 @@ pub mod vector_faces;
pub mod vector_regions;
pub use board::*;
pub use board_route::{END_GAP, RouteEnd, attached_sides, path_handles, reshaped, route_along, route_points};
pub use board_route::{END_GAP, MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points};
pub use colors::*;
pub use comments::*;
pub use facilitation::*;
@@ -767,16 +767,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<Rect> {
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<Rect> {
fn render_bounds_at(&self, id: NodeId, depth: usize, left: &std::cell::Cell<usize>) -> Option<Rect> {
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)),
@@ -785,15 +789,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<Rect> {
fn children_render_bounds(&self, n: &Node, depth: usize, left: &std::cell::Cell<usize>) -> Option<Rect> {
let shown = |i: &NodeId| self.node(*i).is_some_and(|c| c.visible && !c.is_mask);
let mut out: Option<Rect> = 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) {
+17 -5
View File
@@ -948,7 +948,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
@@ -964,9 +964,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),
@@ -974,9 +975,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;
+17
View File
@@ -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]
@@ -596,6 +597,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
+2 -1
View File
@@ -439,8 +439,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),
+12 -1
View File
@@ -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))
}
@@ -277,6 +277,14 @@ pub fn read_capped(path: impl AsRef<Path>, max: u64) -> Result<Vec<u8>> {
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.
@@ -104,3 +104,31 @@ 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::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}");
}
}
+31 -1
View File
@@ -33,6 +33,36 @@ 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 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<NodeId>) -> Option<NodeId> {
fn find(doc: &Document, id: NodeId, p: Point, except: Option<NodeId>, depth: usize) -> Option<NodeId> {
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};
use edit::{label_cmd, set_color, set_style};
@@ -114,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
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 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
),
+23
View File
@@ -223,6 +223,19 @@ pub(super) fn add_connected(s: &mut Session, p: &Value) -> Result<Value> {
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 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)) => {
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()?);
if editing.is_some() {
textedit::end(s)?;
@@ -246,6 +259,16 @@ pub(super) fn add_connected(s: &mut Session, p: &Value) -> Result<Value> {
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<Option<(f64, f64)>> {
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,
+12 -5
View File
@@ -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 };
+11
View File
@@ -42,6 +42,13 @@ impl Session {
}
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, b) = (start, p);
if pixel {
@@ -92,6 +99,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;
+21 -6
View File
@@ -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<CommandSpec> {
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(),
+16 -10
View File
@@ -357,21 +357,27 @@ pub(super) fn copy_props(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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()
}
+17 -1
View File
@@ -267,6 +267,18 @@ 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 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(0, |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);
}
let frameish = n.kind.is_frame_like();
let list = if fills { &mut n.fills } else { &mut n.strokes };
if add {
@@ -298,6 +310,9 @@ pub(super) fn paint_set(s: &mut Session, p: &Value, fills: bool) -> Result<Value
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 list = if fills { &mut n.fills } else { &mut n.strokes };
let at = idx.unwrap_or(list.len().saturating_sub(1));
if list.is_empty() {
@@ -344,7 +359,8 @@ pub(super) fn paint_copy(s: &mut Session, p: &Value, fills: bool) -> Result<Valu
let (paint, stroke) = {
let doc = s.doc()?;
let n = doc.get(id)?;
let list = if fills { &n.fills } else { &n.strokes };
// A text's fills are what its characters show (the list the Design panel's rows are).
let list = if fills { crate::cmd::lists::character_fills(n).unwrap_or_default() } else { n.strokes.clone() };
let at = at.unwrap_or(list.len().saturating_sub(1));
let paint = list.get(at).cloned().ok_or_else(|| bad(cmd, format!("no {} at index {at}", if fills { "fill" } else { "stroke" })))?;
(paint, (!fills).then(|| n.stroke.clone()))
+10 -3
View File
@@ -184,9 +184,10 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
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<usize> {
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<Value> {
@@ -197,11 +198,15 @@ fn crop(s: &mut Session, p: &Value) -> Result<Value> {
let [id] = ids[..] else { return Err(refuse("select one layer to crop its image")) };
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 {
@@ -209,6 +214,8 @@ fn crop(s: &mut Session, p: &Value) -> Result<Value> {
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;
}
+24
View File
@@ -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();
+56 -2
View File
@@ -6,7 +6,7 @@
//! Every list is stored bottom first: index 0 paints (or applies) first, the last one is on top;
//! the Design panel shows them in reverse, the topmost row first.
use figcraft_doc::{Document, LayoutGrid, Node, NodeId};
use figcraft_doc::{Document, LayoutGrid, Node, NodeId, NodeKind};
use serde_json::Value;
use super::{CommandSpec, ok};
@@ -189,6 +189,52 @@ fn paint_field_kept(old: &figcraft_color::Paint, new: &figcraft_color::Paint, fi
}
}
/// The fills a text's characters show when every character shows the same list: the layer's
/// fills, or the one list that styling all of them while editing left on them. None when the
/// characters differ, as the layer's fill is then mixed ("Text nodes can have multiple sets of
/// fills if some characters are colored differently than others", the developer documentation's
/// `fills`). Any other layer: its fills.
pub fn character_fills(n: &Node) -> Option<Vec<figcraft_color::Paint>> {
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)
}
/// 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) {
if !has_character_fills(n) {
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 +296,19 @@ fn move_item(s: &mut Session, p: &Value, cmd: &str, list: BoundList) -> Result<V
let from = req_index(cmd, p, "from")?;
let to = req_index(cmd, p, "to")?;
for id in req_targets(cmd, s, p)? {
let len = s.doc()?.node(id).map(|n| list.len(n)).unwrap_or(0);
// A text's characters' shared fills are the list the Design panel shows and reorders.
let len = s
.doc()?
.node(id)
.map(|n| if list == BoundList::Fills { character_fills(n).map_or(n.fills.len(), |f| f.len()) } else { list.len(n) })
.unwrap_or(0);
if from >= 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),
+11
View File
@@ -109,10 +109,18 @@ pub fn effect_from(cmd: &str, p: &Value, key: &str) -> Result<Option<Effect>> {
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<Effect>) -> 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()
@@ -405,6 +413,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<Paint>) {
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);
+44 -4
View File
@@ -112,7 +112,7 @@ pub fn specs() -> Vec<CommandSpec> {
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<CommandSpec> {
]
}
/// `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<Value> {
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<Value> {
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
+130 -3
View File
@@ -129,11 +129,138 @@ fn toggle_italic(s: &mut Session, p: &Value) -> Result<Value> {
})
}
/// Hiragino's weight names: "W3" is 300.
fn w_number(word: &str) -> Option<u16> {
let n = word.strip_prefix('w')?.parse::<u16>().ok()?;
(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<u16> {
let n = word.parse::<u16>().ok().filter(|_| word.bytes().all(|b| b.is_ascii_digit()))?;
(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<u8> {
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", "67 Bold Condensed" → its Univers width and "condensed").
fn style_rest(style: &str) -> String {
let s = style.to_ascii_lowercase().replace('-', " ");
let words: Vec<&str> = s.split_whitespace().collect();
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
});
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::<Vec<_>>().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 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 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
/// 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<String> {
let italic = st.italic() || slanted(&st.font_style);
let rest = style_rest(&st.font_style);
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));
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());
}
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, 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())
}
/// `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<Value> {
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_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;
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);
}
})
}
+3
View File
@@ -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": "<Card title=\"{title} {title}\" />"}));
assert_eq!(code(&mut s, i, "vue"), "import Card from \"./Card.vue\";\n\n<Card title=\"Say &quot;hi&quot; Say &quot;hi&quot;\" />\n");
// Literal text before the first placeholder keeps it inside the attribute value.
ex(&mut s, "codeConnect.set", json!({"id": i, "language": "vue", "template": "<Card title=\"Say: {title}\" />"}));
assert_eq!(code(&mut s, i, "vue"), "import Card from \"./Card.vue\";\n\n<Card title=\"Say: Say &quot;hi&quot;\" />\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": "<p>Total = {title}</p>"}));
+117
View File
@@ -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<Color> {
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()));
}
+16 -12
View File
@@ -288,41 +288,45 @@ fn pieces(t: &str) -> Vec<Piece<'_>> {
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<char>)> {
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('=')?;
+34
View File
@@ -46,3 +46,37 @@ 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}");
}
#[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}");
}
+22
View File
@@ -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/<x>",
"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");
}
}
@@ -127,6 +127,16 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
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!({
+42 -3
View File
@@ -180,12 +180,21 @@ fn refusal(m: &Manifest, command: &str, params: &Value) -> Option<String> {
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
}
@@ -263,10 +272,23 @@ 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) {
// 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" | "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) {
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");
}
}
}
v.to_string()
@@ -708,6 +730,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)]
+7 -1
View File
@@ -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<DocState>,
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;
@@ -585,6 +589,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;
+3
View File
@@ -592,4 +592,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/"));
}
@@ -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}");
}
+12
View File
@@ -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<Value>,
/// For new text.
pub text: Option<Value>,
}
/// Clipboard contents (internal; the UI mirrors to the system clipboard).
#[derive(Clone, Debug, Default)]
pub struct Clipboard {
+28
View File
@@ -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}));
}
+1
View File
@@ -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(),
@@ -73,8 +73,15 @@ fn bundle() -> Vec<u8> {
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 },
+8 -5
View File
@@ -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)
+85 -1
View File
@@ -1,10 +1,94 @@
//! 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<String> {
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::<Vec<_>>()
.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 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");
// 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());
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();
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();
+190
View File
@@ -0,0 +1,190 @@
//! 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::{name_weight, next_style};
/// 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 {
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, u16)], from: &str, up: bool) -> Vec<String> {
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), ["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::<String>::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 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 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"]);
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"));
}
#[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"));
// 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 {
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 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_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 };
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_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.
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");
}
+50 -4
View File
@@ -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<Point> {
for (from, to) in [("connectorStartCap", "strokeCapStart"), ("connectorEndCap", "strokeCapEnd")] {
@@ -99,11 +100,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.
@@ -412,6 +415,49 @@ 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<ConnectorPath> {
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, out of the object: the first leaves
// the start's side for the first saved run, the last arrives at the end's from the last saved
// run. One along the side, or back into the object, doesn't.
let (across, last) = (first?, last?);
let (&a0, &a1) = (at.first()?, at.last()?);
// Where the run from `p` (`sideways`: going across) meets the saved run at `v`.
let onto = |sideways: bool, p: Point, v: f64| if sideways { Point::new(mid.x + v, p.y) } else { Point::new(p.x, mid.y + v) };
let out_of = |s: Option<Side>, 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 = out_of(s0, p0, onto(across, p0, a0)) && out_of(s1, p1, onto(!last, p1, a1));
fits.then_some(ConnectorPath::Runs { across, at })
}
/// The side of its layer a connector end leaves from: the `magnet` the file names (`AUTO` and
/// `CENTER`: the side facing the other end, whatever `relativePosition` says; #1909), else the edge
/// its point on the layer (`relativePosition`, 0–1) lies on, else the side facing the other end.
+82
View File
@@ -911,3 +911,85 @@ 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();
// 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:?}");
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<Kv<'static>>| {
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)]),
// 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)> {
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", "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:?}");
}
+2 -1
View File
@@ -52,6 +52,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, ConnectorMagnet magnet
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
@@ -75,7 +76,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
";
+10 -3
View File
@@ -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
}
}
+38 -6
View File
@@ -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<String, VariableValue>, 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<String> = (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);
}
}
+5 -3
View File
@@ -282,9 +282,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`].
+23
View File
@@ -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<u8> = (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}");
}
+23 -3
View File
@@ -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)],
},
]);
}
+6 -2
View File
@@ -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<f64>,
/// 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));
}
}
+3 -2
View File
@@ -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.
+11
View File
@@ -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<BezPath> {
// 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();
+55
View File
@@ -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<EffectKind>| {
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:?}");
}
}
+83 -26
View File
@@ -3,25 +3,31 @@
//! `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,Thai,Deva`: one tag per script wanted,
//! as the manifest's scripts column lists them; #1902).
//! `FIGCRAFT_WEB_FONTS` (comma-separated families) adds manifest families to the web build.
use std::fmt::Write as _;
use std::path::PathBuf;
/// Font build script: emit `craft_fonts.rs` from `input_fonts`, passing the
/// `CRAFT_FONTS_DIR`, `CRAFT_FONTS_REQUIRED`, wasm target, `FIGCRAFT_EMBED_CJK` and `FIGCRAFT_WEB_FONTS` inputs;
/// `CRAFT_FONTS_DIR`, `CRAFT_FONTS_REQUIRED`, wasm target, `FIGCRAFT_EMBED_CJK`, `FIGCRAFT_EMBED_SCRIPTS` and
/// `FIGCRAFT_WEB_FONTS` inputs;
/// report generation and write failures with `cargo::error`.
fn main() {
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR");
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED");
println!("cargo::rerun-if-env-changed=FIGCRAFT_EMBED_CJK");
println!("cargo::rerun-if-env-changed=FIGCRAFT_EMBED_SCRIPTS");
println!("cargo::rerun-if-env-changed=FIGCRAFT_WEB_FONTS");
let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n");
let dir = std::env::var_os("CRAFT_FONTS_DIR").map(PathBuf::from);
let required = std::env::var_os("CRAFT_FONTS_REQUIRED").is_some();
let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32");
let embed_cjk = std::env::var_os("FIGCRAFT_EMBED_CJK").is_some();
let embed_scripts = scripts_from(std::env::var("FIGCRAFT_EMBED_SCRIPTS").ok().as_deref());
let web_fonts = web_fonts(&std::env::var("FIGCRAFT_WEB_FONTS").unwrap_or_default());
match input_fonts(dir.as_deref(), wasm, required, embed_cjk, &web_fonts) {
match input_fonts(dir.as_deref(), wasm, required, embed_cjk, &embed_scripts, &web_fonts) {
Ok(entries) => src.push_str(&entries),
Err(e) => println!("cargo::error={e}"),
}
@@ -32,6 +38,12 @@ 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<String> {
var.unwrap_or_default().split([',', ' ']).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect()
}
/// The families `FIGCRAFT_WEB_FONTS` names: comma-separated, trimmed, empty names dropped.
fn web_fonts(list: &str) -> Vec<String> {
list.split(',').map(str::trim).filter(|f| !f.is_empty()).map(str::to_owned).collect()
@@ -43,8 +55,16 @@ fn not_embedded<'a>(web_fonts: &'a [String], faces: &[(String, String)]) -> Vec<
}
/// Collect the effective catalog and enforce the required web release faces after filtering.
/// Families named in `web_fonts` that nothing embedded get a warning (most likely misspelt).
fn input_fonts(dir: Option<&std::path::Path>, wasm: bool, required: bool, embed_cjk: bool, web_fonts: &[String]) -> Result<String, String> {
/// `embed_scripts`: script tags whose faces a web build keeps as well. Families named in `web_fonts`
/// that nothing embedded get a warning (most likely misspelt).
fn input_fonts(
dir: Option<&std::path::Path>,
wasm: bool,
required: bool,
embed_cjk: bool,
embed_scripts: &[String],
web_fonts: &[String],
) -> Result<String, String> {
let Some(dir) = dir else {
for family in web_fonts {
println!("cargo::warning=FIGCRAFT_WEB_FONTS: {family:?} isn't embedded: this build has no craft-fonts");
@@ -60,7 +80,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, web_fonts) {
match craft_fonts(dir, manifest, wasm, embed_cjk, embed_scripts, web_fonts) {
Ok(catalog) => {
loaded = true;
out.push_str(&catalog.entries);
@@ -106,9 +126,16 @@ 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 and the ones `web_fonts` adds, canonicalize and watch each face, and
/// emit `include_bytes!` items.
fn craft_fonts(dir: &std::path::Path, manifest_rel: &str, wasm: bool, embed_cjk: bool, web_fonts: &[String]) -> Result<Catalog, String> {
/// to its budgeted families (plus the faces of the scripts in `embed_scripts` and the families `web_fonts`
/// adds), canonicalize and watch each face, and emit `include_bytes!` items.
fn craft_fonts(
dir: &std::path::Path,
manifest_rel: &str,
wasm: bool,
embed_cjk: bool,
embed_scripts: &[String],
web_fonts: &[String],
) -> Result<Catalog, String> {
let manifest = dir.join(manifest_rel);
watch(&manifest);
let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?;
@@ -129,11 +156,14 @@ 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, optionally Noto Sans CJK (every CJK script, for CJK UI text), and the
// SemiBold wordmark, optionally Noto Sans CJK (every CJK script, for CJK UI text), 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), and the
// families a distribution names in `FIGCRAFT_WEB_FONTS` (a Thai face for Thai text, say).
let wordmark = *family == "Archivo" && *style == "SemiBold";
let asked = scripts.split(',').map(str::trim).any(|s| embed_scripts.iter().any(|e| e.eq_ignore_ascii_case(s)));
let added = web_fonts.iter().any(|f| f == family);
if wasm && !matches!(*family, "Inter" | "Noto Sans Georgian") && !wordmark && !cjk && !added {
if wasm && !matches!(*family, "Inter" | "Noto Sans Georgian") && !wordmark && !cjk && !asked && !added {
continue;
}
let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?;
@@ -187,9 +217,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"));
@@ -197,16 +227,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
@@ -215,12 +245,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
@@ -228,10 +258,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
@@ -241,7 +271,34 @@ 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::<Vec<String>>();
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());
}
/// Asserts `FIGCRAFT_WEB_FONTS` (split on commas, trimmed) adds the families it names to the web
@@ -254,11 +311,11 @@ mod tests {
let named = web_fonts(" Noto Sans Thai, ,Noto Sans Thia ");
assert_eq!(named, ["Noto Sans Thai", "Noto Sans Thia"]);
let families = |c: &Catalog| c.faces.iter().map(|(family, _)| family.clone()).collect::<Vec<_>>();
let web = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &named).unwrap();
let web = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &[], &named).unwrap();
assert_eq!(families(&web), ["Noto Sans Georgian", "Noto Sans Thai"], "the named family joins; the others stay out");
assert_eq!(families(&craft_fonts(&f.0, "fonts/manifest.txt", true, false, &[]).unwrap()), ["Noto Sans Georgian"], "unset: as before");
assert_eq!(craft_fonts(&f.0, "fonts/manifest.txt", false, false, &[]).unwrap().faces.len(), 3, "native builds embed every family");
assert_eq!(families(&craft_fonts(&f.0, "fonts/manifest.txt", true, false, &[], &[]).unwrap()), ["Noto Sans Georgian"], "unset: as before");
assert_eq!(craft_fonts(&f.0, "fonts/manifest.txt", false, false, &[], &[]).unwrap().faces.len(), 3, "native builds embed every family");
assert_eq!(not_embedded(&named, &web.faces), ["Noto Sans Thia"], "a misspelt family is reported");
assert!(input_fonts(Some(&f.0), true, false, false, &named).unwrap().contains("family: \"Noto Sans Thai\""));
assert!(input_fonts(Some(&f.0), true, false, false, &[], &named).unwrap().contains("family: \"Noto Sans Thai\""));
}
}
+47 -9
View File
@@ -544,10 +544,13 @@ fn names(f: &skrifa::FontRef) -> (Option<String>, Option<String>) {
(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",
@@ -640,6 +646,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 +720,10 @@ impl FontDb {
pub fn add_bytes(&mut self, bytes: Vec<u8>) -> Vec<Arc<Face>> {
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,
};
@@ -743,6 +755,12 @@ impl FontDb {
/// Style names of a family, by weight then italic.
pub fn styles(&mut self, family: &str) -> Vec<String> {
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.
@@ -761,14 +779,29 @@ 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();
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 +1535,11 @@ pub fn family_styles(family: &str) -> Vec<String> {
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.
+42 -1
View File
@@ -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::<Vec<_>>();
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)]));
}
+37
View File
@@ -541,6 +541,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]
@@ -598,3 +623,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());
}
+2 -2
View File
@@ -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;
+6
View File
@@ -407,6 +407,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"
"Text direction" = "Text direction"
"Auto: by the first letter with a direction" = "Auto: by the first letter with a direction"
+6
View File
@@ -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)" = "ნაგულისხმევი მნიშვნელობა (ზედა მარცხენა ვარიანტი)"
+169
View File
@@ -34,6 +34,12 @@ fn handle(u: &Ui, side: &str) -> Option<Rect> {
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<Rect> {
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 }]);
@@ -140,3 +146,166 @@ 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)));
}
/// 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");
}
/// 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");
}
/// 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");
}
+3 -2
View File
@@ -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 };
+150 -10
View File
@@ -1,11 +1,15 @@
//! 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 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 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, 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, sticky_or_shape_at};
use serde_json::json;
use crate::FigApp;
@@ -18,6 +22,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();
@@ -41,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>(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 {
@@ -51,8 +72,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<Drag> = 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>(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 +111,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 +130,72 @@ 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 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>(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) 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);
}
if let_go {
ctx.data_mut(|d| d.remove::<Drag>(drag_id()));
if !on_canvas {
return;
}
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>(drag_id()));
}
}
/// 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<NodeId> {
if !app.canvas.rect.contains(p) {
return None;
}
let ds = app.session.ds().ok()?;
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.
@@ -107,9 +210,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<NodeId>) {
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)));
}
+17 -5
View File
@@ -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<Vec<Paint>> {
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;
@@ -220,7 +229,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,
@@ -260,7 +269,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" };
@@ -684,7 +693,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 {
@@ -759,7 +768,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));
@@ -781,3 +790,6 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) {
}
}
}
#[cfg(test)]
mod character_fill_tests;
@@ -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"
);
}
+136 -1
View File
@@ -53,6 +53,113 @@ pub struct Editor {
details: Option<String>,
/// The group the table shows ("space" or "color/brand"); None = every variable.
group: Option<String>,
/// The selected variables' ids (this file's), kept to the rows the table shows.
pub(crate) selected: Vec<String>,
/// The row a Shift+click extends from.
pub(crate) anchor: Option<String>,
/// The variable ids the table shows now, in row order (the range a Shift+click covers).
pub(crate) order: Vec<String>,
}
/// 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<String> = 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<Vec<&'a Variable>> {
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<Value> = 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();
}
// 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 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 +682,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 +715,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 +809,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 +835,19 @@ 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());
}
crate::right::context_popup(&resp).show(|ui| {
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"), "") {
st.details = Some(v.id.clone());
ui.close();
+56
View File
@@ -1214,3 +1214,59 @@ 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);
// 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)], 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);
}
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");
// 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");
}
@@ -51,6 +51,115 @@ fn sorted(mut v: Vec<NodeId>) -> Vec<NodeId> {
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::<Vec<_>>()
};
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();
+4 -2
View File
@@ -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();
+4
View File
@@ -249,6 +249,8 @@ mod text_enter_tests;
#[cfg(test)]
mod text_link_tests;
#[cfg(test)]
mod text_mixed_fill_tests;
#[cfg(test)]
mod titlebar_tests;
#[cfg(test)]
mod ui_params_tests;
@@ -261,6 +263,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;
+34 -6
View File
@@ -962,15 +962,34 @@ 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: &BTreeSet<NodeId>, id: NodeId) -> Option<NodeId> {
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(roots: &[Option<NodeId>], i: usize, mut rr: Rect, gap: f32) -> Option<(Rect, CornerRadius)> {
let root = roots.get(i).copied().flatten()?;
let joins = |neighbor: &Option<NodeId>| *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;
}
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);
}
}
@@ -1071,15 +1090,20 @@ 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.
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);
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);
@@ -1093,9 +1117,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(&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);
}
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();
+2 -1
View File
@@ -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 };
@@ -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::<f64>().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),
}
+107
View File
@@ -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<String>, 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<String> {
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::<Vec<_>>()
.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:?}");
}
+1 -1
View File
@@ -494,7 +494,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");
@@ -0,0 +1,252 @@
//! 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<String> {
let st = u.app.ui.variables.as_ref().unwrap();
let doc = u.app.session.doc().unwrap();
let mut names: Vec<String> = 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<String> {
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<egui::Shape> {
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<String> = 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"));
}
/// 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<egui::Rect> =
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)));
}
+24 -7
View File
@@ -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<f64>, step: f64) -> Option<FieldEdit> {
/// 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<f64>, step: f64, fine_on_alt: bool) -> Option<FieldEdit> {
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<f64>, 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,20 @@ 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<String> = 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 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 alt_now = ui.input(|i| i.modifiers.alt);
let scrubbing_id = id.with("altscrub");
let scrubbing = ui.data(|d| d.get_temp::<bool>(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);
// The label scrubs with the pointer; the keyboard stops at the value only.
@@ -291,10 +305,13 @@ fn number_field_impl(
}
Lead::None | Lead::Named(_) => {}
}
if lead_resp.hovered() || lead_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);
}
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 +357,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_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");
+2 -1
View File
@@ -92,7 +92,8 @@ fn current_paint(app: &FigApp, target: &PickerTarget) -> Option<Paint> {
},
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),
+32 -6
View File
@@ -63,27 +63,53 @@ const NAMED: usize = 3;
#[derive(Default)]
pub(crate) struct Warnings {
seen: std::collections::BTreeMap<Warn, Vec<String>>,
/// 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<Warn, (std::collections::BTreeSet<String>, Vec<String>)>,
}
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<String> {
self.seen
.into_iter()
.map(|(w, names)| {
.map(|(w, (distinct, names))| {
let shown: Vec<String> =
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());
}
}
+3 -2
View File
@@ -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` |
+8 -4
View File
@@ -1,6 +1,6 @@
# Boards parity
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-04 · **Change:** minor (a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre)
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-04 · **Change:** minor (a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); 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 attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre)
**Breadth ~47%, ready ~29% (estimated, erring low).** A board is a FigCraft file of its own kind
(`file.newBoard`) with a dot grid on the page, sticky notes, shapes with text, connectors that
@@ -37,14 +37,16 @@ all end with the same geometry.
| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed; an end dropped on the outer half of an object takes the side it is towards (a drop along a whole edge chooses that edge), one in the middle takes the facing side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal and curves leave tangent to it (#1916) |
| Shapes with text | done | 23 outlines: rectangle, rounded rectangle, ellipse, diamond, triangle up and down, parallelogram right and left, trapezoid, pentagon, hexagon, octagon, star, plus, arrow left and right, chevron, speech bubble, and the flowchart symbols database, document, predefined process, manual input and internal storage; text centred and wrapping inside the outline; shape type and text size from the contextual bar |
| Shape auto-fit to its text, the advanced shape libraries (engineering and other icon shapes) | missing | |
| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed, and within 10 px of one the end keeps that side; re-routed when either end moves or resizes; a deleted end stays where it was |
| 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) |
| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed, and within 10 px of one the end keeps that side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal and curves leave tangent to it (#1916) |
| Create the next shape already connected | done | a selected sticky or shape shows a "+" beside each side; hovering one shows where the next goes, clicking makes one of the same kind, size and colour there, joined by a connector as the Connector tool makes one, and starts typing in it; one undo step (`board.addConnected {id?, side?, edit?}`, #1597). Shift+Cmd/Ctrl+Enter on a selected (or edited) shape adds the next shape on its right, joined the same way, and goes on typing; on a sticky it adds a sticky beside it without a connector, as before |
| Curved connectors, elbows around objects, dragging an end to re-attach | done | `board.setStyle {style: curved}` (and the contextual bar): one curve leaving and arriving along the sides; an elbow whose short way would cross what it joins goes around their boxes, 24 units clear; a selected connector shows its two ends as handles, and dragging one onto an object attaches it there (the object is outlined while dragging), onto empty canvas leaves it free (`board.reattach {id, end, target, side?}`, one undo step) |
| A connector end on any part of an object | done | holding Cmd/Ctrl while moving an end places it where the pointer is on the object, as a share of its box, so it follows moves and resizes; the line leaves by the side facing the other end. Without the key an end snaps to a side |
| 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 |
@@ -64,13 +66,15 @@ 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
| 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 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-11-04 | minor | M12, #1916: a connector end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), as FigJam's do (the issue's screenshots: the line starts a few pixels outside, with a round cap), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal, curves leave tangent to it and straight ones fan out from the same point; the `.jam` importer's routes, re-attached ends, path handles and labels follow the route's points; an end placed by hand with Cmd/Ctrl held keeps its exact point. Tests: `board_route_tests` (three). Numbers unchanged. |
| 2026-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. |
+3 -2
View File
@@ -1,6 +1,6 @@
# Components, variants, styles and variables parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **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); 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
@@ -64,7 +64,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 |
@@ -79,6 +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 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/<i>/<field>`) 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. |
+4 -3
View File
@@ -1,6 +1,6 @@
# File format parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); 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 `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); 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); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); 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 HLine truncated
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: checLine truncated
| `.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 showcaseLine truncated
| `.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 end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, #1909), 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/<key>`, 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) | — |
@@ -189,6 +189,7 @@ source paint coordinates.
|---|---|---|
| 2026-11-03 | patch | M6, #1909: `.jam` import: a connector end whose magnet is `AUTO` (FigJam picks the side when it draws) or `CENTER` (the end aims at the layer's middle) left the side its stale `relativePosition` named, the left one in the reporter's file, so the connectors looped behind their shape or crossed it. It now leaves the side facing the other end, as a board connector drawn here does (`Side::Auto`), for straight, elbowed and curved connectors alike; a named magnet (`TOP`, `RIGHT`, `BOTTOM`, `LEFT`) is unchanged, and an end without a magnet still takes the edge its point lies on. The Plugin API lists the magnets (`ConnectorEndpoint.magnet`: "Which side of the node it attaches to"; NONE, AUTO, TOP, LEFT, BOTTOM, RIGHT, CENTER; "Straight connectors may use only CENTER or NONE magnets"). Test: `connectors_with_an_automatic_side_leave_the_side_facing_the_target`. Numbers unchanged. |
| 2026-11-04 | minor | JPG export: `quality` (1 to 100, default 90) on `file.export`, `export.add` / `export.update` and MCP `export`, kept in the export setting; an sRGB file's JPGs embed the sRGB ICC profile, as Display P3 files' JPGs already embedded theirs, since an untagged JPG is only assumed to be sRGB (#2004). |
| 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` |
+8 -2
View File
@@ -1,6 +1,6 @@
# Localization parity
> **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)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (`FIGCRAFT_EMBED_SCRIPTS` embeds other scripts' craft-fonts faces in a web build, so Arabic and Persian documents draw there (#1902); ; 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
@@ -86,7 +86,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,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
@@ -95,6 +98,8 @@ 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 |
| 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) |
| 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) |
@@ -130,6 +135,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 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-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-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) |
+6 -2
View File
@@ -854,11 +854,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
+2 -1
View File
@@ -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 |
+4 -1
View File
@@ -78,7 +78,10 @@ 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,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
+10 -3
View File
@@ -1,6 +1,6 @@
# UI and interaction parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (; 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); 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`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); 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 widtLine truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (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); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; 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); 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`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); 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 capitLine truncated
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,13 +33,14 @@ 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, and so does a drag of the open gradient's handles or stops on the canvas (#1852). |
| 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; 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
| 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) |
@@ -70,9 +71,10 @@ 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 |
| 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 |
@@ -179,6 +181,11 @@ 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-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-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-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-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-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-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`. |