From bceb0bb233d653d7d25fc16012ee1bc2d1011962 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 8 Nov 2026 19:56:53 -0500 Subject: [PATCH 001/114] M5: present a tall frame sharp on HiDPI displays with a device-scale detail texture over the capped frame (#2127) Cause: - The presenter rasterises a whole frame once, capped at 16.8 MP (texture_scale), so a 1440 x 9701 frame is drawn at 1.0959 px per unit (1579 x 10632 px). - On a 2x display at Fit width or 100% the GPU stretches that 1.8x with linear filtering; scrolling only pans, so the same texture is reused. Fix: - render: render_area_at(doc, ids, b, scale, time), the GIF-clock form of render_area. - present/actions.rs: texture_scale split into pure texture_scale_for plus the ctx wrapper; pure detail_plan (the view plus a quarter margin each way, inside the frame, shrunk to the side and pixel caps; None when the whole texture is already at device scale); Presenter::detail_texture caches one detail for the current frame and renders it with render_area_at. - present/draw.rs: paints the detail right after the base texture, so overlays still paint over it; it is re-rendered when it stops covering the view, and not while a fling, drag or the wheel moves the view (the capped texture shows then). Verified: - tall_frame_detail_plan_renders_the_view_at_device_scale: compile error on main (neither function existed). - presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale: failed on main at the size[0] >= 2878 assert (only present texture 1579 x 10632). - present tests 99 passed; figcraft-ui-egui --lib 1107 passed; figcraft-render --lib 245 passed; clippy -D warnings, fmt and cargo xtask wasm clean. Not changed: - Transitions, smart animate, overlays, the bar thumbnail and the pane keep the capped whole-frame texture; MAX_TEXTURE_PIXELS is unchanged; no tiling. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.1 briefed; Sonnet 5.5 wrote at medium --- crates/render/src/lib.rs | 5 ++ crates/ui-egui/src/present.rs | 4 ++ crates/ui-egui/src/present/actions.rs | 76 ++++++++++++++++++++++++++- crates/ui-egui/src/present/draw.rs | 14 ++++- crates/ui-egui/src/present/tests.rs | 38 ++++++++++++++ crates/ui-egui/src/present_tests.rs | 10 +++- docs/prototyping-parity.md | 5 +- docs/target-app-parity.md | 3 +- 8 files changed, 147 insertions(+), 8 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index f138521ae..c4674c819 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -362,6 +362,11 @@ pub fn render_area(doc: &Document, ids: &[NodeId], b: Rect, scale: f64) -> Optio area_at(doc, ids, b, scale, 0.0) } +/// [`render_area`] `time` seconds into animated GIFs (the presenter plays them). +pub fn render_area_at(doc: &Document, ids: &[NodeId], b: Rect, scale: f64, time: f64) -> Option { + area_at(doc, ids, b, scale, time) +} + fn area_at(doc: &Document, ids: &[NodeId], b: Rect, scale: f64, time: f64) -> Option { let scale = if scale.is_finite() && scale > 0.0 { scale.min(64.0) } else { 1.0 }; let w = (b.width() * scale - 1e-6).ceil().max(1.0); diff --git a/crates/ui-egui/src/present.rs b/crates/ui-egui/src/present.rs index 8f23069f2..64ee81ef0 100644 --- a/crates/ui-egui/src/present.rs +++ b/crates/ui-egui/src/present.rs @@ -286,6 +286,9 @@ pub struct Presenter { anim_tex: Option, temp: Option, textures: HashMap, + /// The part of the presented frame in view, drawn at device scale over the (capped) whole-frame + /// texture; `bounds` is the page area it covers. + detail: Option<(NodeId, FrameTex)>, /// Small current-screen preview in the full-window bar, cached until its content changes. bar_thumb: Option<(NodeId, usize, egui::TextureHandle)>, arrived: f64, @@ -367,6 +370,7 @@ impl Presenter { anim_tex: None, temp: None, textures: HashMap::new(), + detail: None, bar_thumb: None, arrived: -1.0, delays_fired: HashSet::new(), diff --git a/crates/ui-egui/src/present/actions.rs b/crates/ui-egui/src/present/actions.rs index cfc3f26a8..52d75fa88 100644 --- a/crates/ui-egui/src/present/actions.rs +++ b/crates/ui-egui/src/present/actions.rs @@ -252,7 +252,8 @@ impl Presenter { } } - pub(super) fn texture(&mut self, ctx: &egui::Context, doc: &Document, id: NodeId, px_scale: f64, now: f64) -> Option { + /// Seconds into the frame's animated GIFs, and the frame of them showing (see [`Self::texture`]). + fn frame_clock(&self, ctx: &egui::Context, doc: &Document, id: NodeId, now: f64) -> (f64, Option<(u64, f64)>) { // Animated GIFs play from when the frame arrived: a new texture when one of them moves on, // and a wake-up for that moment (nothing else draws frames while it shows). egui wakes a // display frame before the time asked for, a little earlier still at times: ask that much @@ -262,6 +263,48 @@ impl Presenter { if let Some((_, next)) = clock { crate::repaint_in(ctx, next + f64::from(ctx.input(|i| i.predicted_dt))); } + (t, clock) + } + + /// The part of the frame `id` in view (`visible`, page units) at the full pixel scale `px`, for + /// a frame whose whole texture is capped below it (see [`detail_plan`]). While the view moves + /// (`moving`) it only returns a detail already rendered, the capped texture showing under it. + pub(super) fn detail_texture( + &mut self, + ctx: &egui::Context, + doc: &Document, + id: NodeId, + px: f64, + visible: figcraft_geom::Rect, + moving: bool, + now: f64, + ) -> Option { + let (t, clock) = self.frame_clock(ctx, doc, id, now); + let key = (self.rev, px.to_bits(), clock.map_or(0, |c| c.0)); + let covers = |b: &figcraft_geom::Rect| b.x0 <= visible.x0 && b.y0 <= visible.y0 && b.x1 >= visible.x1 && b.y1 >= visible.y1; + if let Some((did, d)) = &self.detail + && *did == id + && d.key == key + && (moving || covers(&d.bounds)) + { + return Some(d.clone()); + } + if moving { + return None; + } + let side = ctx.input(|i| i.max_texture_side) as f64 - 2.0; + let bounds = figcraft_render::export_bounds(doc, id)?; + let rect = detail_plan(bounds, visible, px, side)?; + let pix = figcraft_render::render_area_at(doc, &[id], rect, texture_scale_for(rect, px, side), t)?; + let img = crate::render_worker::screen_image(&pix, doc.color_profile); + let tex = ctx.load_texture(format!("present-detail-{}", id.0), img, egui::TextureOptions::LINEAR); + let ft = FrameTex { key, tex, bounds: rect }; + self.detail = Some((id, ft.clone())); + Some(ft) + } + + pub(super) fn texture(&mut self, ctx: &egui::Context, doc: &Document, id: NodeId, px_scale: f64, now: f64) -> Option { + let (t, clock) = self.frame_clock(ctx, doc, id, now); let key = (self.rev, px_scale.to_bits(), clock.map_or(0, |c| c.0)); if let Some(t) = self.textures.get(&id) && t.key == key @@ -285,12 +328,41 @@ const MAX_TEXTURE_PIXELS: f64 = 16_777_216.0; /// The pixel scale, at most `px`, at which `bounds` makes a texture the GPU takes (no side past /// its limit) of at most [`MAX_TEXTURE_PIXELS`]. pub(super) fn texture_scale(ctx: &egui::Context, bounds: figcraft_geom::Rect, px: f64) -> f64 { - let side = ctx.input(|i| i.max_texture_side) as f64 - 2.0; + texture_scale_for(bounds, px, ctx.input(|i| i.max_texture_side) as f64 - 2.0) +} + +/// [`texture_scale`] for a GPU taking textures up to `side` pixels a side. +pub(super) fn texture_scale_for(bounds: figcraft_geom::Rect, px: f64, side: f64) -> f64 { let (w, h) = (bounds.width().max(1.0), bounds.height().max(1.0)); let s = px.min(side / w.max(h)).min((MAX_TEXTURE_PIXELS / (w * h)).sqrt()); if s.is_finite() && s > 0.0 { s } else { 1e-3 } } +/// The page area to draw at the full pixel scale `px` over the whole frame's capped texture, when +/// that texture is below `px`: the part in `visible` with a margin (a quarter of its size each +/// way, shrunk until the area makes a texture the GPU takes), inside `bounds`. `None` when the +/// whole frame is already at `px`, or nothing of it is in view. When the view alone is past the +/// caps it is returned all the same, and drawn at the scale [`texture_scale_for`] gives it. +pub(super) fn detail_plan(bounds: figcraft_geom::Rect, visible: figcraft_geom::Rect, px: f64, side: f64) -> Option { + if texture_scale_for(bounds, px, side) >= px || !(px.is_finite() && px > 0.0) { + return None; + } + let view = visible.intersect(bounds); + if !(view.width() > 0.0 && view.height() > 0.0 && view.width().is_finite() && view.height().is_finite()) { + return None; + } + let fits = |r: &figcraft_geom::Rect| r.width() * px <= side && r.height() * px <= side && r.area() * px * px <= MAX_TEXTURE_PIXELS; + let mut margin = 0.25; + for _ in 0..8 { + let r = view.inflate(view.width() * margin, view.height() * margin).intersect(bounds); + if fits(&r) { + return Some(r); + } + margin /= 2.0; + } + Some(view) +} + /// The first interaction index on `id` whose trigger satisfies `want`. pub(super) fn find_trigger(doc: &Document, id: NodeId, want: impl Fn(&Trigger) -> bool) -> Option { doc.node(id)?.interactions.iter().position(|it| want(&it.trigger)) diff --git a/crates/ui-egui/src/present/draw.rs b/crates/ui-egui/src/present/draw.rs index b4d679144..c8bd8248f 100644 --- a/crates/ui-egui/src/present/draw.rs +++ b/crates/ui-egui/src/present/draw.rs @@ -74,7 +74,19 @@ pub(super) fn draw(p: &mut Presenter, painter: &egui::Painter, ctx: &egui::Conte } } if !drawn && let Some(to) = &to_tex { - painter.with_clip_rect(l.clip).image(to.tex.id(), l.place.rect(to.bounds), uv, Color32::WHITE); + let on_clip = painter.with_clip_rect(l.clip); + on_clip.image(to.tex.id(), l.place.rect(to.bounds), uv, Color32::WHITE); + // A frame too big for one texture at device scale is drawn from a smaller one: the part in + // view is drawn again from a texture at device scale, over it (and the overlays over that). + let shown = l.clip.intersect(l.place.rect(to.bounds)); + if shown.is_positive() { + let (a, b) = (l.place.page(shown.min), l.place.page(shown.max)); + let visible = figcraft_geom::Rect::new(a.x, a.y, b.x, b.y); + let moving = p.fling.is_some() || p.drag_scroll.is_some() || p.wheel.is_some(); + if let Some(d) = p.detail_texture(ctx, &l.disp, p.current, px, visible, moving, now) { + on_clip.image(d.tex.id(), l.place.rect(d.bounds), uv, Color32::WHITE); + } + } } // Overlays (each with its background and opening transition); closing ones run it backwards. let mut ovs: Vec<(f64, OverlayState)> = diff --git a/crates/ui-egui/src/present/tests.rs b/crates/ui-egui/src/present/tests.rs index bba998788..9ed1fa665 100644 --- a/crates/ui-egui/src/present/tests.rs +++ b/crates/ui-egui/src/present/tests.rs @@ -436,3 +436,41 @@ fn smart_animate_frame_cost() { let per = t0.elapsed().as_secs_f64() * 1000.0 / f64::from(n); eprintln!("smart animate: {per:.2} ms per frame (80 layers, 400x800 px)"); } + +#[test] +fn tall_frame_detail_plan_renders_the_view_at_device_scale() { + use figcraft_geom::Rect as PageRect; + let bounds = PageRect::new(0.0, 0.0, 1440.0, 9701.0); + let visible = PageRect::new(0.0, 0.0, 1440.0, 860.0); + let side = 16382.0; + assert!(actions::texture_scale_for(bounds, 2.0, side) < 1.1, "the whole frame is capped below device scale"); + let r = actions::detail_plan(bounds, visible, 2.0, side).expect("a capped frame gets a detail"); + assert!(r.x0 <= visible.x0 && r.y0 <= visible.y0 && r.x1 >= visible.x1 && r.y1 >= visible.y1, "covers the view"); + assert!(r.x0 >= bounds.x0 && r.y0 >= bounds.y0 && r.x1 <= bounds.x1 && r.y1 <= bounds.y1, "inside the frame"); + assert!(r.width() * 2.0 <= side && r.height() * 2.0 <= side); + assert!(r.width() * r.height() * 4.0 <= 16_777_216.0); + let small = PageRect::new(0.0, 0.0, 1440.0, 900.0); + assert!(actions::detail_plan(small, PageRect::new(0.0, 0.0, 1440.0, 860.0), 2.0, side).is_none()); +} + +#[test] +fn presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale() { + let mut session = figcraft_engine::Session::new(); + let frame = id(&session.execute("node.create", &json!({"type": "frame", "width": 1440, "height": 9701})).unwrap()); + session.execute("node.create", &json!({"type": "rectangle", "parent": frame, "x": 100, "y": 100, "width": 300, "height": 200})).unwrap(); + let mut ui = Ui::new(session); + ui.hidpi = Some((2.0, 16_384)); + ui.run("proto.present", json!({"start": frame})); + ui.app.ui.present.as_mut().unwrap().view.scale = PresentScale::FitWidth; + ui.frames(2, Vec::new); + + let textures = ui.ctx.tex_manager(); + let textures = textures.read(); + let present: Vec<_> = textures.allocated().filter(|(_, m)| m.name.starts_with("present-")).map(|(_, m)| m.size).collect(); + assert!(!present.is_empty()); + assert!(present.iter().any(|s| s[0] >= 2878), "some texture shows the view at 2 px a unit: {present:?}"); + for s in &present { + // The scale caps the area; each side then rounds up to a whole pixel. + assert!(s[0] * s[1] <= 16_777_216 + s[0] + s[1] && s[0] <= 16_384 && s[1] <= 16_384, "{s:?}"); + } +} diff --git a/crates/ui-egui/src/present_tests.rs b/crates/ui-egui/src/present_tests.rs index 4a3819c09..631184bba 100644 --- a/crates/ui-egui/src/present_tests.rs +++ b/crates/ui-egui/src/present_tests.rs @@ -13,11 +13,13 @@ pub(crate) struct Ui { pub(crate) ctx: egui::Context, pub(crate) app: FigApp, pub(crate) time: f64, + /// A display's pixels per point and the biggest texture side its GPU takes (None: egui's defaults). + pub(crate) hidpi: Option<(f32, usize)>, } 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, hidpi: None }; u.frames(3, Vec::new); u } @@ -29,8 +31,12 @@ impl Ui { /// [`Self::frame`], returning what egui output (the AccessKit tree when it's enabled). pub(crate) fn frame_output(&mut self, events: Vec) -> egui::FullOutput { self.time += 1.0 / 60.0; - let input = + let mut input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), time: Some(self.time), events, ..Default::default() }; + if let Some((ppp, side)) = self.hidpi { + input.max_texture_side = Some(side); + input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(ppp); + } let app = &mut self.app; let mut out = self.ctx.run_ui(input, |ui| app.ui(ui)); out.textures_delta.clear(); diff --git a/docs/prototyping-parity.md b/docs/prototyping-parity.md index 7c216bcae..3cb52d2b9 100644 --- a/docs/prototyping-parity.md +++ b/docs/prototyping-parity.md @@ -1,6 +1,6 @@ # Prototyping parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-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) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-08 · **Change:** patch (presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); `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, @@ -91,7 +91,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Widgets react to clicks in a presented prototype | done | clicks only, like on the canvas | | Interactive components: instances play their variant's interactions, overridden per trigger | done | | | Drag-driven animations that follow the pointer, in their direction | done | | -| Presenter: device frames and colours, rotation, custom sizes, fit/fill/100%, responsive frames | done | device bodies drawn in code. Presenting opens a tab for the page, named "file - page", which keeps its screen and history while you go back to the design, with a thumbnail of the current frame, previous / next, device presets and scale choices; the frame is laid out again for the device's screen on the prototype's copy (constraints and auto layout; the file is untouched); on phones and tablets overflowing content drags while the device stays put: a top-level frame bigger than the screen always scrolls (as in Figma, with no overflow setting), content past the frame's own edges as its overflow setting allows ("No scrolling" clips it); closing the window asks about unsaved changes above the presentation (#537). Devices not compared with Figma's | +| Presenter: device frames and colours, rotation, custom sizes, fit/fill/100%, responsive frames | done | device bodies drawn in code. Presenting opens a tab for the page, named "file - page", which keeps its screen and history while you go back to the design, with a thumbnail of the current frame, previous / next, device presets and scale choices; the frame is laid out again for the device's screen on the prototype's copy (constraints and auto layout; the file is untouched); on phones and tablets overflowing content drags while the device stays put: a top-level frame bigger than the screen always scrolls (as in Figma, with no overflow setting), content past the frame's own edges as its overflow setting allows ("No scrolling" clips it); closing the window asks about unsaved changes above the presentation (#537); a frame too big for one texture at device scale (taller than about 2900 units at 1440 wide on a 2x display) shows the part in view from a second texture at device scale over the capped whole-frame one, drawn again when it stops covering the view and not while the view moves (#2127). Devices not compared with Figma's | | Hotspot hints, inspect panel in the presenter, comments in the presenter | done | | | Hide UI in the presenter (Options menu, Cmd/Ctrl+\) | done | the bar above the prototype and the navigation bar under it go away and the prototype takes their room; a toast names the key that brings them back; `proto.presentOptions {hideUi}`, kept for later presentations (#1820) | | Preview pane following edits live | done | | @@ -107,6 +107,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Date | Change | Summary | |---|---|---| +| 2026-11-08 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it; transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | | 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. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 031521f51..0764fca6c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (justified Chinese, Japanese and Korean text, written without spaces, spreads each line's room between its characters so its right edge aligns (#1970); joining the two ends of a path broken open by a deleted point closes it again, so its fill and selection outline follow the new segment and its corner radius instead of a straight line across the gap (#1951); glass's docs say which centre splay bends away from and where a shape gets no core; glass bends towards its core, rounded rectangles 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, measured against the reference tool; bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%; last major: full re-measure against Figma desktop 126.10.7; rows for the community batches: Selection colors, smart-selection spacing and a Present tab (#753), `.fig` import fidelity, paste from another design app, a `.fig` copy from Save as; control requests while the window is minimised (#720); catalog counts re-measured; automation roots (#715); number variables in the text content picker (#629); frames and sections convert into each other (#719)) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); justified Chinese, Japanese and Korean text, written without spaces, spreads each line's room between its characters so its right edge aligns (#1970); joining the two ends of a path broken open by a deleted point closes it again, so its fill and selection outline follow the new segment and its corner radius instead of a straight line across the gap (#1951); glass's docs say which centre splay bends away from and where a shape gets no core; glass bends towards its core, rounded rectangles 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, measured against the reference tool; bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%; last major: full re-measure against Figma desktop 126.10.7; rows for the community batches: Selection colors, smart-selection spacing and a Present tab (#753), `.fig` import fidelity, paste from another design app, a `.fig` copy from Save as; control requests while the window is minimised (#720); catalog counts re-measured; automation roots (#715); number variables in the text content picker (#629); frames and sections convert into each other (#719)) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is @@ -652,6 +652,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-08 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it; transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`) draft catalog: 1,975 UI strings, 641 command labels and 31 menu wordings, clean-room from the English source; zh-TW, zh-HK, zh-MO and zh-Hant read it, explicit Hans stays Simplified; Noto Sans CJK TC then Taiwan system faces; no bundled font; native review pending. Numbers unchanged | | 2026-11-04 | patch | M4, #1970: justified Chinese, Japanese and Korean text, written without spaces between words, aligns its right edge: the room on each line but a paragraph's last goes between its characters, each a word of its own as for line breaking ("Justify aligns the first word in each line of text to the left-most edge, and the last to the right-most edge"), wherever a line could break there, so none opens before a full stop or closing bracket, nor after an opening one. Latin text widens its spaces as before; mixed text widens both. A gap is reordered with the line's runs as a space of no width would be, so one beside a Hebrew word in Chinese text, or beside a Chinese word within that Hebrew, opens beside the word, not inside it. `figcraft_text::breaks::justify_between`, beside `break_between`, says where. Evidence: `tests::justified_ideographs_spread_the_room_between_characters` (fails on main). | | 2026-11-04 | patch | M8, #1951 (#1506 again): a path broken open by deleting a point (Delete, not Shift+Delete) is filled closed by a straight line across the gap, as an open path's fill is; joining its two ends again (the pen onto the other end, Connect, ⌘J) left the loop without the new segment, so once the points were rounded the fill and the selection outline ran straight across while the stroke followed the segment and its arcs. Joining now closes the loop through the new segment ("Click to close the path."; "You can use the Paint tool to add fills to any closed regions of a vector network."): `ops::connect` puts it into the loop whose segments are the chain between the ends, at the gap and in the loop's own order, so a hole keeps its winding whichever end was clicked first; a loop listed out of walking order is left as it was. Evidence: `vectoredit::tests::a_rounded_chamfer_made_other_ways_fills_along_its_arcs` (fails on main: the loop kept 4 of 5 segments), `a_rounded_chamfer_cut_in_the_editor_fills_along_its_arcs` (Shift+Delete, with and without a region fill), `doc::tests::a_chamfered_rectangles_rounded_fill_is_cut_at_every_point` (fill, region path and stroke agree for every loop order and segment direction of a chamfered rectangle). | From 005cc73264c162e0cbcd63053ee5405ace8cb870 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 8 Nov 2026 20:00:05 -0500 Subject: [PATCH 002/114] M5: the presenter's detail texture takes the frame's bounds from its whole texture (#2127) detail_texture worked out the frame's export bounds again on every frame, even for a frame that fits one texture; the caller already has them in the whole-frame texture. The docs rows carry today's date. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- crates/ui-egui/src/present/actions.rs | 11 ++++++----- crates/ui-egui/src/present/draw.rs | 2 +- docs/prototyping-parity.md | 4 ++-- docs/target-app-parity.md | 4 ++-- 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/present/actions.rs b/crates/ui-egui/src/present/actions.rs index 52d75fa88..ec23bd8be 100644 --- a/crates/ui-egui/src/present/actions.rs +++ b/crates/ui-egui/src/present/actions.rs @@ -266,15 +266,17 @@ impl Presenter { (t, clock) } - /// The part of the frame `id` in view (`visible`, page units) at the full pixel scale `px`, for - /// a frame whose whole texture is capped below it (see [`detail_plan`]). While the view moves - /// (`moving`) it only returns a detail already rendered, the capped texture showing under it. + /// The part of the frame `id` (its whole texture covering `whole`, page units) in view + /// (`visible`) at the full pixel scale `px`, for a frame whose whole texture is capped below it + /// (see [`detail_plan`]). While the view moves (`moving`) it only returns a detail already + /// rendered, the capped texture showing under it. pub(super) fn detail_texture( &mut self, ctx: &egui::Context, doc: &Document, id: NodeId, px: f64, + whole: figcraft_geom::Rect, visible: figcraft_geom::Rect, moving: bool, now: f64, @@ -293,8 +295,7 @@ impl Presenter { return None; } let side = ctx.input(|i| i.max_texture_side) as f64 - 2.0; - let bounds = figcraft_render::export_bounds(doc, id)?; - let rect = detail_plan(bounds, visible, px, side)?; + let rect = detail_plan(whole, visible, px, side)?; let pix = figcraft_render::render_area_at(doc, &[id], rect, texture_scale_for(rect, px, side), t)?; let img = crate::render_worker::screen_image(&pix, doc.color_profile); let tex = ctx.load_texture(format!("present-detail-{}", id.0), img, egui::TextureOptions::LINEAR); diff --git a/crates/ui-egui/src/present/draw.rs b/crates/ui-egui/src/present/draw.rs index c8bd8248f..28bc11891 100644 --- a/crates/ui-egui/src/present/draw.rs +++ b/crates/ui-egui/src/present/draw.rs @@ -83,7 +83,7 @@ pub(super) fn draw(p: &mut Presenter, painter: &egui::Painter, ctx: &egui::Conte let (a, b) = (l.place.page(shown.min), l.place.page(shown.max)); let visible = figcraft_geom::Rect::new(a.x, a.y, b.x, b.y); let moving = p.fling.is_some() || p.drag_scroll.is_some() || p.wheel.is_some(); - if let Some(d) = p.detail_texture(ctx, &l.disp, p.current, px, visible, moving, now) { + if let Some(d) = p.detail_texture(ctx, &l.disp, p.current, px, to.bounds, visible, moving, now) { on_clip.image(d.tex.id(), l.place.rect(d.bounds), uv, Color32::WHITE); } } diff --git a/docs/prototyping-parity.md b/docs/prototyping-parity.md index 3cb52d2b9..113e1de57 100644 --- a/docs/prototyping-parity.md +++ b/docs/prototyping-parity.md @@ -1,6 +1,6 @@ # Prototyping parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-08 · **Change:** patch (presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); `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) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-09 · **Change:** patch (presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); `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,7 +107,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Date | Change | Summary | |---|---|---| -| 2026-11-08 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it; transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | +| 2026-11-09 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it; transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | | 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. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0764fca6c..b801fb1fd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); justified Chinese, Japanese and Korean text, written without spaces, spreads each line's room between its characters so its right edge aligns (#1970); joining the two ends of a path broken open by a deleted point closes it again, so its fill and selection outline follow the new segment and its corner radius instead of a straight line across the gap (#1951); glass's docs say which centre splay bends away from and where a shape gets no core; glass bends towards its core, rounded rectangles 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, measured against the reference tool; bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%; last major: full re-measure against Figma desktop 126.10.7; rows for the community batches: Selection colors, smart-selection spacing and a Present tab (#753), `.fig` import fidelity, paste from another design app, a `.fig` copy from Save as; control requests while the window is minimised (#720); catalog counts re-measured; automation roots (#715); number variables in the text content picker (#629); frames and sections convert into each other (#719)) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** patch (presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); justified Chinese, Japanese and Korean text, written without spaces, spreads each line's room between its characters so its right edge aligns (#1970); joining the two ends of a path broken open by a deleted point closes it again, so its fill and selection outline follow the new segment and its corner radius instead of a straight line across the gap (#1951); glass's docs say which centre splay bends away from and where a shape gets no core; glass bends towards its core, rounded rectangles 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, measured against the reference tool; bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%; last major: full re-measure against Figma desktop 126.10.7; rows for the community batches: Selection colors, smart-selection spacing and a Present tab (#753), `.fig` import fidelity, paste from another design app, a `.fig` copy from Save as; control requests while the window is minimised (#720); catalog counts re-measured; automation roots (#715); number variables in the text content picker (#629); frames and sections convert into each other (#719)) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is @@ -652,7 +652,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| -| 2026-11-08 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it; transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | +| 2026-11-09 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it; transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`) draft catalog: 1,975 UI strings, 641 command labels and 31 menu wordings, clean-room from the English source; zh-TW, zh-HK, zh-MO and zh-Hant read it, explicit Hans stays Simplified; Noto Sans CJK TC then Taiwan system faces; no bundled font; native review pending. Numbers unchanged | | 2026-11-04 | patch | M4, #1970: justified Chinese, Japanese and Korean text, written without spaces between words, aligns its right edge: the room on each line but a paragraph's last goes between its characters, each a word of its own as for line breaking ("Justify aligns the first word in each line of text to the left-most edge, and the last to the right-most edge"), wherever a line could break there, so none opens before a full stop or closing bracket, nor after an opening one. Latin text widens its spaces as before; mixed text widens both. A gap is reordered with the line's runs as a space of no width would be, so one beside a Hebrew word in Chinese text, or beside a Chinese word within that Hebrew, opens beside the word, not inside it. `figcraft_text::breaks::justify_between`, beside `break_between`, says where. Evidence: `tests::justified_ideographs_spread_the_room_between_characters` (fails on main). | | 2026-11-04 | patch | M8, #1951 (#1506 again): a path broken open by deleting a point (Delete, not Shift+Delete) is filled closed by a straight line across the gap, as an open path's fill is; joining its two ends again (the pen onto the other end, Connect, ⌘J) left the loop without the new segment, so once the points were rounded the fill and the selection outline ran straight across while the stroke followed the segment and its arcs. Joining now closes the loop through the new segment ("Click to close the path."; "You can use the Paint tool to add fills to any closed regions of a vector network."): `ops::connect` puts it into the loop whose segments are the chain between the ends, at the gap and in the loop's own order, so a hole keeps its winding whichever end was clicked first; a loop listed out of walking order is left as it was. Evidence: `vectoredit::tests::a_rounded_chamfer_made_other_ways_fills_along_its_arcs` (fails on main: the loop kept 4 of 5 segments), `a_rounded_chamfer_cut_in_the_editor_fills_along_its_arcs` (Shift+Delete, with and without a region fill), `doc::tests::a_chamfered_rectangles_rounded_fill_is_cut_at_every_point` (fill, region path and stroke agree for every loop order and segment direction of a chamfered rectangle). | From 3053b771102405096c47b4c99375af0fe48f30b4 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 8 Nov 2026 20:07:14 -0500 Subject: [PATCH 003/114] M3: the Scale tool keeps variable-bound lengths bound on an instance (value x its scale) and bakes them elsewhere (#2090) Cause: scale_node baked the factor into every length, then the command's normalize re-applied the variable bindings of the scaled subtree and wrote each variable's plain value back, so a bound gap or radius snapped back to the unscaled value. Fix: Node gets scale_factor (default 1, not saved at 1, last collab Prop). scale_node makes an instance multiply its factor (clamped 1e-3..1e3) and keep its bindings; apply_bindings_matching draws a bound length at value x the factors of the instance and the instances around it. Any other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled. The gesture preview's detach_edited leaves an instance whose factor changed alone. The instance rebuild carries the factor. Verified: scale_bound_values_tests (instance via transform.scale incl. mode switch and rebuild, the K drag and its undo, save and reopen, a plain frame). Only the gap was measured in Figma; radius, stroke weight and font size are assumed to follow it, and main components are unmeasured. Not changed: .fig import setting the factor, list and text-run bindings, the properties panel label, .fig export. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove and measured; Fable 5.1 briefed; Sonnet 5.5 wrote at medium --- crates/collab/src/change.rs | 1 + crates/doc/src/node.rs | 11 ++ crates/engine/src/assets/components/sync.rs | 2 + crates/engine/src/cmd/arrange.rs | 14 ++ crates/engine/src/cmd/styles.rs | 56 ++++++++ crates/engine/src/lib.rs | 2 + crates/engine/src/scale_bound_values_tests.rs | 130 ++++++++++++++++++ docs/components-parity.md | 3 +- docs/ui-parity.md | 3 +- 9 files changed, 220 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/scale_bound_values_tests.rs diff --git a/crates/collab/src/change.rs b/crates/collab/src/change.rs index 442376f37..6ebe9e0e4 100644 --- a/crates/collab/src/change.rs +++ b/crates/collab/src/change.rs @@ -183,6 +183,7 @@ node_props! { DevResources => dev_resources, Measurements => measurements, Board => board, + ScaleFactor => scale_factor, } /// A document-level property. Lists of entries with ids (styles, comments, variable collections, diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 5b90b3bff..338984638 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -511,6 +511,10 @@ pub struct Node { /// Explicit variable modes (collection → mode) set on this container. #[serde(default, skip_serializing_if = "is_default")] pub var_modes: BTreeMap, + /// An instance's scale factor (the Scale tool): the variables bound on its layers draw at their + /// value times this, and times the factors of the instances around it. 1 on everything else. + #[serde(default = "one64", skip_serializing_if = "is_one64")] + pub scale_factor: f64, /// In a boolean group: how this operand combines with the operands below it (`None`: the /// group's operation). Ignored for the bottom operand and outside boolean groups. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -571,6 +575,9 @@ pub(crate) fn yes() -> bool { fn one() -> f32 { 1.0 } +fn one64() -> f64 { + 1.0 +} fn pass() -> BlendMode { BlendMode::PassThrough } @@ -588,6 +595,9 @@ pub(crate) fn is_default(v: &T) -> bool { fn is_yes(v: &bool) -> bool { *v == yes() } +fn is_one64(v: &f64) -> bool { + *v == 1.0 +} fn is_one(v: &f32) -> bool { *v == one() } @@ -730,6 +740,7 @@ impl Node { styles: StyleRefs::default(), bound: BTreeMap::new(), var_modes: BTreeMap::new(), + scale_factor: 1.0, bool_op: None, constrain_proportions: false, source: None, diff --git a/crates/engine/src/assets/components/sync.rs b/crates/engine/src/assets/components/sync.rs index 7b34c33c2..90304c8f4 100644 --- a/crates/engine/src/assets/components/sync.rs +++ b/crates/engine/src/assets/components/sync.rs @@ -350,6 +350,8 @@ fn fresh_root(doc: &Document, root: &mut Node, comp: &Node, inst: NodeId, compon fresh.locked = root.locked; fresh.visible = root.visible; fresh.var_modes = root.var_modes.clone(); + // The scale an instance was given (a nested copy's own factor comes from its main layer). + fresh.scale_factor = root.scale_factor; fresh.is_mask = root.is_mask; fresh.exposed = root.exposed; fresh.guides = root.guides.clone(); diff --git a/crates/engine/src/cmd/arrange.rs b/crates/engine/src/cmd/arrange.rs index 88146ea95..a5725521c 100644 --- a/crates/engine/src/cmd/arrange.rs +++ b/crates/engine/src/cmd/arrange.rs @@ -399,9 +399,17 @@ fn turn_pivot(s: &Session, ids: &[NodeId]) -> Result> { Ok(ds.moved_origin().filter(|_| ds.selection == ids).or_else(|| ds.doc.bounds_of(&roots(&ds.doc, ids)).map(|b| b.center()))) } +/// The range an instance's scale factor stays in (the same range `.fig` files allow). +const MIN_SCALE_FACTOR: f64 = 1e-3; +const MAX_SCALE_FACTOR: f64 = 1e3; + /// Scale a node and everything in it uniformly (the Scale tool): sizes and positions (whatever /// the children's constraints), strokes, effects, radii, auto layout spacing, min/max sizes, /// layout grids, ruler guides, tiled images and text sizes. +/// +/// Variable-bound lengths follow the incumbent (#2090): an instance multiplies its scale factor and +/// keeps its bindings, which draw at the variable's value times the factor; any other layer not +/// inside an instance keeps the scaled value and drops the binding of each length it scaled. pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { let k = if k.is_finite() && k > 0.0 { k } else { return Ok(()) }; let sub = doc.subtree(id); @@ -410,6 +418,7 @@ pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { // changed with an ancestor's size for what constraints give, so the next rebuild of the // instance would put them back at their main's size (#922). let in_instance: Vec = sub.iter().enumerate().map(|(depth, i)| depth > 0 && crate::components::inside_instance(doc, *i)).collect(); + let nested: Vec = sub.iter().map(|i| crate::components::inside_instance(doc, *i)).collect(); let tiles = |paints: &mut Vec| { for p in paints { if let figcraft_color::PaintKind::Image(img) = &mut p.kind @@ -422,6 +431,11 @@ pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { for (depth, i) in sub.iter().enumerate() { let n = doc.get_mut(*i)?; let (w0, h0, t0) = (n.width, n.height, n.transform); + if matches!(n.kind, NodeKind::Instance { .. }) { + n.scale_factor = (n.scale_factor * k).clamp(MIN_SCALE_FACTOR, MAX_SCALE_FACTOR); + } else if !nested.get(depth).copied().unwrap_or(false) && !n.bound.is_empty() { + n.bound.retain(|field, _| !super::styles::LENGTH_FIELDS.contains(&field.as_str())); + } tiles(&mut n.fills); tiles(&mut n.strokes); let cl = &mut n.child_layout; diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index 9ba420c43..7b6947b29 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -1096,6 +1096,10 @@ pub(crate) fn bound_before(doc: &Document, ids: &[NodeId]) -> Vec]) { for old in before { let Some(n) = doc.node(old.id) else { continue }; + // An instance the Scale tool scaled keeps its bindings: they draw at its new scale (#2090). + if n.scale_factor != old.scale_factor { + continue; + } let edited: Vec = n .bound .keys() @@ -1239,6 +1243,55 @@ pub(crate) fn apply_paint_bindings_on_load(doc: &mut Document) { doc.mark_dirty(pending); } +/// The bound fields holding a length: what the Scale tool scales, so what an instance's scale +/// factor multiplies a number variable by (#2090). +pub(crate) const LENGTH_FIELDS: &[&str] = &[ + "width", + "height", + "w", + "h", + "gap", + "itemSpacing", + "columnGap", + "crossGap", + "counterAxisSpacing", + "rowGap", + "padding", + "paddingTop", + "paddingRight", + "paddingBottom", + "paddingLeft", + "paddingHorizontal", + "paddingVertical", + "cornerRadius", + "topLeftRadius", + "topRightRadius", + "bottomRightRadius", + "bottomLeftRadius", + "strokeWeight", + "strokeTopWeight", + "strokeRightWeight", + "strokeBottomWeight", + "strokeLeftWeight", + "minWidth", + "maxWidth", + "minHeight", + "maxHeight", + "fontSize", + "lineHeight", + "letterSpacing", + "paragraphSpacing", + "paragraphIndent", +]; + +/// The scale a layer's lengths are drawn at: the product of the scale factors of the instances it +/// is or sits in. +fn scale_of(doc: &Document, id: NodeId) -> f64 { + let factor = |i: NodeId| doc.node(i).filter(|n| matches!(n.kind, NodeKind::Instance { .. })).map_or(1.0, |n| n.scale_factor); + let k = std::iter::once(id).chain(doc.ancestors(id)).map(factor).product::(); + if k.is_finite() && k > 0.0 { k } else { 1.0 } +} + /// Re-apply the variable bindings whose field passes `include`, on the `only` nodes (every bound /// node when `None`). Auto layout fields wait while their node has no auto layout. fn apply_bindings_matching(doc: &mut Document, only: Option<&std::collections::BTreeSet>, include: impl Fn(&str) -> bool) { @@ -1253,6 +1306,7 @@ fn apply_bindings_matching(doc: &mut Document, only: Option<&std::collections::B }; for id in bound { let modes = doc.modes_for(id); + let scale = scale_of(doc, id); let Some(n) = doc.node(id) else { continue }; let binds = n.bound.clone(); let has_layout = n.layout.is_some(); @@ -1300,6 +1354,8 @@ fn apply_bindings_matching(doc: &mut Document, only: Option<&std::collections::B VariableValue::Number(x) if field == "arcSweep" => json!(x * 3.6), VariableValue::Number(x) if field == "arcInner" => json!(x / 100.0), VariableValue::Number(x) if field == "characters" => json!(trim_num(*x)), + // An instance's scale factor scales the lengths its variables give. + VariableValue::Number(x) if scale != 1.0 && LENGTH_FIELDS.contains(&field.as_str()) => json!(x * scale), VariableValue::Number(x) => json!(x), VariableValue::String(x) => json!(x), VariableValue::Boolean(b) => json!(b), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 302e7053e..8da1c651a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -531,6 +531,8 @@ mod save_disk_changes_tests; #[cfg(test)] mod save_format_tests; #[cfg(test)] +mod scale_bound_values_tests; +#[cfg(test)] mod scale_tool_tests; #[cfg(test)] mod scaled_instance_tests; diff --git a/crates/engine/src/scale_bound_values_tests.rs b/crates/engine/src/scale_bound_values_tests.rs new file mode 100644 index 000000000..45f5f1644 --- /dev/null +++ b/crates/engine/src/scale_bound_values_tests.rs @@ -0,0 +1,130 @@ +//! The Scale tool and variable-bound lengths (#2090): an instance keeps its bindings and draws them +//! at the variable's value times its scale factor; a plain frame bakes the scaled value and drops +//! the binding of each length it scaled (what the incumbent does, measured for the gap). + +use serde_json::{Value, json}; + +use crate::Session; +use crate::components::tests::{copy_of, ex, healthy, idv, node}; +use figcraft_doc::NodeId; + +/// The scale factor an instance stores (1 when the file has none), read through the saved form. +fn factor(s: &Session, id: NodeId) -> f64 { + serde_json::to_value(node(s, id)).ok().and_then(|v| v.get("scale_factor").and_then(Value::as_f64)).unwrap_or(1.0) +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +fn gap(s: &Session, id: NodeId) -> f64 { + node(s, id).layout.map(|l| l.gap).unwrap_or(f64::NAN) +} + +/// Variables Gap = 8 (Dark 12) and Round = 4; a 56 x 24 horizontal auto layout frame holding two +/// 24 x 24 rectangles, its gap bound to Gap and the first rectangle's corner radius to Round. +/// Returns the frame and the first rectangle. +fn bound_row(s: &mut Session) -> (NodeId, NodeId) { + ex(s, "variable.createCollection", json!({"name": "Theme", "modes": ["Light", "Dark"]})); + ex(s, "variable.create", json!({"collection": "Theme", "name": "Gap", "type": "number", "value": 8})); + ex(s, "variable.set", json!({"variable": "Gap", "mode": "Dark", "value": 12})); + ex(s, "variable.create", json!({"collection": "Theme", "name": "Round", "type": "number", "value": 4})); + let f = idv(&ex(s, "frame.create", json!({"x": 100, "y": 0, "width": 56, "height": 24, "name": "Row"}))); + ex(s, "node.set", json!({"id": f, "props": {"layout": "horizontal", "padding": 0, "gap": 8, "fills": []}})); + let a = idv(&ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 24, "height": 24, "parent": f}))); + ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 24, "height": 24, "parent": f})); + ex(s, "variable.bind", json!({"ids": [f], "field": "gap", "variable": "Gap"})); + ex(s, "variable.bind", json!({"ids": [a], "field": "cornerRadius", "variable": "Round"})); + assert!(near(gap(s, f), 8.0), "{}", gap(s, f)); + assert_eq!(node(s, a).corners.radii, [4.0; 4]); + (f, a) +} + +/// The row as a component with one instance; returns (main, first rectangle in main, instance). +fn row_instance(s: &mut Session) -> (NodeId, NodeId, NodeId) { + let (f, a) = bound_row(s); + let c = idv(&ex(s, "component.create", json!({"ids": [f]}))); + let i = idv(&ex(s, "instance.create", json!({"component": c, "x": 300, "y": 0}))); + (c, a, i) +} + +fn assert_bound_at_half(s: &Session, i: NodeId, a: NodeId, gap_now: f64, why: &str) { + let ia = copy_of(s, i, a); + assert!(near(gap(s, i), gap_now), "{why}: gap {}", gap(s, i)); + assert_eq!(node(s, ia).corners.radii, [2.0; 4], "{why}: radii"); + assert!(node(s, i).bound.contains_key("gap"), "{why}: gap binding kept"); + assert!(node(s, ia).bound.contains_key("cornerRadius"), "{why}: radius binding kept"); + let (n, ni) = (node(s, i), node(s, ia)); + assert!(!n.overrides.contains("gap") && !ni.overrides.contains("corners"), "{why}: {:?} {:?}", n.overrides, ni.overrides); +} + +#[test] +fn a_scaled_instance_draws_bound_gap_and_radius_at_the_factor_and_keeps_the_bindings() { + let mut s = Session::new(); + let (c, a, i) = row_instance(&mut s); + ex(&mut s, "transform.scale", json!({"ids": [i], "factor": 0.5})); + assert!(near(factor(&s, i), 0.5), "factor {}", factor(&s, i)); + assert_bound_at_half(&s, i, a, 4.0, "scaled"); + healthy(&s); + ex(&mut s, "variable.setMode", json!({"ids": [i], "collection": "Theme", "mode": "Dark"})); + assert_bound_at_half(&s, i, a, 6.0, "dark"); + ex(&mut s, "node.set", json!({"id": c, "props": {"fills": ["#ff0000"]}})); + ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 2, "height": 2, "parent": c})); + assert_bound_at_half(&s, i, a, 6.0, "rebuilt"); + assert!(near(factor(&s, i), 0.5), "factor after rebuild {}", factor(&s, i)); + healthy(&s); +} + +#[test] +fn scaling_an_instance_with_the_tool_scales_bound_values_and_undo_takes_them_back() { + use crate::tools::{PointerEvent, PointerKind}; + let mut s = Session::new(); + let (_c, a, i) = row_instance(&mut s); + ex(&mut s, "select.set", json!({"ids": [i]})); + ex(&mut s, "tool.scale", json!({})); + // The bottom right handle of the 56 x 24 box at (300, 0), to half its size about the top left. + for (kind, (x, y)) in + [(PointerKind::Down, (356.0, 24.0)), (PointerKind::Move, (340.0, 18.0)), (PointerKind::Move, (328.0, 12.0)), (PointerKind::Up, (328.0, 12.0))] + { + s.pointer(&PointerEvent::at(kind, x, y, 1.0)).unwrap(); + } + assert!(near(factor(&s, i), 0.5), "factor {}", factor(&s, i)); + assert_bound_at_half(&s, i, a, 4.0, "dragged"); + s.undo().unwrap(); + assert!(near(factor(&s, i), 1.0), "factor after undo {}", factor(&s, i)); + assert!(near(gap(&s, i), 8.0), "gap after undo {}", gap(&s, i)); + assert!(node(&s, i).overrides.is_empty() && node(&s, copy_of(&s, i, a)).overrides.is_empty()); + healthy(&s); +} + +#[test] +fn a_file_with_a_scaled_instance_keeps_its_factor_and_bound_gap_after_save_and_open() { + let mut s = Session::new(); + let (_c, a, i) = row_instance(&mut s); + let plain = serde_json::to_value(node(&s, i)).unwrap(); + assert!(plain.get("scale_factor").is_none(), "an unscaled instance saves no factor: {plain}"); + ex(&mut s, "transform.scale", json!({"ids": [i], "factor": 0.5})); + let dir = std::env::temp_dir().join(format!("figcraft-scale-bound-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("scaled.figcraft"); + ex(&mut s, "file.saveAs", json!({"path": path.to_string_lossy()})); + let mut back = Session::empty(); + back.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + assert!(near(factor(&back, i), 0.5), "factor {}", factor(&back, i)); + assert_bound_at_half(&back, i, a, 4.0, "reopened"); + healthy(&back); +} + +#[test] +fn scaling_a_plain_frame_bakes_its_bound_gap_and_drops_the_binding() { + let mut s = Session::new(); + let (f, a) = bound_row(&mut s); + ex(&mut s, "transform.scale", json!({"ids": [f], "factor": 0.5})); + assert!(near(gap(&s, f), 4.0), "gap {}", gap(&s, f)); + assert!(!node(&s, f).bound.contains_key("gap"), "{:?}", node(&s, f).bound); + assert_eq!(node(&s, a).corners.radii, [2.0; 4]); + assert!(!node(&s, a).bound.contains_key("cornerRadius"), "{:?}", node(&s, a).bound); + assert!(near(factor(&s, f), 1.0)); + healthy(&s); +} diff --git a/docs/components-parity.md b/docs/components-parity.md index d6b1ee5e6..a86a88114 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -68,7 +68,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | 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 | -| Bindings: fills, strokes, effects, opacity, padding, gaps, sizes, radius, font family/style, font size/weight, line height, letter spacing, paragraph spacing/indent, text, visibility, layout grids, instance properties | done | type-checked per field, an effect's only where its effect has the field (as in effect styles); glass fields too (light angle, intensity, refraction, depth, dispersion, frost and splay, percentages as the Design panel shows them, a light angle past ±180 turned round); number variables fill text content; the Design panel's font family and font style menus start with Apply variable (string variables), and a bound one shows its variable in place of the menu; a colour variable bound to a solid paint brings its whole colour, alpha included, once (the paint's opacity restarts at 100% on binding, an opacity set while bound multiplies on top; unbinding moves the alpha back into the opacity) | +| Bindings: fills, strokes, effects, opacity, padding, gaps, sizes, radius, font family/style, font size/weight, line height, letter spacing, paragraph spacing/indent, text, visibility, layout grids, instance properties | done | type-checked per field, an effect's only where its effect has the field (as in effect styles); glass fields too (light angle, intensity, refraction, depth, dispersion, frost and splay, percentages as the Design panel shows them, a light angle past ±180 turned round); number variables fill text content; the Design panel's font family and font style menus start with Apply variable (string variables), and a bound one shows its variable in place of the menu; a colour variable bound to a solid paint brings its whole colour, alpha included, once (the paint's opacity restarts at 100% on binding, an opacity set while bound multiplies on top; unbinding moves the alpha back into the opacity); on a scaled instance a bound length draws at the variable's value times the instance's scale factor (#2090) | | Explicit modes per frame, library collections' modes | done | stored variable and collection references resolve by exact id in export, library copies and swaps, imported aliases, alias deletion and cycle checks, Dev Inspect, the library mode picker and prototype playback; a collection or variable named like another's id no longer stands in for it there | | Gradient stops and variant properties bound to variables | done | a stop's binding follows it when earlier stops are removed | | Extended collections | done | this file's collections (Extend collection on a collection's row; following its edits at once, chains included) and library collections, including a library's own extended collections (chains through libraries); overrides per mode with reset; follow library updates, variables new to the library collection being an update of their own; modes inherited. Checked with synthetic libraries only ([gaps](gaps.md) #14) | @@ -79,6 +79,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled. Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it); the other lengths are assumed to follow, and a main component is unmeasured. Tests: `scale_bound_values_tests`. | | 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. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index aa0ef25bd..4d3c37a51 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -67,7 +67,7 @@ interaction feel not yet compared. | Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | -| Scale tool (K): handles about an anchor, live factor, panel | done | | +| Scale tool (K): handles about an anchor, live factor, panel | done | variable-bound lengths: an instance keeps its bindings and draws them at the variable's value times its scale factor (a field of the instance, kept through rebuilds and saves); other layers keep the scaled value and drop the binding of each length scaled (#2090); only the gap was measured in the incumbent, the other lengths are assumed to follow it | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; thresholds not yet compared with Figma's (`guide_snap_tests`) | | Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing | @@ -187,6 +187,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled. Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it); the other lengths are assumed to follow, and a main component is unmeasured. Tests: `scale_bound_values_tests`. | | 2026-11-02 | patch | Shortcuts: a Cmd/Ctrl-click on a padding field (the horizontal or vertical pair, or a side with Individual padding open) makes the value typed go to all four sides, in one undo step (Guide to auto layout, Keyboard shortcut guide); a plain click still edits that axis or side alone. A documented gesture row: 134 documented, 133 bound. Test: `padding_individual_tests` | | 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 | 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`. | From 72e8b4ca940ed67736b217f427ae64187164f984 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 8 Nov 2026 20:13:01 -0500 Subject: [PATCH 004/114] M3: detaching a scaled instance keeps its lengths as drawn and drops their variables (#2090) Measured in Figma: detaching a 0.5x instance whose gap is bound leaves a plain frame with the gap at the scaled value and no variable. component.detach kept the bindings but dropped the factor, so the gap jumped back to the variable's value. Now the detached frame's own layers drop the bindings of their length fields, the instances inside it take its factor on, and its own factor goes back to 1. Test detaching_a_scaled_instance_keeps_its_lengths_and_drops_their_variables (gap 8 before, 4 now). Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove, measured and wrote --- crates/engine/src/cmd/arrange.rs | 4 ++-- crates/engine/src/cmd/component/instance.rs | 17 ++++++++++++++++ crates/engine/src/scale_bound_values_tests.rs | 20 +++++++++++++++++++ docs/components-parity.md | 2 +- docs/ui-parity.md | 2 +- 5 files changed, 41 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/arrange.rs b/crates/engine/src/cmd/arrange.rs index a5725521c..4aa42f2d8 100644 --- a/crates/engine/src/cmd/arrange.rs +++ b/crates/engine/src/cmd/arrange.rs @@ -400,8 +400,8 @@ fn turn_pivot(s: &Session, ids: &[NodeId]) -> Result> { } /// The range an instance's scale factor stays in (the same range `.fig` files allow). -const MIN_SCALE_FACTOR: f64 = 1e-3; -const MAX_SCALE_FACTOR: f64 = 1e3; +pub(crate) const MIN_SCALE_FACTOR: f64 = 1e-3; +pub(crate) const MAX_SCALE_FACTOR: f64 = 1e3; /// Scale a node and everything in it uniformly (the Scale tool): sizes and positions (whatever /// the children's constraints), strokes, effects, radii, auto layout spacing, min/max sizes, diff --git a/crates/engine/src/cmd/component/instance.rs b/crates/engine/src/cmd/component/instance.rs index 86af6d54b..3b6f8f17d 100644 --- a/crates/engine/src/cmd/component/instance.rs +++ b/crates/engine/src/cmd/component/instance.rs @@ -36,6 +36,23 @@ pub(super) fn detach(s: &mut Session, p: &Value) -> Result { n.prop_refs.remove("mainComponent"); // No properties left to drive. n.bound.retain(|k, _| !k.starts_with(PROP_BINDING)); + // A scaled instance's lengths stay as drawn (#2090, measured): its own layers keep the + // scaled values and drop their variables, and the instances in it take its scale on. + let k = std::mem::replace(&mut n.scale_factor, 1.0); + if k != 1.0 { + for d in doc.subtree(i) { + let own = !inside_instance(doc, d); + let Some(n) = doc.node_mut(d) else { continue }; + if !own { + continue; + } + if matches!(n.kind, NodeKind::Instance { .. }) { + n.scale_factor = (n.scale_factor * k).clamp(crate::cmd::arrange::MIN_SCALE_FACTOR, crate::cmd::arrange::MAX_SCALE_FACTOR); + } else { + n.bound.retain(|f, _| !crate::cmd::styles::LENGTH_FIELDS.contains(&f.as_str())); + } + } + } for nn in nested { rebase_instance(doc, nn); } diff --git a/crates/engine/src/scale_bound_values_tests.rs b/crates/engine/src/scale_bound_values_tests.rs index 45f5f1644..567592e28 100644 --- a/crates/engine/src/scale_bound_values_tests.rs +++ b/crates/engine/src/scale_bound_values_tests.rs @@ -128,3 +128,23 @@ fn scaling_a_plain_frame_bakes_its_bound_gap_and_drops_the_binding() { assert!(near(factor(&s, f), 1.0)); healthy(&s); } + +#[test] +fn detaching_a_scaled_instance_keeps_its_lengths_and_drops_their_variables() { + // Measured: detaching a 0.5x instance whose gap is bound leaves a plain frame with the gap + // at the scaled value and no variable. + let mut s = Session::new(); + let (_c, a, i) = row_instance(&mut s); + ex(&mut s, "transform.scale", json!({"ids": [i], "factor": 0.5})); + let ia = copy_of(&s, i, a); + ex(&mut s, "component.detach", json!({"ids": [i]})); + assert!(near(gap(&s, i), 4.0), "gap {}", gap(&s, i)); + assert_eq!(node(&s, ia).corners.radii, [2.0; 4]); + assert!(!node(&s, i).bound.contains_key("gap"), "the gap's variable goes"); + assert!(!node(&s, ia).bound.contains_key("cornerRadius"), "the radius's variable goes"); + assert!(near(factor(&s, i), 1.0), "a frame has no scale factor: {}", factor(&s, i)); + // The variables no longer reach it. + ex(&mut s, "variable.set", json!({"variable": "Gap", "mode": "Light", "value": 20})); + assert!(near(gap(&s, i), 4.0), "gap after the variable changed {}", gap(&s, i)); + healthy(&s); +} diff --git a/docs/components-parity.md b/docs/components-parity.md index a86a88114..6dc8514e3 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -79,7 +79,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| -| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled. Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it); the other lengths are assumed to follow, and a main component is unmeasured. Tests: `scale_bound_values_tests`. | +| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled, and so does a scaled instance's own layer when the instance is detached (the instances inside it take its factor on). Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it, and detaching a scaled instance bakes it); the other lengths are assumed to follow, and a main component is unmeasured. Tests: `scale_bound_values_tests`. | | 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. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4d3c37a51..7c170f80f 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -187,7 +187,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| -| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled. Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it); the other lengths are assumed to follow, and a main component is unmeasured. Tests: `scale_bound_values_tests`. | +| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled, and so does a scaled instance's own layer when the instance is detached (the instances inside it take its factor on). Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it, and detaching a scaled instance bakes it); the other lengths are assumed to follow, and a main component is unmeasured. Tests: `scale_bound_values_tests`. | | 2026-11-02 | patch | Shortcuts: a Cmd/Ctrl-click on a padding field (the horizontal or vertical pair, or a side with Individual padding open) makes the value typed go to all four sides, in one undo step (Guide to auto layout, Keyboard shortcut guide); a plain click still edits that axis or side alone. A documented gesture row: 134 documented, 133 bound. Test: `padding_individual_tests` | | 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 | 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`. | From 0636a3e6a041a47f72eb1892f78edbeae69dd844 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 8 Nov 2026 22:59:00 -0500 Subject: [PATCH 005/114] M3: a scaled instance's nested instances and its other conversions keep the lengths as drawn (#2134 review) Scaling a subtree now gives the scale factor only to instances with no instance above them in the subtree (scale_of already multiplies the outer factor, so nested ones drew at k x k and jumped back on rebuild). Detach's baking moved to styles::bake_scale; bake_stale_scales runs it after a library import turns an instance with a missing main into a frame, after cycle-breaking detach, and after Restore main component (by analogy with Detach, not measured in Figma). Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.1 reviewed; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/engine/src/assets/components/cycles.rs | 1 + crates/engine/src/assets/library.rs | 5 + crates/engine/src/cmd/arrange.rs | 23 ++++- crates/engine/src/cmd/component/instance.rs | 18 +--- crates/engine/src/cmd/styles.rs | 33 +++++++ crates/engine/src/scale_bound_values_tests.rs | 98 +++++++++++++++++++ 6 files changed, 162 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/assets/components/cycles.rs b/crates/engine/src/assets/components/cycles.rs index 0d9b56f40..1d33b5c80 100644 --- a/crates/engine/src/assets/components/cycles.rs +++ b/crates/engine/src/assets/components/cycles.rs @@ -169,6 +169,7 @@ fn detach_all(doc: &mut Document, top: NodeId) { n.overrides.clear(); n.prop_refs.clear(); } + crate::cmd::styles::bake_stale_scales(doc, top); } /// Break every loop of components containing each other's instances (a file from elsewhere, or diff --git a/crates/engine/src/assets/library.rs b/crates/engine/src/assets/library.rs index d9107ad63..89fe984a9 100644 --- a/crates/engine/src/assets/library.rs +++ b/crates/engine/src/assets/library.rs @@ -942,6 +942,10 @@ pub fn import(doc: &mut Document, lib: &PublishedLibrary, keys: &[NodeId], updat nodes.push(n); } doc.paste_nodes(&nodes, &map, *u, store, None)?; + // An instance whose main is missing became a plain frame: its lengths stay as drawn (#2090). + if let Some(root) = map.get(u).copied() { + crate::cmd::styles::bake_stale_scales(doc, root); + } } copy_images(doc, src, &hashes); for (u, sub) in &write { @@ -1182,6 +1186,7 @@ fn merge_components( } let Some(root) = remote.get(&r.root).copied() else { continue }; doc.paste_nodes(&nodes, &remote, r.root, store, None)?; + crate::cmd::styles::bake_stale_scales(doc, root); let ids = r.ids.iter().filter_map(|(lib, theirs)| remote.get(theirs).map(|l| (*lib, *l))).collect(); doc.libraries_mut().components.push(ImportedComponent { root, ids, ..r.clone() }); } diff --git a/crates/engine/src/cmd/arrange.rs b/crates/engine/src/cmd/arrange.rs index 4aa42f2d8..b6e5362c5 100644 --- a/crates/engine/src/cmd/arrange.rs +++ b/crates/engine/src/cmd/arrange.rs @@ -419,6 +419,25 @@ pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { // instance would put them back at their main's size (#922). let in_instance: Vec = sub.iter().enumerate().map(|(depth, i)| depth > 0 && crate::components::inside_instance(doc, *i)).collect(); let nested: Vec = sub.iter().map(|i| crate::components::inside_instance(doc, *i)).collect(); + // An instance inside another instance of the subtree is covered by the outer factor through + // `scale_of`'s product (#2090); only an instance with no instance above it, up to `id`, takes k. + let covered: Vec = sub + .iter() + .map(|i| { + if *i == id { + return false; + } + for a in doc.ancestors(*i) { + if doc.node(a).is_some_and(|n| matches!(n.kind, NodeKind::Instance { .. })) { + return true; + } + if a == id { + break; + } + } + false + }) + .collect(); let tiles = |paints: &mut Vec| { for p in paints { if let figcraft_color::PaintKind::Image(img) = &mut p.kind @@ -432,7 +451,9 @@ pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { let n = doc.get_mut(*i)?; let (w0, h0, t0) = (n.width, n.height, n.transform); if matches!(n.kind, NodeKind::Instance { .. }) { - n.scale_factor = (n.scale_factor * k).clamp(MIN_SCALE_FACTOR, MAX_SCALE_FACTOR); + if !covered.get(depth).copied().unwrap_or(false) { + n.scale_factor = (n.scale_factor * k).clamp(MIN_SCALE_FACTOR, MAX_SCALE_FACTOR); + } } else if !nested.get(depth).copied().unwrap_or(false) && !n.bound.is_empty() { n.bound.retain(|field, _| !super::styles::LENGTH_FIELDS.contains(&field.as_str())); } diff --git a/crates/engine/src/cmd/component/instance.rs b/crates/engine/src/cmd/component/instance.rs index 3b6f8f17d..f383304c5 100644 --- a/crates/engine/src/cmd/component/instance.rs +++ b/crates/engine/src/cmd/component/instance.rs @@ -38,21 +38,7 @@ pub(super) fn detach(s: &mut Session, p: &Value) -> Result { n.bound.retain(|k, _| !k.starts_with(PROP_BINDING)); // A scaled instance's lengths stay as drawn (#2090, measured): its own layers keep the // scaled values and drop their variables, and the instances in it take its scale on. - let k = std::mem::replace(&mut n.scale_factor, 1.0); - if k != 1.0 { - for d in doc.subtree(i) { - let own = !inside_instance(doc, d); - let Some(n) = doc.node_mut(d) else { continue }; - if !own { - continue; - } - if matches!(n.kind, NodeKind::Instance { .. }) { - n.scale_factor = (n.scale_factor * k).clamp(crate::cmd::arrange::MIN_SCALE_FACTOR, crate::cmd::arrange::MAX_SCALE_FACTOR); - } else { - n.bound.retain(|f, _| !crate::cmd::styles::LENGTH_FIELDS.contains(&f.as_str())); - } - } - } + crate::cmd::styles::bake_scale(doc, i); for nn in nested { rebase_instance(doc, nn); } @@ -381,6 +367,8 @@ pub(super) fn restore_main(s: &mut Session, p: &Value) -> Result { rebase_instance(doc, m); } } + // The instance becomes the main: its lengths stay as drawn (by analogy with Detach, #2090). + crate::cmd::styles::bake_stale_scales(doc, component); s.set_selection(vec![component]); Ok(json!({"id": component})) } diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index 7b6947b29..756e5b16d 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -1292,6 +1292,39 @@ fn scale_of(doc: &Document, id: NodeId) -> f64 { if k.is_finite() && k > 0.0 { k } else { 1.0 } } +/// A layer that stops being an instance keeps its lengths as drawn (#2090, measured for Detach): +/// its own layers drop their length variables and the instances in it take its scale on. The +/// layer must no longer be an instance. +pub(crate) fn bake_scale(doc: &mut Document, id: NodeId) { + let Some(n) = doc.node_mut(id) else { return }; + let k = std::mem::replace(&mut n.scale_factor, 1.0); + if k == 1.0 { + return; + } + for d in doc.subtree(id) { + let own = !crate::components::inside_instance(doc, d); + let Some(n) = doc.node_mut(d) else { continue }; + if !own { + continue; + } + if matches!(n.kind, NodeKind::Instance { .. }) { + n.scale_factor = (n.scale_factor * k).clamp(super::arrange::MIN_SCALE_FACTOR, super::arrange::MAX_SCALE_FACTOR); + } else { + n.bound.retain(|f, _| !LENGTH_FIELDS.contains(&f.as_str())); + } + } +} + +/// [`bake_scale`] for every layer under `root` that is no longer an instance but still has a +/// scale factor (a conversion left it behind). +pub(crate) fn bake_stale_scales(doc: &mut Document, root: NodeId) { + for d in doc.subtree(root) { + if doc.node(d).is_some_and(|n| !matches!(n.kind, NodeKind::Instance { .. }) && n.scale_factor != 1.0) { + bake_scale(doc, d); + } + } +} + /// Re-apply the variable bindings whose field passes `include`, on the `only` nodes (every bound /// node when `None`). Auto layout fields wait while their node has no auto layout. fn apply_bindings_matching(doc: &mut Document, only: Option<&std::collections::BTreeSet>, include: impl Fn(&str) -> bool) { diff --git a/crates/engine/src/scale_bound_values_tests.rs b/crates/engine/src/scale_bound_values_tests.rs index 567592e28..eb936a042 100644 --- a/crates/engine/src/scale_bound_values_tests.rs +++ b/crates/engine/src/scale_bound_values_tests.rs @@ -148,3 +148,101 @@ fn detaching_a_scaled_instance_keeps_its_lengths_and_drops_their_variables() { assert!(near(gap(&s, i), 4.0), "gap after the variable changed {}", gap(&s, i)); healthy(&s); } + +/// Main A holds an instance of main B (the bound row); returns (A, the instance of B in A, an +/// instance of A, the copy of that B instance inside it). +fn nested_instance(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) { + let (b, _a, _i) = row_instance(s); + let fa = idv(&ex(s, "frame.create", json!({"x": 0, "y": 200, "width": 100, "height": 60, "name": "Holder"}))); + let ib = idv(&ex(s, "instance.create", json!({"component": b, "x": 0, "y": 0, "parent": fa}))); + let a_main = idv(&ex(s, "component.create", json!({"ids": [fa]}))); + let ia = idv(&ex(s, "instance.create", json!({"component": a_main, "x": 500, "y": 0}))); + let inner = copy_of(s, ia, ib); + (a_main, ib, ia, inner) +} + +#[test] +fn an_instance_inside_a_scaled_instance_is_drawn_at_the_outer_factor_once() { + let mut s = Session::new(); + let (a_main, _ib, ia, inner) = nested_instance(&mut s); + assert!(near(gap(&s, inner), 8.0), "{}", gap(&s, inner)); + ex(&mut s, "transform.scale", json!({"ids": [ia], "factor": 0.5})); + assert!(near(factor(&s, ia), 0.5), "outer factor {}", factor(&s, ia)); + assert!(near(gap(&s, inner), 4.0), "the nested copy draws at 0.5 once: gap {}", gap(&s, inner)); + // A change to main A rebuilds the instance: the nested copy is still at 0.5. + ex(&mut s, "node.set", json!({"id": a_main, "props": {"fills": ["#ff0000"]}})); + ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 2, "height": 2, "parent": a_main})); + let inner = + s.doc().unwrap().subtree(ia).into_iter().find(|d| *d != ia && matches!(node(&s, *d).kind, figcraft_doc::NodeKind::Instance { .. })).unwrap(); + assert!(near(gap(&s, inner), 4.0), "after the main changed: gap {}", gap(&s, inner)); + healthy(&s); +} + +#[test] +fn restoring_the_main_from_a_scaled_instance_keeps_its_lengths_and_drops_their_variables() { + let mut s = Session::new(); + let (c, _a, i) = row_instance(&mut s); + let j = idv(&ex(&mut s, "instance.create", json!({"component": c, "x": 600, "y": 0}))); + ex(&mut s, "transform.scale", json!({"ids": [i], "factor": 0.5})); + ex(&mut s, "edit.delete", json!({"ids": [c]})); + let r = idv(&ex(&mut s, "component.restoreMain", json!({"id": i}))); + assert_eq!(r, c); + assert!(near(gap(&s, c), 4.0), "the restored main's gap {}", gap(&s, c)); + assert!(!node(&s, c).bound.contains_key("gap"), "the gap's variable goes: {:?}", node(&s, c).bound); + assert!(near(factor(&s, c), 1.0), "a main has no scale factor: {}", factor(&s, c)); + assert!(near(gap(&s, j), 4.0), "another instance re-links and draws the main's gap: {}", gap(&s, j)); + healthy(&s); +} + +#[test] +fn a_library_instance_whose_main_is_missing_lands_as_a_frame_with_the_lengths_as_drawn() { + let dir = std::env::temp_dir().join(format!("figcraft-scale-lib-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let lib_path = dir.join("kit.figcraft").to_string_lossy().to_string(); + let mut lib = Session::new(); + let (b, _a, _i) = row_instance(&mut lib); + let fa = idv(&ex(&mut lib, "frame.create", json!({"x": 0, "y": 200, "width": 100, "height": 60, "name": "Holder"}))); + let ib = idv(&ex(&mut lib, "instance.create", json!({"component": b, "x": 0, "y": 0, "parent": fa}))); + ex(&mut lib, "transform.scale", json!({"ids": [ib], "factor": 0.5})); + ex(&mut lib, "component.create", json!({"ids": [fa]})); + // The row's main goes: the library's instance has no main to bring along. + ex(&mut lib, "edit.delete", json!({"ids": [b]})); + ex(&mut lib, "library.publish", json!({"description": "Kit"})); + ex(&mut lib, "file.saveAs", json!({"path": lib_path})); + let mut s = Session::new(); + let r = ex(&mut s, "library.add", json!({"path": lib_path})); + let lid = r["id"].as_str().unwrap().to_string(); + let placed = idv(&ex(&mut s, "library.place", json!({"library": lid, "component": "Holder", "x": 300, "y": 300}))); + let main = match node(&s, placed).kind { + figcraft_doc::NodeKind::Component { .. } => placed, + figcraft_doc::NodeKind::Instance { component, .. } => component, + _ => panic!("not a component or instance"), + }; + let _ = std::fs::remove_dir_all(&dir); + let doc = s.doc().unwrap(); + let row = doc.subtree(main).into_iter().find(|d| *d != main && node(&s, *d).layout.is_some()).expect("the row frame"); + assert!(matches!(node(&s, row).kind, figcraft_doc::NodeKind::Frame), "{:?}", node(&s, row).kind); + assert!(near(gap(&s, row), 4.0), "gap {}", gap(&s, row)); + assert!(near(factor(&s, row), 1.0), "factor {}", factor(&s, row)); + assert!(!node(&s, row).bound.contains_key("gap"), "binding dropped: {:?}", node(&s, row).bound); +} + +#[test] +fn scaling_a_frame_holding_an_instance_drops_its_own_binding_and_scales_the_instance_once() { + let mut s = Session::new(); + let (c, a, _i) = row_instance(&mut s); + let f = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 400, "width": 200, "height": 60, "name": "Outer"}))); + ex(&mut s, "node.set", json!({"id": f, "props": {"layout": "horizontal", "padding": 0, "gap": 8, "fills": []}})); + let inner = idv(&ex(&mut s, "instance.create", json!({"component": c, "x": 0, "y": 0, "parent": f}))); + ex(&mut s, "variable.bind", json!({"ids": [f], "field": "gap", "variable": "Gap"})); + ex(&mut s, "transform.scale", json!({"ids": [f], "factor": 0.5})); + assert!(!node(&s, f).bound.contains_key("gap"), "{:?}", node(&s, f).bound); + assert!(near(gap(&s, f), 4.0), "frame gap {}", gap(&s, f)); + assert!(near(factor(&s, inner), 0.5), "inner factor {}", factor(&s, inner)); + assert_bound_at_half(&s, inner, a, 4.0, "inner"); + // Back to 1: no factor is saved. + ex(&mut s, "transform.scale", json!({"ids": [f], "factor": 2.0})); + let saved = serde_json::to_value(node(&s, inner)).unwrap(); + assert!(saved.get("scale_factor").is_none(), "{saved}"); + healthy(&s); +} From bd86309d9b90c4ccf7ea19ffa3bcb54820b70913 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 8 Nov 2026 23:33:44 -0500 Subject: [PATCH 006/114] M3: the parity status lines carry the #2090 change, and the Scale tool row its limits (#2134 review) Both docs got a 2026-11-09 revision row without their status line. The Scale tool row now lists what is not done yet: .fig import, list and text-run bindings, a layer scaled inside an instance, and a nested instance scaled inside a copy. Docs only. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- docs/components-parity.md | 2 +- docs/ui-parity.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/components-parity.md b/docs/components-parity.md index 6dc8514e3..32783cc52 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -1,6 +1,6 @@ # Components, variants, styles and variables parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** patch (the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); 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 diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 7c170f80f..2dbe838b4 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); 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 capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** patch (the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); 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 capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -67,7 +67,7 @@ interaction feel not yet compared. | Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | -| Scale tool (K): handles about an anchor, live factor, panel | done | variable-bound lengths: an instance keeps its bindings and draws them at the variable's value times its scale factor (a field of the instance, kept through rebuilds and saves); other layers keep the scaled value and drop the binding of each length scaled (#2090); only the gap was measured in the incumbent, the other lengths are assumed to follow it | +| Scale tool (K): handles about an anchor, live factor, panel | done | variable-bound lengths: an instance keeps its bindings and draws them at the variable's value times its scale factor (a field of the instance, kept through rebuilds and saves); other layers keep the scaled value and drop the binding of each length scaled (#2090); only the gap was measured in the incumbent, the other lengths are assumed to follow it. Not yet: `.fig` import does not set the factor, so bound lengths on an imported scaled instance go back to the variable's value at its first edit; effect, layout grid and text-run bindings are not multiplied; a layer scaled inside an instance keeps its bindings, so its bound lengths stay at the variable's value (unmeasured in the incumbent); a nested instance scaled inside an instance copy loses its factor when the copy is rebuilt | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; thresholds not yet compared with Figma's (`guide_snap_tests`) | | Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing | From 572690c0e896055c1f23550ef25069f5c3bbe960 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 9 Nov 2026 00:34:40 -0500 Subject: [PATCH 007/114] M3: the Scale tool row says which bindings a plain layer drops (#2134 review) Effect, layout grid and text-run bindings stay live on a scaled plain layer and draw at the variable's value again; only layer-level lengths drop their binding. Docs only. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- docs/ui-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 2dbe838b4..03e48f937 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -67,7 +67,7 @@ interaction feel not yet compared. | Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | -| Scale tool (K): handles about an anchor, live factor, panel | done | variable-bound lengths: an instance keeps its bindings and draws them at the variable's value times its scale factor (a field of the instance, kept through rebuilds and saves); other layers keep the scaled value and drop the binding of each length scaled (#2090); only the gap was measured in the incumbent, the other lengths are assumed to follow it. Not yet: `.fig` import does not set the factor, so bound lengths on an imported scaled instance go back to the variable's value at its first edit; effect, layout grid and text-run bindings are not multiplied; a layer scaled inside an instance keeps its bindings, so its bound lengths stay at the variable's value (unmeasured in the incumbent); a nested instance scaled inside an instance copy loses its factor when the copy is rebuilt | +| Scale tool (K): handles about an anchor, live factor, panel | done | variable-bound lengths: an instance keeps its bindings and draws them at the variable's value times its scale factor (a field of the instance, kept through rebuilds and saves); other layers keep the scaled value and drop the binding of each layer-level length scaled: size, gaps, padding, radii, stroke weights, min and max sizes and the layer's text sizes (#2090); only the gap was measured in the incumbent, the other lengths are assumed to follow it. Not yet: `.fig` import does not set the factor, so bound lengths on an imported scaled instance go back to the variable's value at its first edit; effect, layout grid and text-run bindings are neither multiplied nor dropped, so on any scaled layer they go back to the variable's value at the next bindings pass; a layer scaled inside an instance keeps its bindings, so its bound lengths stay at the variable's value (unmeasured in the incumbent); a nested instance scaled inside an instance copy loses its factor when the copy is rebuilt | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; thresholds not yet compared with Figma's (`guide_snap_tests`) | | Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing | From 4fdb02fc5f2c968bca449c8bbd046747827c261c Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 9 Nov 2026 01:32:26 -0500 Subject: [PATCH 008/114] M8: a dragged layer moves with its outline: drawn from a sprite while the base stays put (#2033) While a drag only translates plain layers on the threaded render worker, the dragged layers are rendered once into a texture of their own and drawn each frame at the same shift as the selection outline. The base is rendered once without them, from the document the drag started from, and no further render is asked for until the drag ends. On release, cancel or a zoom change the whole document is rendered again and the sprite stays until that image is shown. Trade-offs while dragging: the sprite draws above everything, blends against the background are approximated, and layers outside the conditions keep the old path. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.1 briefed; Sonnet 5.5 wrote at medium --- crates/ui-egui/src/canvas.rs | 26 ++- crates/ui-egui/src/canvas/drag_sprite.rs | 237 +++++++++++++++++++++++ crates/ui-egui/src/canvas/render.rs | 25 ++- crates/ui-egui/src/canvas_drag_tests.rs | 81 ++++++++ docs/ui-parity.md | 4 +- 5 files changed, 366 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/canvas/drag_sprite.rs diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 251ff25e6..94045a0c8 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -15,6 +15,7 @@ use crate::render_worker::{Done, Job, Worker}; use crate::theme::{COMPONENT, Tokens, doc_c32, regular, semibold}; mod builder; +mod drag_sprite; mod input; mod outline; mod overlays; @@ -58,6 +59,10 @@ pub struct CanvasState { /// The request the texture answers ([`crate::render_worker::Done::seq`]). tex_seq: u64, submitted: Option, + /// The dragged layers drawn from a texture of their own while the base render stays put + /// ([`drag_sprite`]), and the gesture (its start document's address) that can't have one. + sprite: Option, + sprite_declined: usize, /// The view of the last render asked for. want_view: Option, /// What the last canvas render had to do (shown by `ui.inspect`). @@ -89,6 +94,19 @@ pub struct CanvasState { wheel_is_mouse: bool, } +#[cfg(test)] +impl CanvasState { + /// The layers the last submitted canvas job leaves out. + pub(crate) fn submitted_skip(&self) -> Option<&[NodeId]> { + self.submitted.as_ref().map(|k| k.skip.as_slice()) + } + + /// Where the drag sprite shows on screen (at one pixel per point), if there is one. + pub(crate) fn sprite_rect(&self, app: &FigApp) -> Option { + drag_sprite::screen_rect(app, 1.0) + } +} + impl Default for CanvasState { fn default() -> Self { Self { @@ -99,6 +117,8 @@ impl Default for CanvasState { tex_coarse: false, tex_seq: 0, submitted: None, + sprite: None, + sprite_declined: 0, want_view: None, render_work: None, preview_latency_ms: None, @@ -260,7 +280,8 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { }) .unwrap_or(t.canvas); let dots = crate::board_bar::dots(app, bg, &t); - request_render(app, worker, ppp, max_texture_side, dots); + request_render(app, worker, &ctx, ppp, max_texture_side, dots); + drag_sprite::drop_orphan(&mut app.canvas); // Every finished render is shown, even when a newer one is already on its way: renders finish // in order, and an edit every frame (a drag) would otherwise never show until it stopped. let shown = app.session.ds().map(|ds| (ds.uid, ds.page)).ok(); @@ -281,6 +302,7 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { Some(t) => t.set(done.image, filter), None => app.canvas.texture = Some(ctx.load_texture("figcraft-canvas", done.image, filter)), } + let done_at = done.at; let latency = Some(done.at.elapsed().as_secs_f64() * 1000.0); if done.coarse { app.canvas.preview_latency_ms = latency; @@ -291,6 +313,7 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { app.canvas.tex_of = Some((done.uid, done.page)); app.canvas.tex_coarse = done.coarse; app.canvas.tex_seq = done.seq; + drag_sprite::arrived(&mut app.canvas, done_at, done.coarse); } let painter = ui.painter_at(rect); painter.rect_filled(rect, CornerRadius::ZERO, bg); @@ -303,6 +326,7 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { let image_rect = presented_image_rect(tl, v, zoom, ppp, pixel_preview); painter.image(tex.id(), image_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } + drag_sprite::draw(app, &painter, ppp); crate::dev_mode::refresh_measurements(app); app.session.tool.labels = overlays(app, &painter, &t); crate::frame_labels::rename_field(app, ui); diff --git a/crates/ui-egui/src/canvas/drag_sprite.rs b/crates/ui-egui/src/canvas/drag_sprite.rs new file mode 100644 index 000000000..8e9035076 --- /dev/null +++ b/crates/ui-egui/src/canvas/drag_sprite.rs @@ -0,0 +1,237 @@ +//! The dragged-subtree sprite (#2033). The selection outline is drawn from the live document every +//! frame, but the canvas shows the last image the render worker finished, so while a layer is +//! dragged the content trails the outline by the render time of every pointer move. When a +//! gesture only translates plain layers ([`crate::selection_cache::moved`]), the layers are +//! rendered once into a texture of their own (the sprite) and drawn each frame at the same +//! shifted place as the outline, while the base render is made once without them +//! ([`figcraft_render::Options::skip`]) from the document the gesture started from, so no render +//! is requested again until the gesture ends. +//! +//! While it drags, the sprite draws above everything (the layers lose their z-order), blends and +//! backdrop effects against what lies under them are approximated, and a layer that doesn't +//! qualify (see [`plan`]) keeps the old way. + +use std::sync::Arc; + +use egui::{Color32, Rect, pos2}; +use figcraft_color::BlendMode; +use figcraft_doc::{Document, NodeId, NodeKind}; +use web_time::Instant; + +use super::{CanvasState, FigApp}; + +/// The sprite is at most this many times the canvas in pixels. +const MAX_AREA_FACTOR: f64 = 4.0; + +pub(super) struct Sprite { + tex: egui::TextureHandle, + /// The dragged layers. + roots: Vec, + /// Where the first of them was, in page units (the final shift is read off its move). + root_at: (f64, f64), + /// The page area the sprite shows when not shifted, and its pixels. + view: figcraft_render::View, + /// The pointer-driven shift (page units) while it drags, then the final one. + delta: (f64, f64), + zoom: f64, + ppp: f32, + /// The address of the document the gesture started from. + base: usize, + /// Page rectangle the layers are clipped to (the clipping frames above them). + clip: Option, + /// The gesture is over (or the plan stopped holding): the sprite stays until the image of the + /// document without a skip, asked for at or after `release`, is on screen. + ending: bool, + release: Option, +} + +impl Sprite { + fn rect(&self, app: &FigApp, ppp: f32) -> Rect { + let tl = app.to_screen(self.view.origin.0 + self.delta.0, self.view.origin.1 + self.delta.1); + let zoom = app.session.ds().map(|d| d.view.zoom).unwrap_or(self.zoom); + super::presented_image_rect(tl, &self.view, zoom, ppp, false) + } +} + +/// Where the sprite shows on screen now, if there is one (tests compare it with the outline). +#[cfg(test)] +pub(super) fn screen_rect(app: &FigApp, ppp: f32) -> Option { + app.canvas.sprite.as_ref().map(|s| s.rect(app, ppp)) +} + +/// Draw the sprite, above the canvas image. +pub(super) fn draw(app: &FigApp, painter: &egui::Painter, ppp: f32) { + let Some(s) = &app.canvas.sprite else { return }; + let r = s.rect(app, ppp); + let painter = match s.clip { + Some(c) => { + let (a, b) = (app.to_screen(c.x0, c.y0), app.to_screen(c.x1, c.y1)); + painter.with_clip_rect(painter.clip_rect().intersect(Rect::from_two_pos(a, b))) + } + None => painter.clone(), + }; + painter.image(s.tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); +} + +/// A finished image of the canvas, asked for at `at`, is on screen: a sprite that is ending goes. +pub(super) fn arrived(c: &mut CanvasState, at: Instant, coarse: bool) { + if !coarse && c.sprite.as_ref().is_some_and(|s| s.ending && s.release.is_some_and(|r| at >= r)) { + c.sprite = None; + } +} + +/// A job without a skip was asked for at `at`: what an ending sprite waits for. +pub(super) fn released_at(c: &mut CanvasState, at: Instant) { + if let Some(s) = c.sprite.as_mut().filter(|s| s.ending) { + s.release = Some(at); + } +} + +/// An ending sprite no job waits on goes (nothing would ever replace it). +pub(super) fn drop_orphan(c: &mut CanvasState) { + if c.sprite.as_ref().is_some_and(|s| s.ending && s.release.is_none()) { + c.sprite = None; + } +} + +/// Bring the sprite in line with the gesture; the document and layers the canvas render is to be +/// made from, with the layers skipped, while it shows them. +pub(super) fn sync(app: &mut FigApp, ctx: &egui::Context, ppp: f32, max_side: u32) -> Option<(Arc, Vec)> { + if cfg!(target_arch = "wasm32") { + return None; + } + let Ok(ds) = app.session.ds() else { + app.canvas.sprite = None; + return None; + }; + let moved = crate::selection_cache::moved(ds); + let zoom = ds.view.zoom; + let view_ok = view_allows(ds); + if let Some(s) = app.canvas.sprite.as_mut().filter(|s| !s.ending) { + if let Some((base, d)) = moved.as_ref().filter(|(b, _)| Arc::as_ptr(b) as usize == s.base) + && zoom.to_bits() == s.zoom.to_bits() + && ppp.to_bits() == s.ppp.to_bits() + && view_ok + { + s.delta = *d; + return Some((base.clone(), s.roots.clone())); + } + // The gesture ended or the plan stopped holding (then not again in this gesture): freeze + // where the layers are now. + if let Some((b, _)) = moved.as_ref().filter(|(b, _)| Arc::as_ptr(b) as usize == s.base) { + app.canvas.sprite_declined = Arc::as_ptr(b) as usize; + } + match ds.doc.world_transform(s.roots[0]).translation() { + t if ds.doc.contains(s.roots[0]) => { + s.delta = (t.x - s.root_at.0, t.y - s.root_at.1); + s.ending = true; + s.release = None; + } + _ => app.canvas.sprite = None, + } + } + let (base, _) = moved?; + let ptr = Arc::as_ptr(&base) as usize; + if app.canvas.sprite_declined == ptr || !view_ok { + return None; + } + let canvas_px = f64::from(app.canvas.rect.width() * ppp) * f64::from(app.canvas.rect.height() * ppp); + match plan(ctx, &base, &ds.selection, zoom, ppp, max_side, canvas_px) { + Some(s) => { + let out = (base, s.roots.clone()); + app.canvas.sprite = Some(s); + Some(out) + } + None => { + app.canvas.sprite_declined = ptr; + None + } + } +} + +/// What the canvas shows that the sprite can't stand in for. +fn view_allows(ds: &figcraft_engine::DocState) -> bool { + !ds.view.outlines + && !ds.view.outlines_selection + && !ds.view.outline_hidden + && ds.focused().is_none() + && ds.view.pixel_preview_scale().is_none() + && !(ds.view.proof_srgb && !ds.doc.color_profile.is_srgb()) +} + +/// Normal, or the pass-through of groups and frames (which draws like it unless the layers in them blend). +fn ordinary(b: BlendMode) -> bool { + matches!(b, BlendMode::Normal | BlendMode::PassThrough) +} + +/// Whether layer `id` can be drawn apart from the rest: it and what it sits in are plain. +fn plain(doc: &Document, id: NodeId, clip: &mut Option) -> bool { + let Some(n) = doc.node(id) else { return false }; + if !n.effects.is_empty() || !ordinary(n.blend) || n.is_mask { + return false; + } + let Some(parent) = n.parent.and_then(|p| doc.node(p)) else { return false }; + if matches!(parent.kind, NodeKind::BooleanOp { .. }) || parent.children.iter().any(|c| doc.node(*c).is_some_and(|c| c.is_mask)) { + return false; + } + let mut at = Some(parent.id); + while let Some(a) = at.and_then(|a| doc.node(a)) { + if matches!(a.kind, NodeKind::Page { .. }) { + break; + } + if !a.effects.is_empty() || !ordinary(a.blend) || a.opacity < 1.0 || a.is_mask { + return false; + } + if a.clip && a.kind.is_frame_like() { + let Some(b) = doc.world_bounds(a.id) else { return false }; + *clip = Some(clip.map_or(b, |c| c.intersect(b))); + } + at = a.parent; + } + true +} + +/// Render the dragged layers of `base` into a sprite, if they qualify: the roots are plain (see +/// [`plain`]), none inside another, and the sprite fits a texture and a few canvases of pixels. +fn plan(ctx: &egui::Context, base: &Arc, sel: &[NodeId], zoom: f64, ppp: f32, max_side: u32, canvas_px: f64) -> Option { + if sel.is_empty() || !zoom.is_finite() || zoom <= 0.0 { + return None; + } + let mut clip = None; + for id in sel { + if !plain(base, *id, &mut clip) || sel.iter().any(|o| o != id && base.ancestors(*id).contains(o)) { + return None; + } + } + // Bottom to top, as the page draws them. + let page = base.page_of(sel[0])?; + let order = base.subtree(page); + let mut roots: Vec = order.iter().copied().filter(|i| sel.contains(i)).collect(); + if roots.len() != sel.len() { + roots = sel.to_vec(); + } + let bounds = roots.iter().filter_map(|i| base.world_render_bounds(*i)).reduce(|a, b| a.union(b))?; + let scale = zoom * f64::from(ppp); + let (w, h) = ((bounds.width() * scale).ceil(), (bounds.height() * scale).ceil()); + let side = f64::from(max_side); + if !(w >= 1.0 && h >= 1.0 && w <= side && h <= side && w * h <= canvas_px * MAX_AREA_FACTOR) { + return None; + } + let pix = figcraft_render::render_area(base, &roots, bounds, scale)?; + let view = figcraft_render::View { origin: (bounds.x0, bounds.y0), scale, width: pix.width(), height: pix.height() }; + let tex = ctx.load_texture("figcraft-drag-sprite", crate::render_worker::screen_image(&pix, base.color_profile), egui::TextureOptions::LINEAR); + let t = base.world_transform(roots[0]).translation(); + Some(Sprite { + tex, + root_at: (t.x, t.y), + roots, + view, + delta: (0.0, 0.0), + zoom, + ppp, + base: Arc::as_ptr(base) as usize, + clip, + ending: false, + release: None, + }) +} diff --git a/crates/ui-egui/src/canvas/render.rs b/crates/ui-egui/src/canvas/render.rs index c6c4702fa..11658708f 100644 --- a/crates/ui-egui/src/canvas/render.rs +++ b/crates/ui-egui/src/canvas/render.rs @@ -10,7 +10,7 @@ pub(super) struct JobKey { outline: bool, outline_extras: figcraft_render::Outline, outlined: Vec, - skip: Vec, + pub(super) skip: Vec, solo: Option, /// Text lays out anew when fonts arrive (system fonts load in the background). fonts: u64, @@ -46,7 +46,16 @@ fn covers(outer: &figcraft_render::View, inner: &figcraft_render::View) -> bool o.x0 <= i.x0 + eps && o.y0 <= i.y0 + eps && o.x1 >= i.x1 - eps && o.y1 >= i.y1 - eps } -pub(super) fn request_render(app: &mut FigApp, worker: &mut Worker, ppp: f32, max_texture_side: u32, dots: Option) { +pub(super) fn request_render( + app: &mut FigApp, + worker: &mut Worker, + ctx: &egui::Context, + ppp: f32, + max_texture_side: u32, + dots: Option, +) { + // A dragged layer drawn as a sprite: the render is of the document the drag started from, without it. + let sprite = super::drag_sprite::sync(app, ctx, ppp, max_texture_side); let Ok(ds) = app.session.ds() else { return }; let rect = app.canvas.rect; let (mut ox, mut oy) = ds.view.origin(); @@ -60,7 +69,10 @@ pub(super) fn request_render(app: &mut FigApp, worker: &mut Worker, ppp: f32, ma (ds.view.zoom * f64::from(ppp), (rect.width() * ppp).ceil().max(1.0) as u32, (rect.height() * ppp).ceil().max(1.0) as u32) }; // The edited text is drawn live (an IME composition included); the caret is an overlay. - let doc = app.preedit_view().map(|p| p.doc.clone()).unwrap_or_else(|| ds.doc.clone()); + let (doc, skip) = match sprite { + Some(s) => s, + None => (app.preedit_view().map(|p| p.doc.clone()).unwrap_or_else(|| ds.doc.clone()), vec![]), + }; let outlined = if ds.view.outlines_selection { ds.selection.clone() } else { vec![] }; let proof = ds.view.proof_srgb && !doc.color_profile.is_srgb(); let outline_extras = figcraft_render::Outline { hidden: ds.view.outline_hidden, bounds: ds.view.outline_bounds, light: false }; @@ -81,7 +93,7 @@ pub(super) fn request_render(app: &mut FigApp, worker: &mut Worker, ppp: f32, ma outline: ds.view.outlines, outline_extras, outlined: outlined.clone(), - skip: vec![], + skip: skip.clone(), solo: ds.focused(), fonts: figcraft_text::layout_generation(), proof, @@ -105,7 +117,7 @@ pub(super) fn request_render(app: &mut FigApp, worker: &mut Worker, ppp: f32, ma outline: ds.view.outlines, outline_extras, outlined, - skip: vec![], + skip, solo: key.solo, proof, dots, @@ -114,6 +126,9 @@ pub(super) fn request_render(app: &mut FigApp, worker: &mut Worker, ppp: f32, ma at: web_time::Instant::now(), }; app.canvas.want_view = Some(job.view.clone()); + if job.skip.is_empty() { + super::drag_sprite::released_at(&mut app.canvas, job.at); + } worker.submit(job); app.canvas.submitted = Some(key); } diff --git a/crates/ui-egui/src/canvas_drag_tests.rs b/crates/ui-egui/src/canvas_drag_tests.rs index 9f3b38397..e46ccae9a 100644 --- a/crates/ui-egui/src/canvas_drag_tests.rs +++ b/crates/ui-egui/src/canvas_drag_tests.rs @@ -121,3 +121,84 @@ fn a_drag_released_off_the_window_ends_where_the_pointer_was_last_seen_and_later assert!(!doc.contains(gone), "the delete stays"); assert_eq!(doc.node(text).unwrap().kind.text().unwrap().characters, "B"); } + +/// A frame with a child, selected, and the screen point of an empty spot in it. +fn frame_with_child(effects: bool) -> (Ui, figcraft_doc::NodeId, egui::Pos2) { + let mut s = Session::new(); + let id = |v: serde_json::Value| figcraft_engine::params::id_of(&v["id"]).unwrap(); + let f = id(s.execute("frame.create", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()); + s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 80, "height": 60, "parent": f, "props": {"fill": "#e03030"}})).unwrap(); + if effects { + s.execute("node.set", &json!({"ids": [f], "effects": [{"type": "dropShadow", "color": "#00000066", "offset": [0, 8], "radius": 24}]})) + .unwrap(); + } + s.execute("select.set", &json!({"ids": [f]})).unwrap(); + let mut u = Ui::new(s); + settle(&mut u); + let p = u.app.to_screen(350.0, 250.0); + (u, f, p) +} + +fn drag_frames(u: &mut Ui, p: egui::Pos2, n: u32) { + for k in 1..=n { + u.frame(vec![Event::PointerMoved(p + vec2(k as f32 * 7.0, k as f32 * 3.0))]); + } +} + +#[test] +fn dragging_a_plain_frame_draws_its_sprite_with_the_outline() { + let (mut u, f, p) = frame_with_child(false); + u.button(p, true); + drag_frames(&mut u, p, 4); + assert!(u.app.canvas.sprite_rect(&u.app).is_some(), "the sprite exists"); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[f][..]), "the base render leaves the dragged layer out"); + settle(&mut u); + // The sprite and the outline come from the same shift in the same frame. + for k in 5..9 { + u.frame(vec![Event::PointerMoved(p + vec2(k as f32 * 7.0, k as f32 * 3.0))]); + let ds = u.app.session.ds().unwrap(); + let (base, (dx, dy)) = crate::selection_cache::moved(ds).expect("a plain move"); + let b = figcraft_engine::tools::selection_box(&base, &[f]).unwrap(); + let outline = u.app.to_screen(b[0].x + dx, b[0].y + dy); + let sprite = u.app.canvas.sprite_rect(&u.app).unwrap(); + assert!((sprite.min - outline).length() < 0.6, "sprite {:?} outline {outline:?}", sprite.min); + } + // The base stays put: later moves ask for no new render. + settle(&mut u); + let before = u.app.canvas.submitted_skip().map(<[_]>::to_vec); + u.frame(vec![Event::PointerMoved(p + vec2(90.0, 40.0))]); + assert_eq!(u.app.canvas.submitted_skip().map(<[_]>::to_vec), before); + assert!(!u.app.worker.as_ref().is_some_and(|w| w.in_flight()), "no render for a move"); + u.button(p + vec2(90.0, 40.0), false); + u.frame(vec![]); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..]), "the whole document is rendered again"); + settle(&mut u); + u.frame(vec![]); + assert!(u.app.canvas.sprite_rect(&u.app).is_none(), "the sprite goes once that render is shown"); +} + +#[test] +fn a_frame_with_effects_on_itself_keeps_the_old_path() { + let (mut u, _f, p) = frame_with_child(true); + u.button(p, true); + drag_frames(&mut u, p, 4); + assert!(u.app.canvas.sprite_rect(&u.app).is_none()); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..])); + u.button(p + vec2(30.0, 10.0), false); +} + +#[test] +fn zooming_during_a_drag_ends_the_fast_path() { + let (mut u, _f, p) = frame_with_child(false); + u.button(p, true); + drag_frames(&mut u, p, 4); + assert!(u.app.canvas.sprite_rect(&u.app).is_some()); + let z = u.app.session.ds().unwrap().view.zoom; + u.app.session.ds_mut().unwrap().view.zoom = z * 1.5; + u.frame(vec![Event::PointerMoved(p + vec2(40.0, 12.0))]); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..]), "the zoom ended it"); + // Not started again by the next move of the same gesture. + u.frame(vec![Event::PointerMoved(p + vec2(48.0, 15.0))]); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..])); + u.button(p + vec2(48.0, 15.0), false); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 463be3b47..a70de28ce 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); 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 capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (a dragged layer is drawn from a sprite that moves with its outline (#2033); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); 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 capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -67,6 +67,7 @@ interaction feel not yet compared. | Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | +| A dragged layer moves with its outline | partial | #2033: the canvas image is the last render the worker finished, so a drag's content trailed its outline by a render per pointer move (63 ms, about 3.6 frames, and 150 px on screen with drop shadows on 200 layers). While a gesture only translates plain layers (Normal or pass-through blend, no effects on them or above them, not masks, not in a boolean group or beside a mask, no ancestor under 100 percent opacity; their own children may have effects) the layers are rendered once into a texture of their own (the sprite), the base is rendered once without them from the document the drag started from and then asks for no more renders, and the sprite is drawn each frame at the same shifted place as the selection outline. On release, Escape or a zoom change the document is rendered whole again and the sprite stays until that image is shown. Desktop only (the browser renders in the same frame). Trade-offs while dragging: the sprite draws above everything (z-order is lost), blends and backdrop blurs against what is behind are approximated, ancestors' clips are applied as their bounding boxes, and a sprite wider than the texture limit or over four canvases of pixels, outline and focus views, pixel preview and soft proof keep the old way | `canvas/drag_sprite.rs` | | Scale tool (K): handles about an anchor, live factor, panel | done | | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; thresholds not yet compared with Figma's (`guide_snap_tests`) | @@ -187,6 +188,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-09 | patch | M8, #2033: a dragged layer moves with its outline: the layers a translate-only drag moves are drawn from a sprite (a texture rendered once at the start) at the same shift as the outline, and the base render, made once without them, is not asked for again until the drag ends (see the row "A dragged layer moves with its outline" for the conditions and trade-offs). | | 2026-11-02 | patch | Shortcuts: a Cmd/Ctrl-click on a padding field (the horizontal or vertical pair, or a side with Individual padding open) makes the value typed go to all four sides, in one undo step (Guide to auto layout, Keyboard shortcut guide); a plain click still edits that axis or side alone. A documented gesture row: 134 documented, 133 bound. Test: `padding_individual_tests` | | 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 | 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`. | From 89c9625ba02b5f306c7e16b4576262ae574c4f82 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 9 Nov 2026 02:39:27 -0500 Subject: [PATCH 009/114] M8: the drag sprite checks every ancestor for booleans and masks, and stays within render_area's scale (#2144 review) `plain` checked the boolean result and mask siblings only at the dragged layer's parent; a layer in a group inside a boolean, or in a group beside a mask, got a sprite that ignored them. Both checks now run at every level, the page included. `render_area` clamps its scale to 64, so a zoom past it declines the sprite instead of drawing it too small. The parity row's file reference moves into the Notes cell. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- crates/ui-egui/src/canvas/drag_sprite.rs | 56 ++++++++++++++++++++++-- crates/ui-egui/src/canvas_drag_tests.rs | 23 ++++++++++ docs/ui-parity.md | 2 +- 3 files changed, 77 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/canvas/drag_sprite.rs b/crates/ui-egui/src/canvas/drag_sprite.rs index 8e9035076..d728ea53e 100644 --- a/crates/ui-egui/src/canvas/drag_sprite.rs +++ b/crates/ui-egui/src/canvas/drag_sprite.rs @@ -159,6 +159,9 @@ fn view_allows(ds: &figcraft_engine::DocState) -> bool { && !(ds.view.proof_srgb && !ds.doc.color_profile.is_srgb()) } +/// The largest scale `figcraft_render::render_area` renders at (it clamps to this). +const RENDER_AREA_MAX_SCALE: f64 = 64.0; + /// Normal, or the pass-through of groups and frames (which draws like it unless the layers in them blend). fn ordinary(b: BlendMode) -> bool { matches!(b, BlendMode::Normal | BlendMode::PassThrough) @@ -170,12 +173,16 @@ fn plain(doc: &Document, id: NodeId, clip: &mut Option) -> if !n.effects.is_empty() || !ordinary(n.blend) || n.is_mask { return false; } - let Some(parent) = n.parent.and_then(|p| doc.node(p)) else { return false }; - if matches!(parent.kind, NodeKind::BooleanOp { .. }) || parent.children.iter().any(|c| doc.node(*c).is_some_and(|c| c.is_mask)) { + if n.parent.and_then(|p| doc.node(p)).is_none() { return false; } - let mut at = Some(parent.id); + let mut at = n.parent; while let Some(a) = at.and_then(|a| doc.node(a)) { + // At every level, the page included: inside a boolean result, or beside a mask, the layer + // doesn't draw on its own. + if matches!(a.kind, NodeKind::BooleanOp { .. }) || a.children.iter().any(|c| doc.node(*c).is_some_and(|c| c.is_mask)) { + return false; + } if matches!(a.kind, NodeKind::Page { .. }) { break; } @@ -212,6 +219,10 @@ fn plan(ctx: &egui::Context, base: &Arc, sel: &[NodeId], zoom: f64, pp } let bounds = roots.iter().filter_map(|i| base.world_render_bounds(*i)).reduce(|a, b| a.union(b))?; let scale = zoom * f64::from(ppp); + // `render_area` renders at most at this scale; past it the sprite would draw smaller than the layers. + if scale > RENDER_AREA_MAX_SCALE { + return None; + } let (w, h) = ((bounds.width() * scale).ceil(), (bounds.height() * scale).ceil()); let side = f64::from(max_side); if !(w >= 1.0 && h >= 1.0 && w <= side && h <= side && w * h <= canvas_px * MAX_AREA_FACTOR) { @@ -235,3 +246,42 @@ fn plan(ctx: &egui::Context, base: &Arc, sel: &[NodeId], zoom: f64, pp release: None, }) } + +#[cfg(test)] +mod plain_tests { + use super::plain; + use figcraft_engine::Session; + use serde_json::{Value, json}; + + fn id(v: &Value) -> figcraft_doc::NodeId { + figcraft_engine::params::id_of(&v["id"]).or_else(|| figcraft_engine::params::id_of(&v["ids"][0])).unwrap() + } + + fn rect(s: &mut Session, x: f64) -> figcraft_doc::NodeId { + id(&s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 40, "height": 40})).unwrap()) + } + + #[test] + fn a_layer_in_a_group_inside_a_boolean_is_not_plain() { + let mut s = Session::new(); + let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 20.0), rect(&mut s, 60.0)); + let g = id(&s.execute("object.group", &json!({"ids": [a, b]})).unwrap()); + assert!(plain(s.doc().unwrap(), a, &mut None), "in a plain group it is plain"); + s.execute("bool.union", &json!({"ids": [g, c]})).unwrap(); + let doc = s.doc().unwrap(); + assert!(doc.ancestors(a).iter().any(|p| matches!(doc.node(*p).map(|n| &n.kind), Some(figcraft_doc::NodeKind::BooleanOp { .. })))); + assert!(!plain(doc, a, &mut None), "its group sits in a boolean result"); + } + + #[test] + fn a_layer_in_a_group_beside_a_mask_is_not_plain() { + let mut s = Session::new(); + let m = rect(&mut s, 0.0); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 30.0)); + let g = id(&s.execute("object.group", &json!({"ids": [a, b]})).unwrap()); + s.execute("object.mask", &json!({"ids": [m, g]})).unwrap(); + let doc = s.doc().unwrap(); + assert!(doc.node(m).is_some_and(|n| n.is_mask), "the bottom layer masks"); + assert!(!plain(doc, a, &mut None), "its group is masked"); + } +} diff --git a/crates/ui-egui/src/canvas_drag_tests.rs b/crates/ui-egui/src/canvas_drag_tests.rs index e46ccae9a..546c56da1 100644 --- a/crates/ui-egui/src/canvas_drag_tests.rs +++ b/crates/ui-egui/src/canvas_drag_tests.rs @@ -187,6 +187,29 @@ fn a_frame_with_effects_on_itself_keeps_the_old_path() { u.button(p + vec2(30.0, 10.0), false); } +#[test] +fn past_the_largest_render_scale_the_drag_keeps_the_old_path() { + // At 8000% a small frame still fits a texture, but `render_area` renders at most at 64x: + // the sprite would draw smaller than the layers, so there is none. + let mut s = Session::new(); + let id = |v: serde_json::Value| figcraft_engine::params::id_of(&v["id"]).unwrap(); + let f = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap()); + s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 2, "height": 2, "parent": f, "props": {"fill": "#e03030"}})).unwrap(); + s.execute("select.set", &json!({"ids": [f]})).unwrap(); + let mut u = Ui::new(s); + settle(&mut u); + let v = &mut u.app.session.ds_mut().unwrap().view; + (v.zoom, v.cx, v.cy) = (80.0, 2.0, 2.0); + settle(&mut u); + let p = u.app.to_screen(2.0, 2.0); + u.button(p, true); + drag_frames(&mut u, p, 4); + assert_eq!(u.app.session.ds().unwrap().view.zoom, 80.0); + assert!(u.app.canvas.sprite_rect(&u.app).is_none()); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..])); + u.button(p + vec2(30.0, 10.0), false); +} + #[test] fn zooming_during_a_drag_ends_the_fast_path() { let (mut u, _f, p) = frame_with_child(false); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index a70de28ce..90fcedd74 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -67,7 +67,7 @@ interaction feel not yet compared. | Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | -| A dragged layer moves with its outline | partial | #2033: the canvas image is the last render the worker finished, so a drag's content trailed its outline by a render per pointer move (63 ms, about 3.6 frames, and 150 px on screen with drop shadows on 200 layers). While a gesture only translates plain layers (Normal or pass-through blend, no effects on them or above them, not masks, not in a boolean group or beside a mask, no ancestor under 100 percent opacity; their own children may have effects) the layers are rendered once into a texture of their own (the sprite), the base is rendered once without them from the document the drag started from and then asks for no more renders, and the sprite is drawn each frame at the same shifted place as the selection outline. On release, Escape or a zoom change the document is rendered whole again and the sprite stays until that image is shown. Desktop only (the browser renders in the same frame). Trade-offs while dragging: the sprite draws above everything (z-order is lost), blends and backdrop blurs against what is behind are approximated, ancestors' clips are applied as their bounding boxes, and a sprite wider than the texture limit or over four canvases of pixels, outline and focus views, pixel preview and soft proof keep the old way | `canvas/drag_sprite.rs` | +| A dragged layer moves with its outline | partial | #2033: the canvas image is the last render the worker finished, so a drag's content trailed its outline by a render per pointer move (63 ms, about 3.6 frames, and 150 px on screen with drop shadows on 200 layers). While a gesture only translates plain layers (Normal or pass-through blend, no effects on them or above them, not masks, not in a boolean group or beside a mask, no ancestor under 100 percent opacity; their own children may have effects) the layers are rendered once into a texture of their own (the sprite), the base is rendered once without them from the document the drag started from and then asks for no more renders, and the sprite is drawn each frame at the same shifted place as the selection outline. On release, Escape or a zoom change the document is rendered whole again and the sprite stays until that image is shown. Desktop only (the browser renders in the same frame). Trade-offs while dragging: the sprite draws above everything (z-order is lost), blends and backdrop blurs against what is behind are approximated, ancestors' clips are applied as their bounding boxes, and a sprite wider than the texture limit or over four canvases of pixels, outline and focus views, pixel preview and soft proof keep the old way (`canvas/drag_sprite.rs`) | | Scale tool (K): handles about an anchor, live factor, panel | done | | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; thresholds not yet compared with Figma's (`guide_snap_tests`) | From b27ab45feefdc1ccd98d983fa0018d2d6712b674 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 9 Nov 2026 14:57:41 -0500 Subject: [PATCH 010/114] M5: tests for the presenter detail: reuse, re-render on an edit, and detail_plan's edge cases (#2133 review) Pins the detail texture being kept while nothing changes and made again after an edit, and detail_plan's empty, outside, invalid, partly outside, margin-shrinking, over-cap and small-side cases. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 triaged and briefed; Sonnet 5.5 verified and wrote at medium --- crates/ui-egui/src/present/tests.rs | 62 +++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/crates/ui-egui/src/present/tests.rs b/crates/ui-egui/src/present/tests.rs index 9ed1fa665..dde23026f 100644 --- a/crates/ui-egui/src/present/tests.rs +++ b/crates/ui-egui/src/present/tests.rs @@ -474,3 +474,65 @@ fn presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale() { assert!(s[0] * s[1] <= 16_777_216 + s[0] + s[1] && s[0] <= 16_384 && s[1] <= 16_384, "{s:?}"); } } + +/// A tall frame on a 2x display, presented, and the page area its detail texture shows. +fn tall_hidpi(side: usize) -> Ui { + let mut session = figcraft_engine::Session::new(); + let frame = id(&session.execute("node.create", &json!({"type": "frame", "width": 1440, "height": 9701})).unwrap()); + session.execute("node.create", &json!({"type": "rectangle", "parent": frame, "x": 100, "y": 100, "width": 300, "height": 200})).unwrap(); + let mut ui = Ui::new(session); + ui.hidpi = Some((2.0, side)); + ui.run("proto.present", json!({"start": frame})); + ui.app.ui.present.as_mut().unwrap().view.scale = PresentScale::FitWidth; + ui.frames(2, Vec::new); + ui +} + +fn detail_bounds(ui: &Ui) -> Option { + ui.app.ui.present.as_ref().and_then(|p| p.detail.as_ref().map(|(_, d)| d.bounds)) +} + +#[test] +fn the_detail_is_kept_while_nothing_changes_and_made_again_when_the_frame_does() { + let mut ui = tall_hidpi(16_384); + let tex_id = |ui: &Ui| ui.app.ui.present.as_ref().and_then(|p| p.detail.as_ref().map(|(_, d)| d.tex.id())); + let first = tex_id(&ui).expect("a detail is drawn"); + let bounds = detail_bounds(&ui).unwrap(); + assert!( + bounds.x0 == 0.0 && bounds.y0 == 0.0 && bounds.x1 == 1440.0 && bounds.y1 > 860.0 && bounds.y1 < 9701.0, + "the view and a margin: {bounds:?}" + ); + ui.frames(5, Vec::new); + assert_eq!(tex_id(&ui), Some(first), "the same view makes no new render"); + let rect = ui.app.session.doc().unwrap().node(ui.app.session.doc().unwrap().first_page().unwrap()).unwrap().children[0]; + let child = ui.app.session.doc().unwrap().node(rect).unwrap().children[0]; + ui.run("node.set", json!({"id": child, "props": {"x": 120}})); + ui.frames(3, Vec::new); + assert_ne!(tex_id(&ui), Some(first), "an edit renders the detail again"); +} + +#[test] +fn detail_plan_edge_cases() { + use figcraft_geom::Rect as R; + let bounds = R::new(0.0, 0.0, 1440.0, 9701.0); + let side = 16382.0; + // Nothing in view, an empty or invalid view, a bad scale: no detail. + for v in [R::new(0.0, 10_000.0, 1440.0, 11_000.0), R::new(0.0, 100.0, 0.0, 100.0)] { + assert!(actions::detail_plan(bounds, v, 2.0, side).is_none(), "{v:?}"); + } + for px in [0.0, -1.0, f64::NAN] { + assert!(actions::detail_plan(bounds, R::new(0.0, 0.0, 1440.0, 860.0), px, side).is_none(), "{px}"); + } + // Partly outside: the part inside. + let r = actions::detail_plan(bounds, R::new(0.0, -500.0, 1440.0, 360.0), 2.0, side).unwrap(); + assert!(r.y0 == 0.0 && r.y1 >= 360.0, "{r:?}"); + // A view whose quarter margin passes the pixel cap gets a smaller margin that fits. + let r = actions::detail_plan(bounds, R::new(0.0, 3000.0, 1440.0, 5000.0), 2.0, side).unwrap(); + assert!(r.height() > 2000.0 && r.height() < 3000.0 && r.width() * r.height() * 4.0 <= 16_777_216.0, "{r:?}"); + // A view past the caps by itself is returned as it is. + let tall = R::new(0.0, 1000.0, 1440.0, 5000.0); + assert_eq!(actions::detail_plan(bounds, tall, 2.0, side), Some(tall)); + // A small texture limit: the view alone is over it, so it is the view. + let view = R::new(0.0, 0.0, 1440.0, 860.0); + assert_eq!(actions::detail_plan(bounds, view, 2.0, 2048.0), Some(view)); +} From 4cc59a6be17de906bf273c18a1da7ead4407ea5e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 9 Nov 2026 14:47:41 -0500 Subject: [PATCH 011/114] M8: the drag sprite holds its start document, forgets a declined gesture, stays within texture limits and narrows its mask rule (#2144 review) The sprite and the declined-gesture marker held the start document by raw address; they now hold it (Arc / Weak) and compare with ptr_eq. A cancelled drag restores the same document, so a declined gesture no longer declines the next drag of it. The sprite is also dropped when another document or page is on screen, the rendered pixmap is checked against the texture limits, plan declines when the roots are not all on one page, a rounded clipping ancestor or a NaN ancestor opacity makes a layer non-plain, and only the layers above a mask are treated as masked. New tests cover cancel, delete mid-drag, outline views, the sprite size and the rejected ancestor properties. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 triaged and briefed; Sonnet 5.5 verified and wrote at medium --- crates/ui-egui/src/canvas.rs | 6 +- crates/ui-egui/src/canvas/drag_sprite.rs | 147 ++++++++++++++++++----- crates/ui-egui/src/canvas_drag_tests.rs | 77 ++++++++++++ 3 files changed, 194 insertions(+), 36 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 94045a0c8..477b6e046 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -60,9 +60,9 @@ pub struct CanvasState { tex_seq: u64, submitted: Option, /// The dragged layers drawn from a texture of their own while the base render stays put - /// ([`drag_sprite`]), and the gesture (its start document's address) that can't have one. + /// ([`drag_sprite`]), and the gesture (its start document, held weakly) that can't have one. sprite: Option, - sprite_declined: usize, + sprite_declined: Option>, /// The view of the last render asked for. want_view: Option, /// What the last canvas render had to do (shown by `ui.inspect`). @@ -118,7 +118,7 @@ impl Default for CanvasState { tex_seq: 0, submitted: None, sprite: None, - sprite_declined: 0, + sprite_declined: None, want_view: None, render_work: None, preview_latency_ms: None, diff --git a/crates/ui-egui/src/canvas/drag_sprite.rs b/crates/ui-egui/src/canvas/drag_sprite.rs index d728ea53e..8ef80e575 100644 --- a/crates/ui-egui/src/canvas/drag_sprite.rs +++ b/crates/ui-egui/src/canvas/drag_sprite.rs @@ -11,7 +11,7 @@ //! backdrop effects against what lies under them are approximated, and a layer that doesn't //! qualify (see [`plan`]) keeps the old way. -use std::sync::Arc; +use std::sync::{Arc, Weak}; use egui::{Color32, Rect, pos2}; use figcraft_color::BlendMode; @@ -35,8 +35,10 @@ pub(super) struct Sprite { delta: (f64, f64), zoom: f64, ppp: f32, - /// The address of the document the gesture started from. - base: usize, + /// The document the gesture started from (held, so no other document can take its address). + base: Arc, + /// The document and page the sprite belongs to: another one on screen ends it. + of: (u64, NodeId), /// Page rectangle the layers are clipped to (the clipping frames above them). clip: Option, /// The gesture is over (or the plan stopped holding): the sprite stays until the image of the @@ -105,10 +107,16 @@ pub(super) fn sync(app: &mut FigApp, ctx: &egui::Context, ppp: f32, max_side: u3 return None; }; let moved = crate::selection_cache::moved(ds); + if moved.is_none() { + app.canvas.sprite_declined = None; + } + if app.canvas.sprite.as_ref().is_some_and(|s| s.of != (ds.uid, ds.page)) { + app.canvas.sprite = None; + } let zoom = ds.view.zoom; let view_ok = view_allows(ds); if let Some(s) = app.canvas.sprite.as_mut().filter(|s| !s.ending) { - if let Some((base, d)) = moved.as_ref().filter(|(b, _)| Arc::as_ptr(b) as usize == s.base) + if let Some((base, d)) = moved.as_ref().filter(|(b, _)| Arc::ptr_eq(b, &s.base)) && zoom.to_bits() == s.zoom.to_bits() && ppp.to_bits() == s.ppp.to_bits() && view_ok @@ -118,32 +126,32 @@ pub(super) fn sync(app: &mut FigApp, ctx: &egui::Context, ppp: f32, max_side: u3 } // The gesture ended or the plan stopped holding (then not again in this gesture): freeze // where the layers are now. - if let Some((b, _)) = moved.as_ref().filter(|(b, _)| Arc::as_ptr(b) as usize == s.base) { - app.canvas.sprite_declined = Arc::as_ptr(b) as usize; + if let Some((b, _)) = moved.as_ref().filter(|(b, _)| Arc::ptr_eq(b, &s.base)) { + app.canvas.sprite_declined = Some(Arc::downgrade(b)); } - match ds.doc.world_transform(s.roots[0]).translation() { - t if ds.doc.contains(s.roots[0]) => { + match s.roots.first().filter(|r| ds.doc.contains(**r)) { + Some(r) => { + let t = ds.doc.world_transform(*r).translation(); s.delta = (t.x - s.root_at.0, t.y - s.root_at.1); s.ending = true; s.release = None; } - _ => app.canvas.sprite = None, + None => app.canvas.sprite = None, } } let (base, _) = moved?; - let ptr = Arc::as_ptr(&base) as usize; - if app.canvas.sprite_declined == ptr || !view_ok { + if app.canvas.sprite_declined.as_ref().is_some_and(|d| Weak::ptr_eq(d, &Arc::downgrade(&base))) || !view_ok { return None; } let canvas_px = f64::from(app.canvas.rect.width() * ppp) * f64::from(app.canvas.rect.height() * ppp); - match plan(ctx, &base, &ds.selection, zoom, ppp, max_side, canvas_px) { + match plan(ctx, &base, &ds.selection, (ds.uid, ds.page), zoom, ppp, max_side, canvas_px) { Some(s) => { let out = (base, s.roots.clone()); app.canvas.sprite = Some(s); Some(out) } None => { - app.canvas.sprite_declined = ptr; + app.canvas.sprite_declined = Some(Arc::downgrade(&base)); None } } @@ -177,22 +185,29 @@ fn plain(doc: &Document, id: NodeId, clip: &mut Option) -> return false; } let mut at = n.parent; + let mut child = id; while let Some(a) = at.and_then(|a| doc.node(a)) { - // At every level, the page included: inside a boolean result, or beside a mask, the layer - // doesn't draw on its own. - if matches!(a.kind, NodeKind::BooleanOp { .. }) || a.children.iter().any(|c| doc.node(*c).is_some_and(|c| c.is_mask)) { + // At every level, the page included: inside a boolean result, or above a mask (a mask + // masks the layers above it in its container), the layer doesn't draw on its own. + let above_a_mask = a.children.iter().take_while(|c| **c != child).any(|c| doc.node(*c).is_some_and(|c| c.is_mask)); + if matches!(a.kind, NodeKind::BooleanOp { .. }) || above_a_mask { return false; } if matches!(a.kind, NodeKind::Page { .. }) { break; } - if !a.effects.is_empty() || !ordinary(a.blend) || a.opacity < 1.0 || a.is_mask { + if !a.effects.is_empty() || !ordinary(a.blend) || a.opacity.is_nan() || a.opacity < 1.0 || a.is_mask { return false; } if a.clip && a.kind.is_frame_like() { + // The sprite is clipped to a rectangle: a rounded frame clips to a shape it can't follow. + if a.corners.radii.iter().any(|r| *r != 0.0) { + return false; + } let Some(b) = doc.world_bounds(a.id) else { return false }; *clip = Some(clip.map_or(b, |c| c.intersect(b))); } + child = a.id; at = a.parent; } true @@ -200,7 +215,17 @@ fn plain(doc: &Document, id: NodeId, clip: &mut Option) -> /// Render the dragged layers of `base` into a sprite, if they qualify: the roots are plain (see /// [`plain`]), none inside another, and the sprite fits a texture and a few canvases of pixels. -fn plan(ctx: &egui::Context, base: &Arc, sel: &[NodeId], zoom: f64, ppp: f32, max_side: u32, canvas_px: f64) -> Option { +#[allow(clippy::too_many_arguments)] +fn plan( + ctx: &egui::Context, + base: &Arc, + sel: &[NodeId], + of: (u64, NodeId), + zoom: f64, + ppp: f32, + max_side: u32, + canvas_px: f64, +) -> Option { if sel.is_empty() || !zoom.is_finite() || zoom <= 0.0 { return None; } @@ -213,9 +238,10 @@ fn plan(ctx: &egui::Context, base: &Arc, sel: &[NodeId], zoom: f64, pp // Bottom to top, as the page draws them. let page = base.page_of(sel[0])?; let order = base.subtree(page); - let mut roots: Vec = order.iter().copied().filter(|i| sel.contains(i)).collect(); + let roots: Vec = order.iter().copied().filter(|i| sel.contains(i)).collect(); + // Not all on the page of the first (or not in the document): the old way, rather than a guessed order. if roots.len() != sel.len() { - roots = sel.to_vec(); + return None; } let bounds = roots.iter().filter_map(|i| base.world_render_bounds(*i)).reduce(|a, b| a.union(b))?; let scale = zoom * f64::from(ppp); @@ -229,22 +255,15 @@ fn plan(ctx: &egui::Context, base: &Arc, sel: &[NodeId], zoom: f64, pp return None; } let pix = figcraft_render::render_area(base, &roots, bounds, scale)?; + // What came back is what the texture is made of: the same limits again. + let (pw, ph) = (f64::from(pix.width()), f64::from(pix.height())); + if !(pw <= side && ph <= side && pw * ph <= canvas_px * MAX_AREA_FACTOR) { + return None; + } let view = figcraft_render::View { origin: (bounds.x0, bounds.y0), scale, width: pix.width(), height: pix.height() }; let tex = ctx.load_texture("figcraft-drag-sprite", crate::render_worker::screen_image(&pix, base.color_profile), egui::TextureOptions::LINEAR); let t = base.world_transform(roots[0]).translation(); - Some(Sprite { - tex, - root_at: (t.x, t.y), - roots, - view, - delta: (0.0, 0.0), - zoom, - ppp, - base: Arc::as_ptr(base) as usize, - clip, - ending: false, - release: None, - }) + Some(Sprite { tex, root_at: (t.x, t.y), roots, view, delta: (0.0, 0.0), zoom, ppp, base: base.clone(), of, clip, ending: false, release: None }) } #[cfg(test)] @@ -284,4 +303,66 @@ mod plain_tests { assert!(doc.node(m).is_some_and(|n| n.is_mask), "the bottom layer masks"); assert!(!plain(doc, a, &mut None), "its group is masked"); } + + fn frame_with_child(s: &mut Session, props: Value) -> (figcraft_doc::NodeId, figcraft_doc::NodeId) { + let f = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()); + s.execute("node.set", &json!({"id": f, "props": props})).unwrap(); + let c = id(&s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40, "parent": f})).unwrap()); + (f, c) + } + + #[test] + fn what_the_sprite_cannot_stand_in_for_is_not_plain() { + let mut s = Session::new(); + let (_, c) = frame_with_child(&mut s, json!({"clip": false})); + assert!(plain(s.doc().unwrap(), c, &mut None), "a layer in a plain frame is plain"); + for props in [ + json!({"opacity": 0.5}), + json!({"blend": "multiply"}), + json!({"effects": [{"type": "dropShadow", "color": "#00000066", "offset": [0, 8], "radius": 24}]}), + ] { + let mut s = Session::new(); + let (f, c) = frame_with_child(&mut s, props.clone()); + let n = s.doc().unwrap().node(f).unwrap(); + assert!(n.opacity < 1.0 || !n.effects.is_empty() || n.blend != figcraft_color::BlendMode::PassThrough, "{props} took"); + assert!(!plain(s.doc().unwrap(), c, &mut None), "an ancestor with {props}"); + } + } + + #[test] + fn a_layers_own_opacity_is_drawn_by_the_sprite() { + // `render_area` draws the layer as the page does, its opacity included. + let mut s = Session::new(); + let r = rect(&mut s, 0.0); + s.execute("node.set", &json!({"id": r, "props": {"opacity": 0.5}})).unwrap(); + assert!(s.doc().unwrap().node(r).unwrap().opacity < 1.0); + assert!(plain(s.doc().unwrap(), r, &mut None)); + } + + #[test] + fn only_the_layers_above_a_mask_are_masked() { + // A mask set in place (one layer, no group made): it masks the layers above it in its + // container, as `Document::paint_runs` draws it; the layers below it draw on their own. + let mut s = Session::new(); + let (below, m, above) = (rect(&mut s, 0.0), rect(&mut s, 50.0), rect(&mut s, 100.0)); + s.execute("object.mask", &json!({"ids": [m]})).unwrap(); + let doc = s.doc().unwrap(); + assert!(doc.node(m).is_some_and(|n| n.is_mask), "the middle layer masks in place"); + let parent = |i| doc.node(i).and_then(|n| n.parent); + assert!(parent(below) == parent(m) && parent(above) == parent(m), "one container"); + assert!(!plain(doc, above, &mut None), "above the mask: masked"); + assert!(plain(doc, below, &mut None), "below it nothing is masked"); + } + + #[test] + fn a_rounded_clipping_ancestor_is_not_plain_a_square_one_is_clipped_to() { + let mut s = Session::new(); + let (f, c) = frame_with_child(&mut s, json!({"clip": true})); + let mut clip = None; + assert!(plain(s.doc().unwrap(), c, &mut clip)); + assert_eq!(clip, s.doc().unwrap().world_bounds(f)); + let mut s = Session::new(); + let (_, c) = frame_with_child(&mut s, json!({"clip": true, "cornerRadius": 12})); + assert!(!plain(s.doc().unwrap(), c, &mut None), "a rounded frame clips to a shape the sprite can't follow"); + } } diff --git a/crates/ui-egui/src/canvas_drag_tests.rs b/crates/ui-egui/src/canvas_drag_tests.rs index 546c56da1..65292869f 100644 --- a/crates/ui-egui/src/canvas_drag_tests.rs +++ b/crates/ui-egui/src/canvas_drag_tests.rs @@ -162,6 +162,10 @@ fn dragging_a_plain_frame_draws_its_sprite_with_the_outline() { let outline = u.app.to_screen(b[0].x + dx, b[0].y + dy); let sprite = u.app.canvas.sprite_rect(&u.app).unwrap(); assert!((sprite.min - outline).length() < 0.6, "sprite {:?} outline {outline:?}", sprite.min); + // It is the frame (300 x 200) at the view's zoom, and no move asks the worker for anything. + let zoom = u.app.session.ds().unwrap().view.zoom; + assert!((f64::from(sprite.width()) - 300.0 * zoom).abs() < 1.5 && (f64::from(sprite.height()) - 200.0 * zoom).abs() < 1.5, "{sprite:?}"); + assert!(!u.app.worker.as_ref().is_some_and(|w| w.in_flight()), "no render for a move"); } // The base stays put: later moves ask for no new render. settle(&mut u); @@ -172,6 +176,7 @@ fn dragging_a_plain_frame_draws_its_sprite_with_the_outline() { u.button(p + vec2(90.0, 40.0), false); u.frame(vec![]); assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..]), "the whole document is rendered again"); + assert!(u.app.canvas.sprite_rect(&u.app).is_some(), "the sprite stays until that render is shown"); settle(&mut u); u.frame(vec![]); assert!(u.app.canvas.sprite_rect(&u.app).is_none(), "the sprite goes once that render is shown"); @@ -225,3 +230,75 @@ fn zooming_during_a_drag_ends_the_fast_path() { assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..])); u.button(p + vec2(48.0, 15.0), false); } + +/// Drag `u`'s frame four frames, with the sprite up. +fn start_drag(u: &mut Ui, p: egui::Pos2) { + u.button(p, true); + drag_frames(u, p, 4); + assert!(u.app.canvas.sprite_rect(&u.app).is_some(), "the sprite exists"); +} + +#[test] +fn a_cancelled_drag_keeps_its_sprite_until_the_restored_document_shows_and_the_next_drag_has_one() { + let (mut u, _f, p) = frame_with_child(false); + start_drag(&mut u, p); + u.app.session.cancel_interaction().unwrap(); + u.frame(vec![]); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..]), "the restored document is rendered whole"); + assert!(u.app.canvas.sprite_rect(&u.app).is_some(), "the sprite stays until that render is shown"); + u.button(p, false); + settle(&mut u); + u.frame(vec![]); + assert!(u.app.canvas.sprite_rect(&u.app).is_none()); + // The restored document is the one the cancelled drag started from: a new drag of it still gets a sprite. + start_drag(&mut u, p); + u.button(p + vec2(30.0, 10.0), false); +} + +#[test] +fn a_drag_that_declined_the_sprite_does_not_decline_the_next_drag_of_the_same_document() { + let (mut u, _f, p) = frame_with_child(false); + start_drag(&mut u, p); + let z = u.app.session.ds().unwrap().view.zoom; + u.app.session.ds_mut().unwrap().view.zoom = z * 1.5; + u.frame(vec![Event::PointerMoved(p + vec2(40.0, 12.0))]); + u.app.session.cancel_interaction().unwrap(); + u.button(p, false); + settle(&mut u); + u.app.session.ds_mut().unwrap().view.zoom = z; + settle(&mut u); + let p = u.app.to_screen(350.0, 250.0); + start_drag(&mut u, p); + u.button(p + vec2(30.0, 10.0), false); +} + +#[test] +fn deleting_the_dragged_layer_mid_drag_drops_the_sprite_and_renders_normally() { + let (mut u, f, p) = frame_with_child(false); + start_drag(&mut u, p); + u.app.session.cancel_interaction().unwrap(); + u.app.session.execute("edit.delete", &json!({"ids": [f]})).unwrap(); + u.frame(vec![Event::PointerMoved(p + vec2(50.0, 20.0))]); + assert!(u.app.canvas.sprite_rect(&u.app).is_none(), "nothing to show"); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..])); + u.button(p + vec2(50.0, 20.0), false); +} + +#[test] +fn outline_views_keep_the_old_path() { + for flag in 0..3 { + let (mut u, _f, p) = frame_with_child(false); + let v = &mut u.app.session.ds_mut().unwrap().view; + match flag { + 0 => v.outlines = true, + 1 => v.outlines_selection = true, + _ => v.outline_hidden = true, + } + settle(&mut u); + u.button(p, true); + drag_frames(&mut u, p, 4); + assert!(u.app.canvas.sprite_rect(&u.app).is_none(), "flag {flag}"); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..]), "flag {flag}"); + u.button(p + vec2(30.0, 10.0), false); + } +} From a96edd9f7f5acf027705b90d00261e565efa0b09 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 11 Nov 2026 19:15:26 -0500 Subject: [PATCH 012/114] M3, #2033: a page switch no longer keeps the drag base render (without the dragged layers) as the page image Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/ui-egui/src/canvas.rs | 28 +++++++++++++++++++++- crates/ui-egui/src/canvas/render_worker.rs | 4 +++- crates/ui-egui/src/canvas_drag_tests.rs | 18 ++++++++++++++ 3 files changed, 48 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index d13ea3525..5cd12d59c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -56,6 +56,8 @@ pub struct CanvasState { tex_of: Option<(u64, NodeId)>, /// The texture is a coarse preview (see [`crate::render_worker`]). pub tex_coarse: bool, + /// The texture leaves out layers ([`crate::render_worker::Done::skipped`]): it is not kept as the page's image. + tex_skipped: bool, /// The request the texture answers ([`crate::render_worker::Done::seq`]). tex_seq: u64, /// Refined images of the files and pages shown before, newest first: switching back to one @@ -105,6 +107,26 @@ impl CanvasState { self.submitted.as_ref().map(|k| k.skip.as_slice()) } + /// The file and page the texture shows. + pub(crate) fn tex_of(&self) -> Option<(u64, NodeId)> { + self.tex_of + } + + /// A page or tab switch to `shown`, as the canvas does on a frame. + pub(crate) fn switch_to(&mut self, shown: (u64, NodeId)) { + self.switch_texture(Some(shown), |_| true); + } + + /// Whether an image of `of` is kept for a switch back to it. + pub(crate) fn keeps(&self, of: (u64, NodeId)) -> bool { + self.kept.iter().any(|k| k.of == of) + } + + /// Whether the canvas holds a texture. + pub(crate) fn has_texture(&self) -> bool { + self.texture.is_some() + } + /// Where the drag sprite shows on screen (at one pixel per point), if there is one. pub(crate) fn sprite_rect(&self, app: &FigApp) -> Option { drag_sprite::screen_rect(app, 1.0) @@ -119,6 +141,7 @@ impl Default for CanvasState { tex_view: None, tex_of: None, tex_coarse: false, + tex_skipped: false, tex_seq: 0, kept: Vec::new(), submitted: None, @@ -164,10 +187,12 @@ impl CanvasState { if shown.is_some() && self.tex_of != shown { let back = self.kept.iter().position(|k| Some(k.of) == shown).map(|i| self.kept.remove(i)); let (texture, view, of) = (self.texture.take(), self.tex_view.take(), self.tex_of.take()); - if let (Some(texture), Some(view), Some(of), false) = (texture, view, of, self.tex_coarse) { + // An image without the dragged layers isn't the page's complete one: not kept. + if let (Some(texture), Some(view), Some(of), false, false) = (texture, view, of, self.tex_coarse, self.tex_skipped) { self.kept.insert(0, Kept { texture, view, of, seq: self.tex_seq }); } self.tex_coarse = false; + self.tex_skipped = false; if let Some(k) = back { (self.texture, self.tex_view, self.tex_of, self.tex_seq) = (Some(k.texture), Some(k.view), Some(k.of), k.seq); } @@ -358,6 +383,7 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { app.canvas.tex_view = Some(done.view); app.canvas.tex_of = Some((done.uid, done.page)); app.canvas.tex_coarse = done.coarse; + app.canvas.tex_skipped = done.skipped; app.canvas.tex_seq = done.seq; drag_sprite::arrived(&mut app.canvas, done_at, done.coarse); } diff --git a/crates/ui-egui/src/canvas/render_worker.rs b/crates/ui-egui/src/canvas/render_worker.rs index 44a478807..81cb44fde 100644 --- a/crates/ui-egui/src/canvas/render_worker.rs +++ b/crates/ui-egui/src/canvas/render_worker.rs @@ -86,6 +86,8 @@ pub struct Done { pub page: NodeId, /// A coarse preview, refined by a later image unless a newer request replaced it. pub coarse: bool, + /// The image leaves out the layers of [`Job::skip`] (a drag's base render): not the page's complete image. + pub skipped: bool, /// [`Job::at`]. pub at: Instant, /// The request it answers, numbered by the worker in order (0 outside a worker). @@ -142,7 +144,7 @@ fn done(job: &Job, view: View, pix: &Pixmap, work: Work, ms: f64, coarse: bool) if job.proof { mark_outside_srgb(&mut image, pix, job.doc.color_profile); } - Done { image, view, ms, work, uid: job.uid, page: job.page, coarse, at: job.at, seq: 0 } + Done { image, view, ms, work, uid: job.uid, page: job.page, coarse, skipped: !job.skip.is_empty(), at: job.at, seq: 0 } } /// `view` with [`PREVIEW_FACTOR`] times fewer pixels each way, showing at least the same area. diff --git a/crates/ui-egui/src/canvas_drag_tests.rs b/crates/ui-egui/src/canvas_drag_tests.rs index 65292869f..5c8f4c4ad 100644 --- a/crates/ui-egui/src/canvas_drag_tests.rs +++ b/crates/ui-egui/src/canvas_drag_tests.rs @@ -302,3 +302,21 @@ fn outline_views_keep_the_old_path() { u.button(p + vec2(30.0, 10.0), false); } } + +#[test] +fn a_page_switch_does_not_keep_the_drags_base_render_as_the_pages_image() { + let (mut u, f, p) = frame_with_child(false); + u.button(p, true); + drag_frames(&mut u, p, 4); + settle(&mut u); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[f][..]), "the render shown leaves the dragged layer out"); + let ds = u.app.session.ds().unwrap(); + let (here, other) = ((ds.uid, ds.page), (ds.uid, figcraft_doc::NodeId(ds.page.0 + 1))); + assert_eq!(u.app.canvas.tex_of(), Some(here)); + // Switching away while it shows must not keep it: coming back would show the page without the dragged layer. + u.app.canvas.switch_to(other); + assert!(!u.app.canvas.keeps(here), "an image without the dragged layers is not kept"); + u.app.canvas.switch_to(here); + assert!(!u.app.canvas.has_texture(), "so coming back shows no image until the render lands"); + u.button(p + vec2(30.0, 10.0), false); +} From bb9a1906d974a9dad4ec31e5570d26f90398a44c Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 11 Nov 2026 22:45:46 -0500 Subject: [PATCH 013/114] Docs: drop the duplicate Scale tool row left by the union merge, keeping main's Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- docs/ui-parity.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 574b333db..bea186f92 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -69,7 +69,6 @@ interaction feel not yet compared. | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | | A dragged layer moves with its outline | partial | #2033: the canvas image is the last render the worker finished, so a drag's content trailed its outline by a render per pointer move (63 ms, about 3.6 frames, and 150 px on screen with drop shadows on 200 layers). While a gesture only translates plain layers (Normal or pass-through blend, no effects on them or above them, not masks, not in a boolean group or beside a mask, no ancestor under 100 percent opacity; their own children may have effects) the layers are rendered once into a texture of their own (the sprite), the base is rendered once without them from the document the drag started from and then asks for no more renders, and the sprite is drawn each frame at the same shifted place as the selection outline. On release, Escape or a zoom change the document is rendered whole again and the sprite stays until that image is shown. Desktop only (the browser renders in the same frame). Trade-offs while dragging: the sprite draws above everything (z-order is lost), blends and backdrop blurs against what is behind are approximated, ancestors' clips are applied as their bounding boxes, and a sprite wider than the texture limit or over four canvases of pixels, outline and focus views, pixel preview and soft proof keep the old way (`canvas/drag_sprite.rs`) | -| Scale tool (K): handles about an anchor, live factor, panel | done | | | Scale tool (K): handles about an anchor, live factor, panel | done | Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured), as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`. | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; thresholds not yet compared with Figma's (`guide_snap_tests`) | From 0859f94c7d80e9d76b925361730034947526b6c8 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 20:27:55 -0500 Subject: [PATCH 014/114] Presenter: the hidpi detail replaces the whole-frame texture instead of drawing over it (#2127) Both textures start from a transparent pixmap, so a translucent layer was counted twice where the detail covered it. The whole-frame texture is now drawn only around the detail rect (up to four clipped strips), then the detail. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/ui-egui/src/present/draw.rs | 37 ++++++++++++++++--- crates/ui-egui/src/present/tests.rs | 56 +++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/present/draw.rs b/crates/ui-egui/src/present/draw.rs index 28bc11891..0afe7cd86 100644 --- a/crates/ui-egui/src/present/draw.rs +++ b/crates/ui-egui/src/present/draw.rs @@ -75,17 +75,24 @@ pub(super) fn draw(p: &mut Presenter, painter: &egui::Painter, ctx: &egui::Conte } if !drawn && let Some(to) = &to_tex { let on_clip = painter.with_clip_rect(l.clip); - on_clip.image(to.tex.id(), l.place.rect(to.bounds), uv, Color32::WHITE); // A frame too big for one texture at device scale is drawn from a smaller one: the part in - // view is drawn again from a texture at device scale, over it (and the overlays over that). + // view is drawn from a texture at device scale instead. The detail REPLACES that part of the + // whole-frame texture (the base is drawn only around it): both start from a transparent + // pixmap, so drawn over it a translucent layer would count twice. let shown = l.clip.intersect(l.place.rect(to.bounds)); + let mut detail = None; if shown.is_positive() { let (a, b) = (l.place.page(shown.min), l.place.page(shown.max)); let visible = figcraft_geom::Rect::new(a.x, a.y, b.x, b.y); let moving = p.fling.is_some() || p.drag_scroll.is_some() || p.wheel.is_some(); - if let Some(d) = p.detail_texture(ctx, &l.disp, p.current, px, to.bounds, visible, moving, now) { - on_clip.image(d.tex.id(), l.place.rect(d.bounds), uv, Color32::WHITE); - } + detail = p.detail_texture(ctx, &l.disp, p.current, px, to.bounds, visible, moving, now); + } + let hole = detail.as_ref().map(|d| l.clip.intersect(l.place.rect(d.bounds))); + for part in base_parts(l.clip, hole) { + painter.with_clip_rect(part).image(to.tex.id(), l.place.rect(to.bounds), uv, Color32::WHITE); + } + if let Some(d) = detail { + on_clip.image(d.tex.id(), l.place.rect(d.bounds), uv, Color32::WHITE); } } // Overlays (each with its background and opening transition); closing ones run it backwards. @@ -133,3 +140,23 @@ pub(super) fn draw(p: &mut Presenter, painter: &egui::Painter, ctx: &egui::Conte ctx.request_repaint(); } } + +/// The parts of `clip` outside `hole` (up to four disjoint rectangles; `clip` itself with no hole). +pub(super) fn base_parts(clip: Rect, hole: Option) -> Vec { + let Some(h) = hole.filter(|h| h.is_positive()) else { + return vec![clip]; + }; + let h = h.intersect(clip); + if !h.is_positive() { + return vec![clip]; + } + [ + Rect::from_min_max(clip.min, egui::pos2(clip.max.x, h.min.y)), + Rect::from_min_max(egui::pos2(clip.min.x, h.max.y), clip.max), + Rect::from_min_max(egui::pos2(clip.min.x, h.min.y), egui::pos2(h.min.x, h.max.y)), + Rect::from_min_max(egui::pos2(h.max.x, h.min.y), egui::pos2(clip.max.x, h.max.y)), + ] + .into_iter() + .filter(|r| r.is_positive()) + .collect() +} diff --git a/crates/ui-egui/src/present/tests.rs b/crates/ui-egui/src/present/tests.rs index dde23026f..58c669754 100644 --- a/crates/ui-egui/src/present/tests.rs +++ b/crates/ui-egui/src/present/tests.rs @@ -536,3 +536,59 @@ fn detail_plan_edge_cases() { let view = R::new(0.0, 0.0, 1440.0, 860.0); assert_eq!(actions::detail_plan(bounds, view, 2.0, 2048.0), Some(view)); } + +#[test] +fn the_detail_replaces_the_whole_frame_texture_instead_of_drawing_over_it() { + // A frame with no fill holding a 50% rectangle: both textures start from a transparent pixmap, + // so drawn over each other the rectangle would count twice (75%, not 50%). + let mut session = figcraft_engine::Session::new(); + let frame = id(&session.execute("node.create", &json!({"type": "frame", "width": 1440, "height": 9701, "props": {"fills": []}})).unwrap()); + let r = + id(&session.execute("node.create", &json!({"type": "rectangle", "parent": frame, "x": 0, "y": 0, "width": 1440, "height": 9701})).unwrap()); + session.execute("node.set", &json!({"id": r, "props": {"fill": "#ff0000", "opacity": 0.5}})).unwrap(); + let mut ui = Ui::new(session); + ui.hidpi = Some((2.0, 16_384)); + ui.run("proto.present", json!({"start": frame})); + ui.app.ui.present.as_mut().unwrap().view.scale = PresentScale::FitWidth; + ui.frames(2, Vec::new); + + // The pixel's alpha is the rectangle's 0.5 in the whole-frame render and in the detail render. + let doc = ui.app.session.doc().unwrap(); + let alpha = |pix: &figcraft_render::Pixmap| pix.data()[3]; + let whole = figcraft_render::render_node_at(doc, frame, 0.5, 0.0).unwrap(); + let detail = figcraft_render::render_area_at(doc, &[frame], figcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0), 2.0, 0.0).unwrap(); + assert!((i32::from(alpha(&whole)) - 128).abs() <= 1 && (i32::from(alpha(&detail)) - 128).abs() <= 1); + + // On screen, no whole-frame texture is drawn under the detail: one texture covers its centre. + let out = ui.frame_output(Vec::new()); + let prims = ui.ctx.tessellate(out.shapes, 2.0); + let names: std::collections::HashMap = + ui.ctx.tex_manager().read().allocated().map(|(id, m)| (*id, m.name.clone())).collect(); + let mut present: Vec<(String, egui::Rect, egui::Rect)> = Vec::new(); + for prim in &prims { + if let egui::epaint::Primitive::Mesh(m) = &prim.primitive + && let Some(n) = names.get(&m.texture_id).filter(|n| n.starts_with("present-")) + { + let bbox = m.vertices.iter().fold(egui::Rect::NOTHING, |r, v| r.union(egui::Rect::from_min_max(v.pos, v.pos))); + present.push((n.clone(), bbox, prim.clip_rect)); + } + } + let (_, dbox, dclip) = present.iter().find(|(n, ..)| n.starts_with("present-detail-")).expect("the detail is drawn"); + let centre = dbox.intersect(*dclip).center(); + let covering: Vec<_> = present.iter().filter(|(_, b, c)| b.contains(centre) && c.contains(centre)).map(|(n, ..)| n.as_str()).collect(); + assert_eq!(covering.len(), 1, "only the detail covers the view's centre:: {covering:?}"); +} + +#[test] +fn base_parts_leave_the_hole_out() { + use egui::{Rect, pos2}; + let clip = Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 100.0)); + assert_eq!(draw::base_parts(clip, None), vec![clip]); + let hole = Rect::from_min_max(pos2(10.0, 20.0), pos2(60.0, 70.0)); + let parts = draw::base_parts(clip, Some(hole)); + assert_eq!(parts.len(), 4); + let area: f32 = parts.iter().map(|r| r.width() * r.height()).sum(); + assert_eq!(area, 100.0 * 100.0 - 50.0 * 50.0); + assert!(parts.iter().all(|r| !r.intersects(hole.shrink(0.01)))); + assert!(draw::base_parts(clip, Some(clip)).is_empty()); +} From 2182962f7e978e41a21f49b5e3fa54bb67937655 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 20:34:43 -0500 Subject: [PATCH 015/114] Drag sprite: decline for a rotated or skewed clipping frame and for layers under different clipping frames The sprite clipped to the world bounds of each clipping ancestor, which is the real clip only when the frame is axis-aligned, and intersected the clips of unrelated frames into one. Both now fall back to the normal render path. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/geom/src/transform.rs | 8 +++++ crates/ui-egui/src/canvas/drag_sprite.rs | 40 ++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/crates/geom/src/transform.rs b/crates/geom/src/transform.rs index 69c6c788d..98e10fe6f 100644 --- a/crates/geom/src/transform.rs +++ b/crates/geom/src/transform.rs @@ -11,6 +11,14 @@ pub fn rotation_degrees(xf: Affine) -> f64 { if deg <= -180.0 { deg + 360.0 } else { deg } } +/// Whether `xf` maps axis-aligned rectangles to axis-aligned rectangles: scale, flip, translate or a +/// quarter turn, but no other rotation and no skew. +pub fn is_axis_aligned(xf: Affine) -> bool { + let [a, b, c, d, ..] = xf.as_coeffs(); + let tol = 1e-9 * (a.abs() + b.abs() + c.abs() + d.abs()).max(1.0); + (b.abs() <= tol && c.abs() <= tol) || (a.abs() <= tol && d.abs() <= tol) +} + /// The translation part of `xf`. pub fn translation(xf: Affine) -> Point { let c = xf.as_coeffs(); diff --git a/crates/ui-egui/src/canvas/drag_sprite.rs b/crates/ui-egui/src/canvas/drag_sprite.rs index 8ef80e575..2425d23a2 100644 --- a/crates/ui-egui/src/canvas/drag_sprite.rs +++ b/crates/ui-egui/src/canvas/drag_sprite.rs @@ -204,6 +204,11 @@ fn plain(doc: &Document, id: NodeId, clip: &mut Option) -> if a.corners.radii.iter().any(|r| *r != 0.0) { return false; } + // Its world box is the clip only when the frame is axis-aligned: for a rotated or skewed + // one it is just the box around the real clip, and the layers would paint outside it. + if !figcraft_geom::is_axis_aligned(doc.world_transform(a.id)) { + return false; + } let Some(b) = doc.world_bounds(a.id) else { return false }; *clip = Some(clip.map_or(b, |c| c.intersect(b))); } @@ -213,6 +218,11 @@ fn plain(doc: &Document, id: NodeId, clip: &mut Option) -> true } +/// The clipping frames above layer `id`, nearest first. +fn clippers(doc: &Document, id: NodeId) -> Vec { + doc.ancestors(id).into_iter().filter(|a| doc.node(*a).is_some_and(|n| n.clip && n.kind.is_frame_like())).collect() +} + /// Render the dragged layers of `base` into a sprite, if they qualify: the roots are plain (see /// [`plain`]), none inside another, and the sprite fits a texture and a few canvases of pixels. #[allow(clippy::too_many_arguments)] @@ -230,6 +240,13 @@ fn plan( return None; } let mut clip = None; + // Layers under different clipping frames would need a clip each; one shared (intersected) clip + // could hide both, so the sprite stands aside. + if let Some((first, rest)) = sel.split_first() + && rest.iter().any(|o| clippers(base, *o) != clippers(base, *first)) + { + return None; + } for id in sel { if !plain(base, *id, &mut clip) || sel.iter().any(|o| o != id && base.ancestors(*id).contains(o)) { return None; @@ -365,4 +382,27 @@ mod plain_tests { let (_, c) = frame_with_child(&mut s, json!({"clip": true, "cornerRadius": 12})); assert!(!plain(s.doc().unwrap(), c, &mut None), "a rounded frame clips to a shape the sprite can't follow"); } + + #[test] + fn a_rotated_clipping_ancestor_is_not_plain() { + let mut s = Session::new(); + let (f, c) = frame_with_child(&mut s, json!({"clip": true})); + assert!(plain(s.doc().unwrap(), c, &mut None), "axis-aligned: plain"); + s.execute("transform.rotate", &json!({"ids": [f], "degrees": 30})).unwrap(); + assert!(!plain(s.doc().unwrap(), c, &mut None), "its world box is not its clip"); + } + + #[test] + fn layers_under_different_clipping_frames_decline_the_sprite() { + let ctx = egui::Context::default(); + let mut s = Session::new(); + let (_, a) = frame_with_child(&mut s, json!({"clip": true})); + let f2 = id(&s.execute("frame.create", &json!({"x": 300, "y": 0, "width": 200, "height": 200})).unwrap()); + s.execute("node.set", &json!({"id": f2, "props": {"clip": true}})).unwrap(); + let b = id(&s.execute("shape.rectangle", &json!({"x": 310, "y": 10, "width": 40, "height": 40, "parent": f2})).unwrap()); + let base = std::sync::Arc::new(s.doc().unwrap().clone()); + let of = (0, base.page_of(a).unwrap()); + assert!(super::plan(&ctx, &base, &[a], of, 1.0, 1.0, 4096, 1e9).is_some(), "one clipping frame: a sprite"); + assert!(super::plan(&ctx, &base, &[a, b], of, 1.0, 1.0, 4096, 1e9).is_none(), "two: no shared clip"); + } } From 6d4df2b9099f97c1eef2c1b722629a5a690d8838 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 21:15:22 -0500 Subject: [PATCH 016/114] Presenter: a view a rounding error past the frame keeps its detail texture (#2127) The page rect of the view, converted back from the screen, can stand a hair outside the frame. The cached detail is always inside the frame, so it never covered that view, and a still view rendered a new detail every frame. detail_texture now clips the view to the frame first. Test: present::tests::a_view_a_rounding_error_past_the_frame_keeps_its_detail (failed before: a new texture on the second call). Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- crates/ui-egui/src/present/actions.rs | 4 ++++ crates/ui-egui/src/present/tests.rs | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/crates/ui-egui/src/present/actions.rs b/crates/ui-egui/src/present/actions.rs index ec23bd8be..d3386da0a 100644 --- a/crates/ui-egui/src/present/actions.rs +++ b/crates/ui-egui/src/present/actions.rs @@ -281,6 +281,10 @@ impl Presenter { moving: bool, now: f64, ) -> Option { + // Converted back from the screen, the view can stand a rounding error outside the frame, + // which a detail (always inside the frame) never covers: a still view would then render a + // new detail every frame. + let visible = visible.intersect(whole); let (t, clock) = self.frame_clock(ctx, doc, id, now); let key = (self.rev, px.to_bits(), clock.map_or(0, |c| c.0)); let covers = |b: &figcraft_geom::Rect| b.x0 <= visible.x0 && b.y0 <= visible.y0 && b.x1 >= visible.x1 && b.y1 >= visible.y1; diff --git a/crates/ui-egui/src/present/tests.rs b/crates/ui-egui/src/present/tests.rs index 58c669754..2cb710923 100644 --- a/crates/ui-egui/src/present/tests.rs +++ b/crates/ui-egui/src/present/tests.rs @@ -511,6 +511,22 @@ fn the_detail_is_kept_while_nothing_changes_and_made_again_when_the_frame_does() assert_ne!(tex_id(&ui), Some(first), "an edit renders the detail again"); } +#[test] +fn a_view_a_rounding_error_past_the_frame_keeps_its_detail() { + let mut ui = tall_hidpi(16_384); + let ctx = ui.ctx.clone(); + let doc = ui.app.session.doc().unwrap().clone(); + let now = ui.time; + let p = ui.app.ui.present.as_mut().unwrap(); + let id = p.current; + let whole = figcraft_geom::Rect::new(0.0, 0.0, 1440.0, 9701.0); + // The screen-to-page round trip can put the view a hair outside the frame. + let view = figcraft_geom::Rect::new(-1e-9, 0.0, 1440.0 + 1e-9, 860.0); + let first = p.detail_texture(&ctx, &doc, id, 2.0, whole, view, false, now).expect("a detail").tex.id(); + let again = p.detail_texture(&ctx, &doc, id, 2.0, whole, view, false, now).expect("a detail").tex.id(); + assert_eq!(again, first, "the same view reuses its detail instead of rendering a new one"); +} + #[test] fn detail_plan_edge_cases() { use figcraft_geom::Rect as R; From 654f1c4911a945cda7ce3939b39edfb20ab811c7 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 22:28:38 -0500 Subject: [PATCH 017/114] M8: a scale that would take an instance past its scale range is refused, so bound and unbound lengths stay equal (#2090) scale_node clamped only the stored scale factor while every other length took the full factor, so past 0.001 to 1000 a bound length (drawn at the variable's value times the factor) and an unbound one drifted apart. A new scale_fits checks every instance the scale multiplies (sharing the covered rule with scale_node) and scale_node and transform.scale refuse before changing anything; a selection where only one root fails changes nothing. The Scale tool drag keeps the last frame that fit. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/engine/src/canvas/tools/drag.rs | 15 ++- crates/engine/src/cmd/arrange.rs | 78 +++++++++++----- crates/engine/src/scale_bound_values_tests.rs | 91 +++++++++++++++++++ docs/components-parity.md | 4 +- docs/ui-parity.md | 4 +- 5 files changed, 165 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/canvas/tools/drag.rs b/crates/engine/src/canvas/tools/drag.rs index ea336a142..07697afaf 100644 --- a/crates/engine/src/canvas/tools/drag.rs +++ b/crates/engine/src/canvas/tools/drag.rs @@ -646,14 +646,25 @@ impl Session { // A layer's place in the box scales about the pivot; a negative factor turns it over. let about = frame * Affine::translate(pivot.to_vec2() * (1.0 - k)); let sign = k.signum(); - self.preview(|doc, _| { + // A factor an instance can't follow (its scale factor would leave 0.001 to 1000) is not + // applied: the drag keeps the last frame that fit. + let mut refused = false; + let shown = self.preview(|doc, _| { + if !nodes.iter().all(|(id, ..)| crate::cmd::arrange::scale_fits(doc, *id, k.abs())) { + refused = true; + return Err(crate::error::bad("transform.scale", "past the scale range")); + } for (id, world, _, _) in &nodes { let c = (inv * *world).as_coeffs(); doc.set_world_transform(*id, about * Affine::new([sign * c[0], sign * c[1], sign * c[2], sign * c[3], k * c[4], k * c[5]]))?; crate::cmd::arrange::scale_node(doc, *id, k.abs())?; } Ok(()) - })?; + }); + if refused { + return Ok(()); + } + shown?; let p = frame * pivot; self.tool.overlay.scale = Some(ScaleHint { factor: k, pivot: [p.x, p.y] }); self.tool.overlay.guides = guides; diff --git a/crates/engine/src/cmd/arrange.rs b/crates/engine/src/cmd/arrange.rs index b6e5362c5..57ed10a50 100644 --- a/crates/engine/src/cmd/arrange.rs +++ b/crates/engine/src/cmd/arrange.rs @@ -403,26 +403,10 @@ fn turn_pivot(s: &Session, ids: &[NodeId]) -> Result> { pub(crate) const MIN_SCALE_FACTOR: f64 = 1e-3; pub(crate) const MAX_SCALE_FACTOR: f64 = 1e3; -/// Scale a node and everything in it uniformly (the Scale tool): sizes and positions (whatever -/// the children's constraints), strokes, effects, radii, auto layout spacing, min/max sizes, -/// layout grids, ruler guides, tiled images and text sizes. -/// -/// Variable-bound lengths follow the incumbent (#2090): an instance multiplies its scale factor and -/// keeps its bindings, which draw at the variable's value times the factor; any other layer not -/// inside an instance keeps the scaled value and drops the binding of each length it scaled. -pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { - let k = if k.is_finite() && k > 0.0 { k } else { return Ok(()) }; - let sub = doc.subtree(id); - // The layers below `id` scale whatever their constraints, so where they are layers of an - // instance their new size and place are overrides. The edit's own diff takes geometry that - // changed with an ancestor's size for what constraints give, so the next rebuild of the - // instance would put them back at their main's size (#922). - let in_instance: Vec = sub.iter().enumerate().map(|(depth, i)| depth > 0 && crate::components::inside_instance(doc, *i)).collect(); - let nested: Vec = sub.iter().map(|i| crate::components::inside_instance(doc, *i)).collect(); - // An instance inside another instance of the subtree is covered by the outer factor through - // `scale_of`'s product (#2090); only an instance with no instance above it, up to `id`, takes k. - let covered: Vec = sub - .iter() +/// For each layer of `sub` (the subtree of `id`), whether an instance sits above it, up to `id` +/// (never `id` itself): `scale_of`'s product already carries the outer factor to it (#2090). +fn covered_by_instance(doc: &Document, sub: &[NodeId], id: NodeId) -> Vec { + sub.iter() .map(|i| { if *i == id { return false; @@ -437,7 +421,51 @@ pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { } false }) - .collect(); + .collect() +} + +/// Whether [`scale_node`] by `k` keeps every instance it multiplies inside the scale factor's +/// range. Every other length takes the full `k`, so a factor that had to be clamped would leave +/// bound lengths (drawn at the variable's value times the factor) off from unbound ones. +pub(crate) fn scale_fits(doc: &Document, id: NodeId, k: f64) -> bool { + if !(k.is_finite() && k > 0.0) { + return true; + } + let sub = doc.subtree(id); + let covered = covered_by_instance(doc, &sub, id); + sub.iter().enumerate().all(|(depth, i)| { + let Some(n) = doc.node(*i) else { return true }; + if !matches!(n.kind, NodeKind::Instance { .. }) || covered.get(depth).copied().unwrap_or(false) { + return true; + } + // A hair of slack, so 10 x 100 and 0.1 x 0.01 land on the bounds despite rounding. + let f = n.scale_factor * k; + (MIN_SCALE_FACTOR * (1.0 - 1e-9)..=MAX_SCALE_FACTOR * (1.0 + 1e-9)).contains(&f) + }) +} + +/// Scale a node and everything in it uniformly (the Scale tool): sizes and positions (whatever +/// the children's constraints), strokes, effects, radii, auto layout spacing, min/max sizes, +/// layout grids, ruler guides, tiled images and text sizes. +/// +/// Variable-bound lengths follow the incumbent (#2090): an instance multiplies its scale factor and +/// keeps its bindings, which draw at the variable's value times the factor; any other layer not +/// inside an instance keeps the scaled value and drops the binding of each length it scaled. +pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { + let k = if k.is_finite() && k > 0.0 { k } else { return Ok(()) }; + if !scale_fits(doc, id, k) { + return Err(scale_range_error()); + } + let sub = doc.subtree(id); + // The layers below `id` scale whatever their constraints, so where they are layers of an + // instance their new size and place are overrides. The edit's own diff takes geometry that + // changed with an ancestor's size for what constraints give, so the next rebuild of the + // instance would put them back at their main's size (#922). + let in_instance: Vec = sub.iter().enumerate().map(|(depth, i)| depth > 0 && crate::components::inside_instance(doc, *i)).collect(); + let nested: Vec = sub.iter().map(|i| crate::components::inside_instance(doc, *i)).collect(); + // An instance inside another instance of the subtree is covered by the outer factor through + // `scale_of`'s product (#2090); only an instance with no instance above it, up to `id`, takes k. + let covered = covered_by_instance(doc, &sub, id); let tiles = |paints: &mut Vec| { for p in paints { if let figcraft_color::PaintKind::Image(img) = &mut p.kind @@ -565,6 +593,10 @@ pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { Ok(()) } +fn scale_range_error() -> crate::EngineError { + bad("transform.scale", "the scale would take an instance past the supported scale range of 0.001 to 1000") +} + fn scale_cmd(s: &mut Session, p: &Value) -> Result { let k = req_num("transform.scale", p, "factor")?; if k <= 0.0 { @@ -575,6 +607,10 @@ fn scale_cmd(s: &mut Session, p: &Value) -> Result { let ids = roots(doc, &ids); let b = doc.bounds_of(&ids).unwrap_or_default(); let pivot = Point::new(num_or(p, "cx", b.x0), num_or(p, "cy", b.y0)); + // Refuse before anything changes, so a selection where only a later root fails stays whole. + if !ids.iter().all(|i| scale_fits(doc, *i, k)) { + return Err(scale_range_error()); + } for i in ids { let Some(nb) = doc.world_bounds(i) else { continue }; scale_node(doc, i, k)?; diff --git a/crates/engine/src/scale_bound_values_tests.rs b/crates/engine/src/scale_bound_values_tests.rs index eb936a042..c6e7244cf 100644 --- a/crates/engine/src/scale_bound_values_tests.rs +++ b/crates/engine/src/scale_bound_values_tests.rs @@ -246,3 +246,94 @@ fn scaling_a_frame_holding_an_instance_drops_its_own_binding_and_scales_the_inst assert!(saved.get("scale_factor").is_none(), "{saved}"); healthy(&s); } + +/// A bound instance beside an unbound rectangle with the same radius (4), as (instance, its first +/// rectangle, the unbound one). +fn bound_and_unbound(s: &mut Session) -> (NodeId, NodeId, NodeId) { + let (_c, a, i) = row_instance(s); + let r = idv(&ex(s, "shape.rectangle", json!({"x": 500, "y": 0, "width": 24, "height": 24}))); + ex(s, "node.set", json!({"id": r, "props": {"cornerRadius": 4}})); + (i, a, r) +} + +fn radius(s: &Session, id: NodeId) -> f64 { + node(s, id).corners.radii[0] +} + +/// The bound radius (the instance's copy of `a`) and the unbound one agree: both are 4 times `k`. +fn assert_radii_equal(s: &Session, i: NodeId, a: NodeId, r: NodeId, k: f64, why: &str) { + let (bound, plain) = (radius(s, copy_of(s, i, a)), radius(s, r)); + assert!(near(bound, 4.0 * k) && near(plain, 4.0 * k), "{why}: bound {bound} unbound {plain} want {}", 4.0 * k); +} + +#[test] +fn scaling_past_the_largest_factor_is_refused_and_keeps_bound_and_unbound_lengths_equal() { + let mut s = Session::new(); + let (i, a, r) = bound_and_unbound(&mut s); + ex(&mut s, "transform.scale", json!({"ids": [i, r], "factor": 100})); + assert!(near(factor(&s, i), 100.0)); + assert_radii_equal(&s, i, a, r, 100.0, "first"); + let again = s.execute("transform.scale", &json!({"ids": [i, r], "factor": 100})); + assert!(again.is_err(), "the second scale must be refused: {again:?}"); + assert!(near(factor(&s, i), 100.0), "factor {}", factor(&s, i)); + assert_radii_equal(&s, i, a, r, 100.0, "after the refusal"); + healthy(&s); + s.undo().unwrap(); + assert!(near(factor(&s, i), 1.0), "factor after undo {}", factor(&s, i)); + assert_radii_equal(&s, i, a, r, 1.0, "undone"); +} + +#[test] +fn scaling_past_the_smallest_factor_is_refused_the_same_way() { + let mut s = Session::new(); + let (i, a, r) = bound_and_unbound(&mut s); + ex(&mut s, "transform.scale", json!({"ids": [i, r], "factor": 0.05})); + assert!(near(factor(&s, i), 0.05)); + assert_radii_equal(&s, i, a, r, 0.05, "first"); + let again = s.execute("transform.scale", &json!({"ids": [i, r], "factor": 0.01})); + assert!(again.is_err(), "the second scale must be refused: {again:?}"); + assert!(near(factor(&s, i), 0.05), "factor {}", factor(&s, i)); + assert_radii_equal(&s, i, a, r, 0.05, "after the refusal"); + healthy(&s); + s.undo().unwrap(); + assert!(near(factor(&s, i), 1.0), "factor after undo {}", factor(&s, i)); + assert_radii_equal(&s, i, a, r, 1.0, "undone"); +} + +#[test] +fn a_selection_where_one_instance_cannot_scale_changes_nothing() { + let mut s = Session::new(); + let (c, _a, i1) = row_instance(&mut s); + let i2 = idv(&ex(&mut s, "instance.create", json!({"component": c, "x": 600, "y": 0}))); + ex(&mut s, "transform.scale", json!({"ids": [i1], "factor": 500})); + let (before1, before2) = (node(&s, i1), node(&s, i2)); + let res = s.execute("transform.scale", &json!({"ids": [i2, i1], "factor": 4})); + assert!(res.is_err(), "{res:?}"); + assert!(near(factor(&s, i1), 500.0) && near(factor(&s, i2), 1.0), "{} {}", factor(&s, i1), factor(&s, i2)); + assert!(node(&s, i1) == before1 && node(&s, i2) == before2, "a refused scale changed a layer"); + healthy(&s); +} + +#[test] +fn dragging_the_scale_tool_past_the_limit_stops_at_the_last_factor_that_fits() { + use crate::tools::{PointerEvent, PointerKind}; + let mut s = Session::new(); + let (_c, a, i) = row_instance(&mut s); + // The instance is already 5 times; its 280 x 120 box at (300, 0) is dragged by the bottom right + // handle out to 100 times (500 in all), then to the tool's own top of 1000 times (5000 in all). + ex(&mut s, "transform.scale", json!({"ids": [i], "factor": 5})); + ex(&mut s, "select.set", json!({"ids": [i]})); + ex(&mut s, "tool.scale", json!({})); + for (kind, (x, y)) in [ + (PointerKind::Down, (580.0, 120.0)), + (PointerKind::Move, (300.0 + 280.0 * 100.0, 120.0 * 100.0)), + (PointerKind::Move, (300.0 + 280.0 * 1000.0, 120.0 * 1000.0)), + (PointerKind::Up, (300.0 + 280.0 * 1000.0, 120.0 * 1000.0)), + ] { + s.pointer(&PointerEvent::at(kind, x, y, 1.0)).unwrap(); + } + assert!(near(factor(&s, i), 500.0), "factor {}", factor(&s, i)); + assert!(near(gap(&s, i), 8.0 * 500.0), "gap {}", gap(&s, i)); + assert!(near(radius(&s, copy_of(&s, i, a)), 4.0 * 500.0), "radius {}", radius(&s, copy_of(&s, i, a))); + healthy(&s); +} diff --git a/docs/components-parity.md b/docs/components-parity.md index 9cfa2d219..ae3524a93 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -70,7 +70,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | 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 | -| Bindings: fills, strokes, effects, opacity, padding, gaps, sizes, radius, font family/style, font size/weight, line height, letter spacing, paragraph spacing/indent, text, visibility, layout grids, instance properties | done | type-checked per field, an effect's only where its effect has the field (as in effect styles); glass fields too (light angle, intensity, refraction, depth, dispersion, frost and splay, percentages as the Design panel shows them, a light angle past ±180 turned round); number variables fill text content; the Design panel's font family and font style menus start with Apply variable (string variables), and a bound one shows its variable in place of the menu; a colour variable bound to a solid paint brings its whole colour, alpha included, once (the paint's opacity restarts at 100% on binding, an opacity set while bound multiplies on top; unbinding moves the alpha back into the opacity); on a scaled instance a bound length draws at the variable's value times the instance's scale factor (#2090) | +| Bindings: fills, strokes, effects, opacity, padding, gaps, sizes, radius, font family/style, font size/weight, line height, letter spacing, paragraph spacing/indent, text, visibility, layout grids, instance properties | done | type-checked per field, an effect's only where its effect has the field (as in effect styles); glass fields too (light angle, intensity, refraction, depth, dispersion, frost and splay, percentages as the Design panel shows them, a light angle past ±180 turned round); number variables fill text content; the Design panel's font family and font style menus start with Apply variable (string variables), and a bound one shows its variable in place of the menu; a colour variable bound to a solid paint brings its whole colour, alpha included, once (the paint's opacity restarts at 100% on binding, an opacity set while bound multiplies on top; unbinding moves the alpha back into the opacity); on a scaled instance a bound length draws at the variable's value times the instance's scale factor (#2090); a scale that would take an instance past 0.001 to 1000 times is refused | | Explicit modes per frame, library collections' modes | done | stored variable and collection references resolve by exact id in export, library copies and swaps, imported aliases, alias deletion and cycle checks, Dev Inspect, the library mode picker and prototype playback; a collection or variable named like another's id no longer stands in for it there | | Explicit modes per frame and per page (Page section), library collections' modes | done | stored variable and collection references resolve by exact id in export, library copies and swaps, imported aliases, alias deletion and cycle checks, Dev Inspect, the library mode picker and prototype playback; a collection or variable named like another's id no longer stands in for it there | | Gradient stops and variant properties bound to variables | done | a stop's binding follows it when earlier stops are removed | @@ -82,7 +82,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| -| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled, and so does a scaled instance's own layer when the instance is detached (the instances inside it take its factor on). Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it, and detaching a scaled instance bakes it); the other lengths are assumed to follow, and a main component is unmeasured. Tests: `scale_bound_values_tests`. | +| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled, and so does a scaled instance's own layer when the instance is detached (the instances inside it take its factor on). Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it, and detaching a scaled instance bakes it); the other lengths are assumed to follow, and a main component is unmeasured; a scale that would take an instance past 0.001 to 1000 times is refused. Tests: `scale_bound_values_tests`. | | 2026-11-07 | minor | M3, #2082: Edit variables in the context menu of a selection of several local variables opens the reference's compact editor with two tabs: Details holds only Hide from publishing, Scope the scopes every selected variable's type has (All supported properties and one box per scope; a selection that shares none says so). Each box is checked when all selected variables have it, empty when none, and shows a dash when they differ; a click sets it on all (or clears it when checked on all), each change one `command.batch`, so one undo step. Names, descriptions and code syntax stay single-variable, as in the reference. The Scope: menu entries stay. A tri-state `widgets::checkbox_tri` draws the dash. Tests: `variables_select_tests` (headless UI). Grade unchanged | | 2026-11-12 | minor | M7, #2215: pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215). The same section the frames' Variable modes use (`variable.setMode` without layers sets the page's mode), one undo step per pick. Binding the page background to a variable is not in the reference and is not offered | | 2026-11-10 | minor | M7, #2174: a text style binds a number variable to its weight (`style.bind {field: "fontWeight"}`): the style takes the face nearest the number and sets the `wght` axis, so static and variable fonts both follow; a face-name (string) binding and a weight binding replace each other, and the weight wins in a file carrying both. The style editor's weight menu offers number variables beside string ones. A number bound to a line height is applied in pixels, as the reference tool does, which a test now pins. Numbers unchanged. Tests: `style_vars_tests`, `style_picker::tests`. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 0ef19f364..1b22668cb 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -72,7 +72,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | -| Scale tool (K): handles about an anchor, live factor, panel | done | Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured), as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`.variable-bound lengths: an instance keeps its bindings and draws them at the variable's value times its scale factor (a field of the instance, kept through rebuilds and saves); other layers keep the scaled value and drop the binding of each layer-level length scaled: size, gaps, padding, radii, stroke weights, min and max sizes and the layer's text sizes (#2090); only the gap was measured in the incumbent, the other lengths are assumed to follow it. Not yet: `.fig` import does not set the factor, so bound lengths on an imported scaled instance go back to the variable's value at its first edit; effect, layout grid and text-run bindings are neither multiplied nor dropped, so on any scaled layer they go back to the variable's value at the next bindings pass; a layer scaled inside an instance keeps its bindings, so its bound lengths stay at the variable's value (unmeasured in the incumbent); a nested instance scaled inside an instance copy loses its factor when the copy is rebuilt | +| Scale tool (K): handles about an anchor, live factor, panel | done | Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured), as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`.variable-bound lengths: an instance keeps its bindings and draws them at the variable's value times its scale factor (a field of the instance, kept through rebuilds and saves); other layers keep the scaled value and drop the binding of each layer-level length scaled: size, gaps, padding, radii, stroke weights, min and max sizes and the layer's text sizes (#2090); only the gap was measured in the incumbent, the other lengths are assumed to follow it. Not yet: `.fig` import does not set the factor, so bound lengths on an imported scaled instance go back to the variable's value at its first edit; effect, layout grid and text-run bindings are neither multiplied nor dropped, so on any scaled layer they go back to the variable's value at the next bindings pass; a layer scaled inside an instance keeps its bindings, so its bound lengths stay at the variable's value (unmeasured in the incumbent); a nested instance scaled inside an instance copy loses its factor when the copy is rebuilt; a scale that would take an instance past 0.001 to 1000 times is refused | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; thresholds not yet compared with Figma's (`guide_snap_tests`) | | Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing | @@ -215,7 +215,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| -| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled, and so does a scaled instance's own layer when the instance is detached (the instances inside it take its factor on). Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it, and detaching a scaled instance bakes it); the other lengths are assumed to follow, and a main component is unmeasured. Tests: `scale_bound_values_tests`. | +| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled, and so does a scaled instance's own layer when the instance is detached (the instances inside it take its factor on). Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it, and detaching a scaled instance bakes it); the other lengths are assumed to follow, and a main component is unmeasured; a scale that would take an instance past 0.001 to 1000 times is refused. Tests: `scale_bound_values_tests`. | | 2026-11-12 | patch | M8: Tab while renaming the last layer in the Layers panel commits and opens the first row's rename, as measured in Figma's web app on 2026-11-12 (it ended the rename before); Shift+Tab on the first row is unchanged, not measured; Tab and Shift+Tab now move only the rename and leave the selection on the layer first renamed, as measured in Figma's web app on 2026-11-12 (it followed the rename before) (`tab_on_the_last_row_commits_and_wraps_to_the_first`, `tab_while_renaming_leaves_the_selection_on_the_first_layer`), Rename row | | 2026-11-09 | patch | M3, #2156: the text caret takes the text's solid fill colour (red text, red caret; light grey on a dark frame, light grey, one colour and no inversion), measured in Figma's web app: the fill of the character before the caret (the first one's at the start); FigCraft draws it opaque (how Figma treats a translucent fill was not measured); gradient, image and hidden fills (not measured) give a black caret on a light surface and a white one on a dark one (the nearest layer around the text whose top visible fill is a solid at least half opaque as drawn, counting layer opacity, else the page; a layer whose top fill is a gradient or an image is passed over), not the interface's text colour (white in the dark theme, invisible on the default light page, #2190). Width and height unchanged; collaborators' carets unchanged. Tests: `caret_tests` | | 2026-11-10 | minor | The Rotation field shows and sets the layer's rotation on the page (its own angle plus its parents' when no ancestor is flipped; with a flipped ancestor FigCraft reads the composed angle, which flips the sign of the layer's own angle, and Figma's behaviour there was not measured), in frames and groups alike, as measured in Figma's web app for rotated, unflipped parents (#2196) | From 254766471d6c16f6ddbc4f50a5c844a99f1f28a7 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 23:45:13 -0500 Subject: [PATCH 018/114] M8: a scale by one keeps a plain layer's length bindings (#2090) A Scale tool drag back to where it started restores its snapshot and scales by exactly one, which changes no length, but scale_node still dropped the plain layers' length bindings. A scale by one now returns before touching anything. Test: scale_bound_values_tests::a_scale_by_one_keeps_a_plain_frames_bindings (failed before: the gap binding was gone). Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- crates/engine/src/cmd/arrange.rs | 5 +++++ crates/engine/src/scale_bound_values_tests.rs | 12 ++++++++++++ 2 files changed, 17 insertions(+) diff --git a/crates/engine/src/cmd/arrange.rs b/crates/engine/src/cmd/arrange.rs index 57ed10a50..92c890094 100644 --- a/crates/engine/src/cmd/arrange.rs +++ b/crates/engine/src/cmd/arrange.rs @@ -456,6 +456,11 @@ pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { if !scale_fits(doc, id, k) { return Err(scale_range_error()); } + // A scale by one changes no length, so it keeps every binding: a Scale tool drag back to where it + // started scales by exactly one, and must not unbind the lengths it never changed. + if (k - 1.0).abs() <= f64::EPSILON { + return Ok(()); + } let sub = doc.subtree(id); // The layers below `id` scale whatever their constraints, so where they are layers of an // instance their new size and place are overrides. The edit's own diff takes geometry that diff --git a/crates/engine/src/scale_bound_values_tests.rs b/crates/engine/src/scale_bound_values_tests.rs index c6e7244cf..b408e5ec6 100644 --- a/crates/engine/src/scale_bound_values_tests.rs +++ b/crates/engine/src/scale_bound_values_tests.rs @@ -116,6 +116,18 @@ fn a_file_with_a_scaled_instance_keeps_its_factor_and_bound_gap_after_save_and_o healthy(&back); } +#[test] +fn a_scale_by_one_keeps_a_plain_frames_bindings() { + // A Scale tool drag back to where it started scales by exactly one: no length changes, so no + // binding is dropped. + let mut s = Session::new(); + let (f, a) = bound_row(&mut s); + ex(&mut s, "transform.scale", json!({"ids": [f], "factor": 1})); + assert!(node(&s, f).bound.contains_key("gap"), "{:?}", node(&s, f).bound); + assert!(node(&s, a).bound.contains_key("cornerRadius"), "{:?}", node(&s, a).bound); + healthy(&s); +} + #[test] fn scaling_a_plain_frame_bakes_its_bound_gap_and_drops_the_binding() { let mut s = Session::new(); From a7fd34288d612dadfe8d460367eb61345d77752e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 00:04:29 -0500 Subject: [PATCH 019/114] Presenter: a still view keeps its detail at fractional scales, tested end to end (#2127) The rounding overshoot fixed in 6d4df2b9, through the presenter's own frames rather than a direct call: a tall frame presented fit-to-width at eleven fractional widths, and a still view keeps its detail texture for four more frames. Before 6d4df2b9 it failed at width 1555.5 (a new texture on every frame). Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- crates/ui-egui/src/present/tests.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/ui-egui/src/present/tests.rs b/crates/ui-egui/src/present/tests.rs index 2cb710923..61edc5bf8 100644 --- a/crates/ui-egui/src/present/tests.rs +++ b/crates/ui-egui/src/present/tests.rs @@ -527,6 +527,29 @@ fn a_view_a_rounding_error_past_the_frame_keeps_its_detail() { assert_eq!(again, first, "the same view reuses its detail instead of rendering a new one"); } +#[test] +fn a_still_view_keeps_its_detail_at_fractional_scales() { + // Frame widths that give fractional fit-width scales: the view's page rect then comes back + // from the screen with rounding, a hair past the frame's edge. + let mut with_detail = 0; + for w in [1001.3, 1111.1, 1234.5, 1337.7, 1440.9, 1555.5, 1666.6, 1777.7, 1888.8, 1999.9, 2345.6] { + let mut session = figcraft_engine::Session::new(); + let frame = id(&session.execute("node.create", &json!({"type": "frame", "width": w, "height": 9701})).unwrap()); + session.execute("node.create", &json!({"type": "rectangle", "parent": frame, "x": 100, "y": 100, "width": 300, "height": 200})).unwrap(); + let mut ui = Ui::new(session); + ui.hidpi = Some((2.0, 16_384)); + ui.run("proto.present", json!({"start": frame})); + ui.app.ui.present.as_mut().unwrap().view.scale = PresentScale::FitWidth; + ui.frames(2, Vec::new); + let tex_id = |ui: &Ui| ui.app.ui.present.as_ref().and_then(|p| p.detail.as_ref().map(|(_, d)| d.tex.id())); + let Some(first) = tex_id(&ui) else { continue }; + with_detail += 1; + ui.frames(4, Vec::new); + assert_eq!(tex_id(&ui), Some(first), "width {w}: a still view keeps its detail"); + } + assert!(with_detail >= 3, "most of these widths need a detail texture: {with_detail}"); +} + #[test] fn detail_plan_edge_cases() { use figcraft_geom::Rect as R; From 258bf152573bb5e8a52b7dc152a5063b6da7da05 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 14:50:23 -0500 Subject: [PATCH 020/114] Docs: drop the old Scale tool row main already removed, keeping main's Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- docs/ui-parity.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 231793714..f78306190 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -74,7 +74,6 @@ interaction feel only partly compared: the interactions measured so far, case by | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers); Alt going down or up mid-drag turns the move into a copy or back to the original, with Shift a copy kept to one axis (`alt_pressed_during_a_drag_turns_the_move_into_a_copy`, `alt_shift_drag_on_a_selected_layer_duplicates_it`; measured in Figma's web app, 2026-11-08) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | | A dragged layer moves with its outline | partial | #2033: the canvas image is the last render the worker finished, so a drag's content trailed its outline by a render per pointer move (63 ms, about 3.6 frames, and 150 px on screen with drop shadows on 200 layers). While a gesture only translates plain layers (Normal or pass-through blend, no effects on them or above them, not masks, not in a boolean group or beside a mask, no ancestor under 100 percent opacity; their own children may have effects) the layers are rendered once into a texture of their own (the sprite), the base is rendered once without them from the document the drag started from and then asks for no more renders, and the sprite is drawn each frame at the same shifted place as the selection outline. On release, Escape or a zoom change the document is rendered whole again and the sprite stays until that image is shown. Desktop only (the browser renders in the same frame). Trade-offs while dragging: the sprite draws above everything (z-order is lost), blends and backdrop blurs against what is behind are approximated, ancestors' clips are applied as their bounding boxes, and a sprite wider than the texture limit or over four canvases of pixels, outline and focus views, pixel preview and soft proof keep the old way (`canvas/drag_sprite.rs`) | -| Scale tool (K): handles about an anchor, live factor, panel | done | Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured), as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`. | | Scale tool (K): handles about the opposite handle, live factor, panel | done | Dragging a handle ignores the origin grid and pivots on the opposite handle's point (the opposite corner, or the opposite edge's middle for an edge, which scales both ways), with Alt on the centre; the origin grid (`tool.scaleAnchor`) starts at the centre and sets only what the Scale field and the W and H fields keep fixed (W and H with a non-centre origin are unmeasured). Measured in Figma's web app, 2026-11-09. Tests: `a_scale_handle_drag_pivots_on_the_opposite_handle_whatever_the_origin`, `the_scale_origin_starts_at_the_centre`. Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin, which starts at the centre, as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`. | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; the object snap threshold is 4.5 screen pixels, measured against Figma (snapped at a gap of 4.4 screen px, not at 4.6, at 100% and 200% zoom, 2026-11-08; the equal-spacing snap shares it), but the ruler-guide and rotation-origin thresholds (5 px), the red guide's look and snapping with Snap to pixel grid off are not yet compared with Figma's (`guide_snap_tests`, `transform_behaviour_tests`) | From 148ab21e28b8920ec834532a5602f48690c52562 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 14:50:34 -0500 Subject: [PATCH 021/114] Docs: drop the old Scale tool row main already removed, keeping main's Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- docs/ui-parity.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index a9c2868f3..c3aa74496 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -73,7 +73,6 @@ interaction feel only partly compared: the interactions measured so far, case by | Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers); Alt going down or up mid-drag turns the move into a copy or back to the original, with Shift a copy kept to one axis (`alt_pressed_during_a_drag_turns_the_move_into_a_copy`, `alt_shift_drag_on_a_selected_layer_duplicates_it`; measured in Figma's web app, 2026-11-08) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | -| Scale tool (K): handles about an anchor, live factor, panel | done | Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured), as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`.variable-bound lengths: an instance keeps its bindings and draws them at the variable's value times its scale factor (a field of the instance, kept through rebuilds and saves); other layers keep the scaled value and drop the binding of each layer-level length scaled: size, gaps, padding, radii, stroke weights, min and max sizes and the layer's text sizes (#2090); only the gap was measured in the incumbent, the other lengths are assumed to follow it. Not yet: `.fig` import does not set the factor, so bound lengths on an imported scaled instance go back to the variable's value at its first edit; effect, layout grid and text-run bindings are neither multiplied nor dropped, so on any scaled layer they go back to the variable's value at the next bindings pass; a layer scaled inside an instance keeps its bindings, so its bound lengths stay at the variable's value (unmeasured in the incumbent); a nested instance scaled inside an instance copy loses its factor when the copy is rebuilt; a scale that would take an instance past 0.001 to 1000 times is refused | | Scale tool (K): handles about the opposite handle, live factor, panel | done | Dragging a handle ignores the origin grid and pivots on the opposite handle's point (the opposite corner, or the opposite edge's middle for an edge, which scales both ways), with Alt on the centre; the origin grid (`tool.scaleAnchor`) starts at the centre and sets only what the Scale field and the W and H fields keep fixed (W and H with a non-centre origin are unmeasured). Measured in Figma's web app, 2026-11-09. Tests: `a_scale_handle_drag_pivots_on_the_opposite_handle_whatever_the_origin`, `the_scale_origin_starts_at_the_centre`. Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin, which starts at the centre, as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`. | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; the object snap threshold is 4.5 screen pixels, measured against Figma (snapped at a gap of 4.4 screen px, not at 4.6, at 100% and 200% zoom, 2026-11-08; the equal-spacing snap shares it), but the ruler-guide and rotation-origin thresholds (5 px), the red guide's look and snapping with Snap to pixel grid off are not yet compared with Figma's (`guide_snap_tests`, `transform_behaviour_tests`) | From d5018e736e727c93ed956187a5efe4e201d99443 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 15 Nov 2026 11:41:29 -0500 Subject: [PATCH 022/114] M5: while the view moves, the presenter's detail is drawn only while it covers the view (#2133 review) Past the detail's edge the capped whole-frame texture is drawn alone until the view settles, and then a detail for the new view is rendered, so no sharp/soft boundary crosses the view while it pans. The presenter row and the #2127 revision note describe the fallback. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 driver, no subagent --- crates/ui-egui/src/present/actions.rs | 5 +++-- crates/ui-egui/src/present/tests.rs | 31 +++++++++++++++++++++++++++ docs/prototyping-parity.md | 4 ++-- docs/target-app-parity.md | 2 +- 4 files changed, 37 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/present/actions.rs b/crates/ui-egui/src/present/actions.rs index d3386da0a..bb1ca5c25 100644 --- a/crates/ui-egui/src/present/actions.rs +++ b/crates/ui-egui/src/present/actions.rs @@ -269,7 +269,8 @@ impl Presenter { /// The part of the frame `id` (its whole texture covering `whole`, page units) in view /// (`visible`) at the full pixel scale `px`, for a frame whose whole texture is capped below it /// (see [`detail_plan`]). While the view moves (`moving`) it only returns a detail already - /// rendered, the capped texture showing under it. + /// rendered, and only while it covers the whole view: past it the capped texture shows alone + /// (no sharp edge across the view) until the view settles and a detail for it is rendered. pub(super) fn detail_texture( &mut self, ctx: &egui::Context, @@ -291,7 +292,7 @@ impl Presenter { if let Some((did, d)) = &self.detail && *did == id && d.key == key - && (moving || covers(&d.bounds)) + && covers(&d.bounds) { return Some(d.clone()); } diff --git a/crates/ui-egui/src/present/tests.rs b/crates/ui-egui/src/present/tests.rs index 4a6eab7df..9b4504bdb 100644 --- a/crates/ui-egui/src/present/tests.rs +++ b/crates/ui-egui/src/present/tests.rs @@ -527,6 +527,37 @@ fn a_view_a_rounding_error_past_the_frame_keeps_its_detail() { assert_eq!(again, first, "the same view reuses its detail instead of rendering a new one"); } +/// While the view moves, the detail is drawn only while it covers the whole view: past its edge +/// the capped whole-frame texture shows alone, so no sharp/soft boundary crosses the view, and +/// once the view settles a detail for it is rendered. +#[test] +fn a_moving_view_past_its_detail_shows_the_capped_frame_alone_until_it_settles() { + use figcraft_geom::Rect as R; + let mut ui = tall_hidpi(16_384); + let ctx = ui.ctx.clone(); + let doc = ui.app.session.doc().unwrap().clone(); + let now = ui.time; + let p = ui.app.ui.present.as_mut().unwrap(); + let id = p.current; + let whole = R::new(0.0, 0.0, 1440.0, 9701.0); + let covers = |b: R, v: R| b.x0 <= v.x0 && b.y0 <= v.y0 && b.x1 >= v.x1 && b.y1 >= v.y1; + let first = p.detail_texture(&ctx, &doc, id, 2.0, whole, R::new(0.0, 0.0, 1440.0, 860.0), false, now).expect("a detail"); + // Moving within the detail's margin: it is reused. + let shift = (first.bounds.y1 - 860.0) / 2.0; + assert!(shift > 0.0, "{:?}", first.bounds); + let inside = R::new(0.0, shift, 1440.0, 860.0 + shift); + let moved = p.detail_texture(&ctx, &doc, id, 2.0, whole, inside, true, now).expect("still covered"); + assert_eq!(moved.tex.id(), first.tex.id()); + // Moving past its edge: no detail, the capped texture shows alone. + let past = R::new(0.0, first.bounds.y1 - 430.0, 1440.0, first.bounds.y1 + 430.0); + assert!(!covers(first.bounds, past)); + assert!(p.detail_texture(&ctx, &doc, id, 2.0, whole, past, true, now).is_none(), "the old detail is not drawn over part of the view"); + // Settled there: a new detail for that view. + let settled = p.detail_texture(&ctx, &doc, id, 2.0, whole, past, false, now).expect("a new detail"); + assert_ne!(settled.tex.id(), first.tex.id()); + assert!(covers(settled.bounds, past), "{:?} covers {past:?}", settled.bounds); +} + #[test] fn a_still_view_keeps_its_detail_at_fractional_scales() { // Frame widths that give fractional fit-width scales: the view's page rect then comes back diff --git a/docs/prototyping-parity.md b/docs/prototyping-parity.md index af062cd1f..6863a4c7d 100644 --- a/docs/prototyping-parity.md +++ b/docs/prototyping-parity.md @@ -92,7 +92,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Widgets react to clicks in a presented prototype | done | clicks only, like on the canvas | | Interactive components: instances play their variant's interactions, overridden per trigger | done | | | Drag-driven animations that follow the pointer, in their direction | done | | -| Presenter: device frames and colours, rotation, custom sizes, fit/fill/100%, responsive frames | done | device bodies drawn in code. Presenting opens a tab for the page, named "file - page", which keeps its screen and history while you go back to the design, with a thumbnail of the current frame, previous / next, device presets and scale choices; the frame is laid out again for the device's screen on the prototype's copy (constraints and auto layout; the file is untouched); on phones and tablets overflowing content drags while the device stays put: a top-level frame bigger than the screen always scrolls (as in Figma, with no overflow setting), content past the frame's own edges as its overflow setting allows ("No scrolling" clips it); closing the window asks about unsaved changes above the presentation (#537); a frame too big for one texture at device scale (taller than about 2900 units at 1440 wide on a 2x display) shows the part in view from a second texture at device scale over the capped whole-frame one, drawn again when it stops covering the view and not while the view moves (#2127). Devices not compared with Figma's | +| Presenter: device frames and colours, rotation, custom sizes, fit/fill/100%, responsive frames | done | device bodies drawn in code. Presenting opens a tab for the page, named "file - page", which keeps its screen and history while you go back to the design, with a thumbnail of the current frame, previous / next, device presets and scale choices; the frame is laid out again for the device's screen on the prototype's copy (constraints and auto layout; the file is untouched); on phones and tablets overflowing content drags while the device stays put: a top-level frame bigger than the screen always scrolls (as in Figma, with no overflow setting), content past the frame's own edges as its overflow setting allows ("No scrolling" clips it); closing the window asks about unsaved changes above the presentation (#537); a frame too big for one texture at device scale (taller than about 2900 units at 1440 wide on a 2x display) shows the part in view from a second texture at device scale over the capped whole-frame one, drawn again when it stops covering the view and not while the view moves, when past it the capped texture shows alone until the view settles (#2127). Devices not compared with Figma's | | Hotspot hints, inspect panel in the presenter, comments in the presenter | done | | | Hide UI in the presenter (Options menu, Cmd/Ctrl+\) | done | the bar above the prototype and the navigation bar under it go away and the prototype takes their room; a toast names the key that brings them back; `proto.presentOptions {hideUi}`, kept for later presentations (#1820) | | Preview pane following edits live | done | | @@ -109,7 +109,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Date | Change | Summary | |---|---|---| | 2026-11-09 | patch | M7, #2158: a connection dragged from a variant (or a layer in it) onto a sibling variant of its set did nothing, because the drop looked only for top-level frames and a variant's top-level frame is its set. It now creates Change to the sibling (On click, Instant, as measured in Figma's web app) and outlines the sibling while dragging; the set's background and the variant itself still add nothing, and a frame outside the set still gets Navigate to | -| 2026-11-09 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it; transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | +| 2026-11-09 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it (while the view moves, a detail is drawn only while it covers the whole view: past it the capped texture shows alone, with no sharp edge across the view, until the view settles); transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | | 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. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 363697182..6edc89451 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -649,7 +649,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| -| 2026-11-09 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it; transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | +| 2026-11-09 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it (while the view moves, a detail is drawn only while it covers the whole view: past it the capped texture shows alone, with no sharp edge across the view, until the view settles); transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | | 2026-11-10 | minor | M4, #2222: a boolean group's corner radius rounds every sharp corner of its result (row 4). Numbers unchanged | | 2026-11-08 | minor | M8: measured in Figma on 2026-11-08, vector edit mode's Point section: X and Y show the value the selected points share, or Mixed when they differ, and a typed value sets every selected point's own coordinate in the layer being edited, points of other edited layers left as they are (it moved the group's top-left before); a relative edit (`+10`, `*2`, `/2`) typed into a Mixed field applies to each point's own value (`vector.edit.position` takes a number or `{add}`, `{mul}`, `{div}` per axis); the W and H row and other edited layers' points are unchanged. | | 2026-11-11 | patch | M4: typing a number, a full stop and a space at the start of a plain paragraph starts a numbered list at that number (`5. ` then "x", Enter, "y" reads 5. then 6.), as measured in Figma web on 2026-11-11 (it has no start-number field: the start comes only from the typed number); before, only `1. ` and `1)` started a list. `0. `, `12a. ` and a bracket after a number other than 1 stay text (not measured), and the number is capped at 9999. Also measured: a plain paragraph or a bullet item between numbered items restarts the count at 1, and an indented sub-item does not break the outer count; those rows were pinned as silent. Tests: `text_tail_tests::typed_list_starts`, `typed_number_starts_the_list_there`, `tail_tests` restart rows. Numbers unchanged | From 6d2b386b60eadb29529364fb90c6981d64b9f254 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 16 Nov 2026 04:37:46 -0500 Subject: [PATCH 023/114] docs: status lines are main's summary with this PR's entry in front The main merge kept the old summary in front of main's rewritten one; this takes main's line and puts back only the PR's own entry. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 driver, no subagent --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 327d07589..5d615175e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (; a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) -- this replaces the 2026-10-11 rule from the documentation; an exported layer with a background blur or glass keeps the blurred content behind it within its bounds (#2213); a typed number and a full stop at the start of a paragraph starts a numbered list at that number, as measured in Figma 2026-11-11; justified Chinese, Japanese and Korean text, written without spaces, spreads each line's room between its characters so its right edge aligns (#1970); joining the two ends of a path broken open by a deleted point closes it again, so its fill and selection outline follow the new segment and its corner radius instead of a straight line across the gap (#1951); glass's docs say which centre splay bends away from and where a shape gets no core; glass bends towards its core, rounded rectangles 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, measured against the reference tool; bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%; last major: full re-measure against Figma desktop 126.10.7; rows for the community batches: Selection colors, smart-selection spacing and a Present tab (#753), `.fig` import fidelity, paste from another design app, a `.fig` copy from Save as; control requests while the window is minimised (#720); catalog counts re-measured; automation roots (#715); number variables in the text content picker (#629); frames and sections convert into each other (#719)) · **Target:** Figma Design (desktop app 126.10.7, macOS); M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is From 6dace8c570d375820ece3bd4fcbf3535a2dd3efa Mon Sep 17 00:00:00 2001 From: B-uchi Date: Wed, 18 Nov 2026 08:00:03 +0100 Subject: [PATCH 024/114] M8: get_node reports text and stroke settings it stores A layer stored its vertical text alignment, text case, paragraph spacing and indent, OpenType features, start and end caps, a frame's variable modes, which component property controls a field, and whether a nested instance is exposed, but node.get and document.inspect left them out. They are reported now, under the names node.set takes so a value read can be written back, and only when they aren't the default. --- crates/engine/src/automation/inspect.rs | 40 +++++++++++++++- crates/engine/src/inspect_fields_tests.rs | 56 +++++++++++++++++++++++ docs/control-protocol.md | 3 ++ 3 files changed, 98 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/automation/inspect.rs b/crates/engine/src/automation/inspect.rs index c74829961..a3c0b94e5 100644 --- a/crates/engine/src/automation/inspect.rs +++ b/crates/engine/src/automation/inspect.rs @@ -1,6 +1,6 @@ //! Document inspection as JSON, so agents can verify their work without screenshots. -use figcraft_doc::{Document, Node, NodeId, NodeKind, StrokeJoin, TextData, TextDecoration}; +use figcraft_doc::{Document, Node, NodeId, NodeKind, StrokeCap, StrokeJoin, TextAlignV, TextCase, TextData, TextDecoration}; use serde_json::{Value, json}; use crate::Session; @@ -34,7 +34,10 @@ pub const NODE_KEYS: &[&str] = &[ "devResources", "devStatus", "effects", + "endCap", "exports", + "exposedInstance", + "features", "fills", "flows", "fontFamily", @@ -76,13 +79,17 @@ pub const NODE_KEYS: &[&str] = &[ "opacity", "operandOperation", "overrides", + "paragraphIndent", + "paragraphSpacing", "pluginData", "pointCount", + "propertyReferences", "rotation", "sectionContentsHidden", "segments", "sizing", "slot", + "startCap", "strokeAlign", "strokeJoin", "strokeSides", @@ -91,7 +98,9 @@ pub const NODE_KEYS: &[&str] = &[ "styledRuns", "styles", "textAlign", + "textAlignVertical", "textAutoResize", + "textCase", "textDecoration", "textDecorationColor", "textDecorationOffset", @@ -102,6 +111,7 @@ pub const NODE_KEYS: &[&str] = &[ "textPath", "textStyleRanges", "type", + "variableModes", "vertices", "visible", "width", @@ -263,6 +273,11 @@ fn paint_props(n: &Node, o: &mut serde_json::Map, options: &Inspe if !n.stroke.dashes.is_empty() { insert_prop(o, options, "dashes", || json!(n.stroke.dashes)); } + for (k, cap) in [("startCap", n.stroke.cap_start), ("endCap", n.stroke.cap_end)] { + if cap != StrokeCap::None { + insert_prop(o, options, k, || json!(cap)); + } + } if let Some(cap) = n.stroke.dash_cap { insert_prop(o, options, "dashCap", || json!(cap)); } @@ -383,6 +398,15 @@ fn dev_props(doc: &Document, n: &Node, o: &mut serde_json::Map, o if !n.bound.is_empty() { insert_prop(o, options, "boundVariables", || json!(n.bound)); } + if !n.var_modes.is_empty() { + insert_prop(o, options, "variableModes", || json!(n.var_modes)); + } + if !n.prop_refs.is_empty() { + insert_prop(o, options, "propertyReferences", || json!(n.prop_refs)); + } + if n.exposed { + insert_prop(o, options, "exposedInstance", || json!(true)); + } if !n.overrides.is_empty() { insert_prop(o, options, "overrides", || json!(n.overrides)); } @@ -417,7 +441,21 @@ fn text_props(t: &TextData, o: &mut serde_json::Map, options: &In insert_prop(o, options, "lineHeight", || json!(t.style.line_height.label())); insert_prop(o, options, "letterSpacing", || json!(t.style.letter_spacing.label())); insert_prop(o, options, "textAlign", || json!(t.align_h)); + if t.align_v != TextAlignV::default() { + insert_prop(o, options, "textAlignVertical", || json!(t.align_v)); + } insert_prop(o, options, "textAutoResize", || json!(t.auto_resize)); + if t.style.case != TextCase::default() { + insert_prop(o, options, "textCase", || json!(t.style.case)); + } + for (k, v) in [("paragraphSpacing", t.paragraph_spacing), ("paragraphIndent", t.paragraph_indent)] { + if v != 0.0 { + insert_prop(o, options, k, || json!(v)); + } + } + if !t.features.is_empty() { + insert_prop(o, options, "features", || json!(t.features)); + } if t.max_lines > 0 { insert_prop(o, options, "maxLines", || json!(t.max_lines)); } diff --git a/crates/engine/src/inspect_fields_tests.rs b/crates/engine/src/inspect_fields_tests.rs index 2083a5108..592ca8b94 100644 --- a/crates/engine/src/inspect_fields_tests.rs +++ b/crates/engine/src/inspect_fields_tests.rs @@ -505,3 +505,59 @@ fn node_get_uses_options_but_keeps_its_existing_depth_and_selection() { assert_eq!(s.selection(), selection); assert_eq!(s.undo_depth(), history); } + +/// Text and stroke settings a layer stores are reported, under the names `node.set` takes, so a +/// value read can be written back unchanged. +#[test] +fn stored_text_and_stroke_settings_are_read_back_as_set() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text = s.execute("node.create", &json!({"type": "text", "text": "Hi", "width": 120})).unwrap()["id"].clone(); + let line = + s.execute("node.create", &json!({"type": "line", "width": 80, "props": {"strokes": ["#000000"], "strokeWeight": 2}})).unwrap()["id"].clone(); + let set = json!({ + "textAlignVertical": "middle", "textCase": "upper", "paragraphSpacing": 8.0, "paragraphIndent": 12.0, "features": {"liga": false}, + }); + s.execute("node.set", &json!({"ids": [text.clone()], "props": set})).unwrap(); + s.execute("node.set", &json!({"ids": [line.clone()], "props": {"startCap": "round", "endCap": "triangleArrow"}})).unwrap(); + let got = s.execute("node.get", &json!({"id": text})).unwrap(); + for (key, value) in set.as_object().unwrap() { + assert_eq!(&got[key], value, "{key}: {got}"); + // Written back as read, it changes nothing. + s.execute("node.set", &json!({"ids": [text.clone()], "props": {key.as_str(): got[key].clone()}})).unwrap(); + assert_eq!(s.execute("node.get", &json!({"id": text})).unwrap()[key], *value, "{key}"); + } + let got = s.execute("node.get", &json!({"id": line})).unwrap(); + assert_eq!((got["startCap"].as_str(), got["endCap"].as_str()), (Some("round"), Some("triangleArrow")), "{got}"); + // Defaults stay out, as they do for other keys. + let plain = s.execute("node.create", &json!({"type": "text", "text": "x"})).unwrap()["id"].clone(); + let got = s.execute("node.get", &json!({"id": plain})).unwrap(); + for key in ["textAlignVertical", "textCase", "paragraphSpacing", "paragraphIndent", "features", "startCap", "endCap", "variableModes"] { + assert!(got.get(key).is_none(), "{key} at its default: {got}"); + } +} + +/// A frame's variable modes, a layer's component property bindings and an exposed nested instance +/// are reported. +#[test] +fn modes_property_bindings_and_exposed_instances_are_read() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let c = s.execute("variable.createCollection", &json!({"name": "Theme", "modes": ["Light", "Dark"]})).unwrap(); + let frame = s.execute("node.create", &json!({"type": "frame", "width": 100, "height": 100})).unwrap()["id"].clone(); + s.execute("variable.setMode", &json!({"ids": [frame.clone()], "collection": c["id"], "mode": "Dark"})).unwrap(); + let modes = s.execute("node.get", &json!({"id": frame})).unwrap()["variableModes"].clone(); + assert_eq!(modes.as_object().map(|m| m.len()), Some(1), "{modes}"); + let card = s.execute("node.create", &json!({"type": "frame", "name": "Card", "width": 100, "height": 50})).unwrap()["id"].clone(); + let title = s.execute("node.create", &json!({"type": "text", "parent": card.clone(), "text": "Title"})).unwrap()["id"].clone(); + let main = s.execute("component.create", &json!({"ids": [card]})).unwrap()["id"].clone(); + s.execute("component.addProperty", &json!({"id": main.clone(), "name": "Label", "type": "text", "layer": title.clone()})).unwrap(); + let refs = s.execute("node.get", &json!({"id": title})).unwrap()["propertyReferences"].clone(); + assert!(refs.as_object().is_some_and(|r| r.values().any(|v| v.as_str().is_some_and(|p| p.starts_with("Label")))), "{refs}"); + let tag = s.execute("node.create", &json!({"type": "frame", "name": "Tag", "x": 300, "width": 40, "height": 20})).unwrap()["id"].clone(); + let tag_main = s.execute("component.create", &json!({"ids": [tag]})).unwrap()["id"].clone(); + let nested = s.execute("instance.create", &json!({"component": tag_main})).unwrap()["id"].clone(); + s.execute("node.reparent", &json!({"ids": [nested.clone()], "parent": main})).unwrap(); + s.execute("component.exposeInstance", &json!({"id": nested.clone()})).unwrap(); + assert_eq!(s.execute("node.get", &json!({"id": nested})).unwrap()["exposedInstance"], true); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 381992c55..325b67b24 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -195,6 +195,9 @@ layout (including grid `columnTracks` / `rowTracks`), sizing, `minWidth` / `maxW children), `gridCell` (a grid auto layout child's column, row and spans), clip, text properties, component/instance links, overrides, `slot` (a slot layer's property name), boundVariables, interactions, exports, `devStatus` (handoff status), `devChanged` (changed since it was marked ready for dev), +`textAlignVertical`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `features` (OpenType +toggles), `startCap` and `endCap` (when not none), `variableModes` (a frame's collection → mode), +`propertyReferences` (which component property controls a field), `exposedInstance`, `annotations` (Developer Mode notes: `[{label, properties, category?}]`), `codeLinks` (a component's links to code: `[{language, importPath, name, template}]`), `devResources` (links for developers, its own and inherited: `[{name, url, index?, from?}]`), `measurements` (Developer Mode measurements From d332c18a2c166f5d6ed6c1bf52370c8315d2c282 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 18 Nov 2026 15:44:42 +0500 Subject: [PATCH 025/114] REST import: variables bound to stroke sides bind each side's weight (#2441) boundVariables.individualStrokeWeights was skipped with a warning, so a 1 px bottom divider bound to a variable came across as a plain number. Each side now binds strokeTopWeight ... strokeLeftWeight, read from the live API's BORDER_TOP_WEIGHT ... keys or the published spec's top ... keys. --- .../format/src/rest/proto_variable_tests.rs | 38 +++++++++++++++++++ crates/format/src/rest/variables.rs | 13 +++++++ 2 files changed, 51 insertions(+) diff --git a/crates/format/src/rest/proto_variable_tests.rs b/crates/format/src/rest/proto_variable_tests.rs index 133d45de2..3c89d8a41 100644 --- a/crates/format/src/rest/proto_variable_tests.rs +++ b/crates/format/src/rest/proto_variable_tests.rs @@ -188,6 +188,44 @@ fn bound_variables_and_explicit_modes() { assert!(has(&warnings, "pass the local variables JSON"), "{warnings:?}"); } +/// #2441: a variable bound to one or more stroke sides (`individualStrokeWeights`) binds that +/// side's weight. The live API names the sides `BORDER_TOP_WEIGHT` …, the published spec `top` …; +/// both are read, and neither is reported as skipped. +#[test] +fn variables_bound_to_stroke_sides_bind_each_sides_weight() { + let rect = |id: &str, name: &str, sides: Value| { + json!({"id": id, "name": name, "type": "RECTANGLE", "relativeTransform": at(0.0, 0.0), "size": {"x": 40, "y": 20}, + "strokes": [{"type": "SOLID", "color": rgba(0.0, 0.0, 0.0)}], "strokeWeight": 1, + "individualStrokeWeights": {"top": 1, "right": 1, "bottom": 1, "left": 1}, + "boundVariables": {"individualStrokeWeights": sides}}) + }; + let file = json!({"name": "Sides", "document": {"id": "0:0", "type": "DOCUMENT", "children": [ + {"id": "0:1", "name": "Page", "type": "CANVAS", "children": [ + rect("1:1", "Row", json!({"BORDER_BOTTOM_WEIGHT": alias(SPACE)})), + rect("1:2", "Card", json!({"BORDER_TOP_WEIGHT": alias(SPACE), "BORDER_RIGHT_WEIGHT": alias(SPACE), + "BORDER_BOTTOM_WEIGHT": alias(SPACE), "BORDER_LEFT_WEIGHT": alias(SPACE)})), + rect("1:3", "Spec", json!({"top": alias(SPACE), "left": alias(SPACE)})), + rect("1:4", "Colour", json!({"BORDER_LEFT_WEIGHT": alias(BRAND)})) + ]} + ]}}); + let (doc, warnings) = import_with(&file, Some(&variables_json()), &no_images).unwrap(); + let sides = |name: &str| -> Vec<(String, String)> { + let n = named(&doc, name); + ["strokeTopWeight", "strokeRightWeight", "strokeBottomWeight", "strokeLeftWeight"] + .iter() + .filter_map(|f| n.bound.get(*f).map(|v| (f.to_string(), v.clone()))) + .collect() + }; + let b = |f: &str| (f.to_string(), SPACE.to_string()); + assert_eq!(sides("Row"), [b("strokeBottomWeight")], "one side bound"); + assert_eq!(sides("Card"), [b("strokeTopWeight"), b("strokeRightWeight"), b("strokeBottomWeight"), b("strokeLeftWeight")]); + assert_eq!(sides("Spec"), [b("strokeTopWeight"), b("strokeLeftWeight")], "the spec's names"); + assert_eq!(sides("Colour"), [], "a colour variable can't be a weight"); + assert!(!has(&warnings, "`individualStrokeWeights`"), "{warnings:?}"); + assert!(has(&warnings, "type doesn't fit"), "{warnings:?}"); + assert!(doc.validate().is_empty(), "{:?}", doc.validate()); +} + #[test] fn embedded_variables_match_separate_ones() { let mut embedded = file_json(); diff --git a/crates/format/src/rest/variables.rs b/crates/format/src/rest/variables.rs index ba2467423..a962ded0f 100644 --- a/crates/format/src/rest/variables.rs +++ b/crates/format/src/rest/variables.rs @@ -427,6 +427,19 @@ fn node_binding<'v>(k: &str, v: &'v Value, n: &Node, out: &mut Vec<(String, &'v push(f, v.get(key).and_then(alias)); } } + // Each stroke side's weight (#2441). The live `/nodes` response names the sides + // `BORDER_TOP_WEIGHT` and so on, as `rectangleCornerRadii` names its corners; Figma's + // published OpenAPI spec names them `top` … `left`. Either is read. + "individualStrokeWeights" => { + for (keys, f) in [ + (["BORDER_TOP_WEIGHT", "top"], "strokeTopWeight"), + (["BORDER_RIGHT_WEIGHT", "right"], "strokeRightWeight"), + (["BORDER_BOTTOM_WEIGHT", "bottom"], "strokeBottomWeight"), + (["BORDER_LEFT_WEIGHT", "left"], "strokeLeftWeight"), + ] { + push(f, keys.iter().find_map(|key| v.get(*key)).and_then(alias)); + } + } "fills" | "strokes" => { let field = if k == "fills" { "fill" } else { "stroke" }; match v.as_array().and_then(|a| a.first()).and_then(alias) { From d7fcbf94caf24325f748c8e19838e17b1b2e4beb Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 18 Nov 2026 15:57:39 +0500 Subject: [PATCH 026/114] REST import test: each of Card's sides is bound to a variable of its own So a side read into another side's field fails the test (review). --- .../format/src/rest/proto_variable_tests.rs | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/crates/format/src/rest/proto_variable_tests.rs b/crates/format/src/rest/proto_variable_tests.rs index 3c89d8a41..e54a4fbf7 100644 --- a/crates/format/src/rest/proto_variable_tests.rs +++ b/crates/format/src/rest/proto_variable_tests.rs @@ -193,6 +193,10 @@ fn bound_variables_and_explicit_modes() { /// both are read, and neither is reported as skipped. #[test] fn variables_bound_to_stroke_sides_bind_each_sides_weight() { + const TOP: &str = "VariableID:9:1"; + const RIGHT: &str = "VariableID:9:2"; + const BOTTOM: &str = "VariableID:9:3"; + const LEFT: &str = "VariableID:9:4"; let rect = |id: &str, name: &str, sides: Value| { json!({"id": id, "name": name, "type": "RECTANGLE", "relativeTransform": at(0.0, 0.0), "size": {"x": 40, "y": 20}, "strokes": [{"type": "SOLID", "color": rgba(0.0, 0.0, 0.0)}], "strokeWeight": 1, @@ -202,13 +206,19 @@ fn variables_bound_to_stroke_sides_bind_each_sides_weight() { let file = json!({"name": "Sides", "document": {"id": "0:0", "type": "DOCUMENT", "children": [ {"id": "0:1", "name": "Page", "type": "CANVAS", "children": [ rect("1:1", "Row", json!({"BORDER_BOTTOM_WEIGHT": alias(SPACE)})), - rect("1:2", "Card", json!({"BORDER_TOP_WEIGHT": alias(SPACE), "BORDER_RIGHT_WEIGHT": alias(SPACE), - "BORDER_BOTTOM_WEIGHT": alias(SPACE), "BORDER_LEFT_WEIGHT": alias(SPACE)})), + rect("1:2", "Card", json!({"BORDER_TOP_WEIGHT": alias(TOP), "BORDER_RIGHT_WEIGHT": alias(RIGHT), + "BORDER_BOTTOM_WEIGHT": alias(BOTTOM), "BORDER_LEFT_WEIGHT": alias(LEFT)})), rect("1:3", "Spec", json!({"top": alias(SPACE), "left": alias(SPACE)})), rect("1:4", "Colour", json!({"BORDER_LEFT_WEIGHT": alias(BRAND)})) ]} ]}}); - let (doc, warnings) = import_with(&file, Some(&variables_json()), &no_images).unwrap(); + // A variable of its own for each of Card's sides, so a side read into another's field fails. + let mut vars = variables_json(); + for id in [TOP, RIGHT, BOTTOM, LEFT] { + vars["meta"]["variables"][id] = json!({"id": id, "name": id, "variableCollectionId": THEME, "resolvedType": "FLOAT", + "valuesByMode": {"1:0": 1}, "scopes": ["ALL_SCOPES"]}); + } + let (doc, warnings) = import_with(&file, Some(&vars), &no_images).unwrap(); let sides = |name: &str| -> Vec<(String, String)> { let n = named(&doc, name); ["strokeTopWeight", "strokeRightWeight", "strokeBottomWeight", "strokeLeftWeight"] @@ -217,8 +227,12 @@ fn variables_bound_to_stroke_sides_bind_each_sides_weight() { .collect() }; let b = |f: &str| (f.to_string(), SPACE.to_string()); + let on = |f: &str, v: &str| (f.to_string(), v.to_string()); assert_eq!(sides("Row"), [b("strokeBottomWeight")], "one side bound"); - assert_eq!(sides("Card"), [b("strokeTopWeight"), b("strokeRightWeight"), b("strokeBottomWeight"), b("strokeLeftWeight")]); + assert_eq!( + sides("Card"), + [on("strokeTopWeight", TOP), on("strokeRightWeight", RIGHT), on("strokeBottomWeight", BOTTOM), on("strokeLeftWeight", LEFT)] + ); assert_eq!(sides("Spec"), [b("strokeTopWeight"), b("strokeLeftWeight")], "the spec's names"); assert_eq!(sides("Colour"), [], "a colour variable can't be a weight"); assert!(!has(&warnings, "`individualStrokeWeights`"), "{warnings:?}"); From 11b896699f0d5fa6fcd3e56068211e7b6afcf107 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 18 Nov 2026 16:24:41 +0500 Subject: [PATCH 027/114] REST import test: the spec's four side names each bind a variable of their own --- crates/format/src/rest/proto_variable_tests.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/format/src/rest/proto_variable_tests.rs b/crates/format/src/rest/proto_variable_tests.rs index e54a4fbf7..f89466194 100644 --- a/crates/format/src/rest/proto_variable_tests.rs +++ b/crates/format/src/rest/proto_variable_tests.rs @@ -208,7 +208,7 @@ fn variables_bound_to_stroke_sides_bind_each_sides_weight() { rect("1:1", "Row", json!({"BORDER_BOTTOM_WEIGHT": alias(SPACE)})), rect("1:2", "Card", json!({"BORDER_TOP_WEIGHT": alias(TOP), "BORDER_RIGHT_WEIGHT": alias(RIGHT), "BORDER_BOTTOM_WEIGHT": alias(BOTTOM), "BORDER_LEFT_WEIGHT": alias(LEFT)})), - rect("1:3", "Spec", json!({"top": alias(SPACE), "left": alias(SPACE)})), + rect("1:3", "Spec", json!({"top": alias(TOP), "right": alias(RIGHT), "bottom": alias(BOTTOM), "left": alias(LEFT)})), rect("1:4", "Colour", json!({"BORDER_LEFT_WEIGHT": alias(BRAND)})) ]} ]}}); @@ -233,7 +233,11 @@ fn variables_bound_to_stroke_sides_bind_each_sides_weight() { sides("Card"), [on("strokeTopWeight", TOP), on("strokeRightWeight", RIGHT), on("strokeBottomWeight", BOTTOM), on("strokeLeftWeight", LEFT)] ); - assert_eq!(sides("Spec"), [b("strokeTopWeight"), b("strokeLeftWeight")], "the spec's names"); + assert_eq!( + sides("Spec"), + [on("strokeTopWeight", TOP), on("strokeRightWeight", RIGHT), on("strokeBottomWeight", BOTTOM), on("strokeLeftWeight", LEFT)], + "the spec's names" + ); assert_eq!(sides("Colour"), [], "a colour variable can't be a weight"); assert!(!has(&warnings, "`individualStrokeWeights`"), "{warnings:?}"); assert!(has(&warnings, "type doesn't fit"), "{warnings:?}"); From d6bfe68936f176213737b780143f5cea52569925 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 16:51:10 -0500 Subject: [PATCH 028/114] M1: Paste with a layer in a frame selected puts the copy next to it (#2355) Cmd/Ctrl+V with one layer inside a frame selected pasted onto the page on top of the frame. It now pastes into the layer's parent just above it, in an auto layout frame the item after it. Page-level layers, several layers, instance children, board atoms, component sets and copied components keep today's behaviour. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/engine/src/cmd/edit/clipboard.rs | 44 ++++++-- crates/engine/src/lib.rs | 2 + crates/engine/src/paste_sibling_tests.rs | 122 +++++++++++++++++++++++ docs/ui-parity.md | 5 +- 4 files changed, 164 insertions(+), 9 deletions(-) create mode 100644 crates/engine/src/paste_sibling_tests.rs diff --git a/crates/engine/src/cmd/edit/clipboard.rs b/crates/engine/src/cmd/edit/clipboard.rs index dbf4ec180..09c79190b 100644 --- a/crates/engine/src/cmd/edit/clipboard.rs +++ b/crates/engine/src/cmd/edit/clipboard.rs @@ -295,6 +295,9 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result { }) .filter(|i| !copy_local || !s.clipboard.copied_components.iter().any(|root| doc.is_ancestor(*root, *i))) }); + // One layer selected that isn't a frame target: the copy joins its parent, just above it (#2355). + let sibling_of = if target.is_none() && id(p, "parent").is_none() { sibling_anchor(s, &sel, copy_local) } else { None }; + let target = target.or_else(|| sibling_of.and_then(|i| doc.node(i).and_then(|n| n.parent))); let parent = target.unwrap_or(page); let at = match (num(p, "x"), num(p, "y")) { (Some(x), Some(y)) => Some((x, y)), @@ -321,10 +324,42 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result { } }; let ids = paste_into(s, parent, at)?; + if let Some(sel) = sibling_of { + let above = s.doc()?.index_in_parent(sel).map(|ix| ix + 1); + move_above(s, &ids, parent, above)?; + } s.set_selection(ids.clone()); Ok(json!({"ids": ids})) } +/// The one selected layer a plain paste goes next to: not a page-level layer, not inside an instance +/// (its children are fixed), not a board atom, a component set (a variant's parent) or inside a copied +/// component. Else the page, as before. +fn sibling_anchor(s: &Session, sel: &[NodeId], copy_local: bool) -> Option { + let [only] = sel else { return None }; + let doc = s.doc().ok()?; + let parent = doc.node(*only)?.parent?; + let pn = doc.node(parent)?; + let ok = !pn.is_page() + && pn.kind.is_frame_like() + && !pn.is_board_atom() + && !crate::components::inside_instance(doc, *only) + && !matches!(pn.kind, NodeKind::Instance { .. } | NodeKind::ComponentSet { .. }) + && (!copy_local || !s.clipboard.copied_components.iter().any(|root| doc.is_ancestor(*root, parent))); + ok.then_some(*only) +} + +/// Move the pasted copies that landed in `parent` to `above` and after, in the copied order. +fn move_above(s: &mut Session, ids: &[NodeId], parent: NodeId, above: Option) -> Result<()> { + let Some(above) = above else { return Ok(()) }; + let doc = s.doc_mut()?; + for (k, i) in ids.iter().filter(|i| doc.node(**i).is_some_and(|n| n.parent == Some(parent))).copied().collect::>().into_iter().enumerate() + { + doc.reorder(i, above + k)?; + } + Ok(()) +} + pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result { let sel = s.selection(); let page = s.page()?; @@ -337,14 +372,7 @@ pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result { None => (page, None, None), }; let ids = paste_into(s, parent, at)?; - if let Some(above) = above { - let doc = s.doc_mut()?; - for (k, i) in - ids.iter().filter(|i| doc.node(**i).is_some_and(|n| n.parent == Some(parent))).copied().collect::>().into_iter().enumerate() - { - doc.reorder(i, above + k)?; - } - } + move_above(s, &ids, parent, above)?; s.set_selection(ids.clone()); Ok(json!({"ids": ids})) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3c81b9147..91de56d61 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -474,6 +474,8 @@ mod panels_behaviour_tests; #[cfg(test)] mod paste_missing_image_tests; #[cfg(test)] +mod paste_sibling_tests; +#[cfg(test)] mod path_read_caps_tests; #[cfg(test)] mod pdf_print_tests; diff --git a/crates/engine/src/paste_sibling_tests.rs b/crates/engine/src/paste_sibling_tests.rs new file mode 100644 index 000000000..70174fff6 --- /dev/null +++ b/crates/engine/src/paste_sibling_tests.rs @@ -0,0 +1,122 @@ +//! Cmd/Ctrl+V with one layer inside a frame selected pastes next to it, in its parent (#2355). + +use serde_json::{Value, json}; + +use crate::Session; +use crate::params::id_of; +use figcraft_doc::NodeId; + +fn id(v: &Value) -> NodeId { + id_of(&v["id"]).unwrap() +} + +fn sess() -> Session { + Session::new() +} + +fn rect(s: &mut Session, parent: Option, x: f64, y: f64) -> NodeId { + let mut p = json!({"x": x, "y": y, "width": 40, "height": 20}); + if let Some(parent) = parent { + p["parent"] = json!(parent); + } + id(&s.execute("shape.rectangle", &p).unwrap()) +} + +fn kids(s: &Session, parent: NodeId) -> Vec { + s.doc().unwrap().node(parent).unwrap().children.clone() +} + +fn parent_of(s: &Session, n: NodeId) -> Option { + s.doc().unwrap().node(n).unwrap().parent +} + +fn paste(s: &mut Session) -> Vec { + s.execute("edit.paste", &json!({})).unwrap()["ids"].as_array().unwrap().iter().filter_map(id_of).collect() +} + +#[test] +fn paste_with_a_layer_in_an_auto_layout_frame_selected_goes_right_after_it() { + let mut s = sess(); + let a = rect(&mut s, None, 0.0, 0.0); + let b = rect(&mut s, None, 0.0, 30.0); + let r = s.execute("layout.add", &json!({"ids": [a, b], "direction": "vertical"})).unwrap(); + let frame = id_of(&r["ids"][0]).unwrap(); + s.execute("node.set", &json!({"id": frame, "props": {"gap": 10}})).unwrap(); + let h0 = s.doc().unwrap().node(frame).unwrap().height; + assert_eq!(h0, 50.0); + assert_eq!(kids(&s, frame), vec![a, b]); + s.set_selection(vec![b]); + s.execute("edit.copy", &json!({})).unwrap(); + let pasted = paste(&mut s); + assert_eq!(pasted.len(), 1); + assert_eq!(parent_of(&s, pasted[0]), Some(frame), "the copy joins the selected layer's frame"); + assert_eq!(kids(&s, frame), vec![a, b, pasted[0]], "right after the selected layer in the flow"); + assert_eq!(s.doc().unwrap().node(frame).unwrap().height, h0 + 20.0 + 10.0, "the frame grew by the copy's height plus the gap"); + assert_eq!(s.selection(), pasted); +} + +#[test] +fn paste_with_a_layer_in_a_plain_frame_selected_stays_in_the_frame_in_place() { + let mut s = sess(); + let frame = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()); + let a = rect(&mut s, Some(frame), 10.0, 10.0); + let b = rect(&mut s, Some(frame), 100.0, 100.0); + s.set_selection(vec![a]); + s.execute("edit.copy", &json!({})).unwrap(); + let pasted = paste(&mut s); + assert_eq!(pasted.len(), 1); + assert_eq!(parent_of(&s, pasted[0]), Some(frame)); + assert_eq!(kids(&s, frame), vec![a, pasted[0], b], "just above the selected layer"); + let wb = s.doc().unwrap().world_bounds(pasted[0]).unwrap(); + assert_eq!((wb.x0, wb.y0), (10.0, 10.0), "at the selected layer's position"); + assert_eq!(s.selection(), pasted); +} + +#[test] +fn paste_with_a_top_level_layer_selected_is_unchanged() { + let mut s = sess(); + let a = rect(&mut s, None, 10.0, 10.0); + let page = parent_of(&s, a).unwrap(); + let before = kids(&s, page); + s.set_selection(vec![a]); + s.execute("edit.copy", &json!({})).unwrap(); + let pasted = paste(&mut s); + assert_eq!(parent_of(&s, pasted[0]), Some(page)); + let mut want = before; + want.push(pasted[0]); + assert_eq!(kids(&s, page), want, "on the page, on top, as before"); +} + +#[test] +fn paste_with_two_layers_selected_is_unchanged() { + let mut s = sess(); + let frame = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()); + let a = rect(&mut s, Some(frame), 10.0, 10.0); + let b = rect(&mut s, Some(frame), 100.0, 100.0); + let page = parent_of(&s, frame).unwrap(); + s.set_selection(vec![a, b]); + s.execute("edit.copy", &json!({})).unwrap(); + let pasted = paste(&mut s); + assert_eq!(pasted.len(), 2); + assert!(pasted.iter().all(|p| parent_of(&s, *p) == Some(page)), "on the page, as before"); + assert_eq!(kids(&s, frame), vec![a, b]); +} + +#[test] +fn paste_with_a_layer_inside_an_instance_selected_is_unchanged() { + let mut s = sess(); + let f = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 50, "name": "Button"})).unwrap()); + s.execute("text.create", &json!({"text": "OK", "x": 10, "y": 10, "parent": f})).unwrap(); + let c = id(&s.execute("component.create", &json!({"ids": [f]})).unwrap()); + let inst = id(&s.execute("instance.create", &json!({"component": c, "x": 200, "y": 0})).unwrap()); + let page = parent_of(&s, inst).unwrap(); + let inner = kids(&s, inst)[0]; + let inner_kids = kids(&s, inst); + let other = rect(&mut s, None, 500.0, 500.0); + s.set_selection(vec![other]); + s.execute("edit.copy", &json!({})).unwrap(); + s.set_selection(vec![inner]); + let pasted = paste(&mut s); + assert_eq!(parent_of(&s, pasted[0]), Some(page), "an instance's children are fixed: the copy goes to the page"); + assert_eq!(kids(&s, inst), inner_kids); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 2ec810638..fcd4212c6 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -159,7 +159,9 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look presenting. The paint bucket's tooltip shows Shift+B (B still works). - **Fixed (2026-10-17):** Shift+Cmd/Ctrl+V (Paste over selection) and Alt+Cmd/Ctrl+V (Paste properties) work on the desktop (they were bound but didn't act there, #716); Cmd/Ctrl+V pastes an - image copied in another app (#663). Counts above unchanged (the suite checks bindings). + image copied in another app (#663). With one layer inside a frame selected, Cmd/Ctrl+V pastes + into its parent just above it (in an auto layout frame, the item after it), #2355. Counts above + unchanged (the suite checks bindings). - **Where the documentation disagrees with itself** (noted per row): pixel grid (Shift+' or Cmd+'), letter spacing (Alt or Cmd with < >; Cmd would be the font size keys, Alt bound), Windows remove fill (Alt+/ or Alt+,; Alt+, is letter spacing), the Layers panel on Windows (Alt+1 @@ -208,6 +210,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-18 | patch | M1, #2355: Cmd/Ctrl+V with one layer inside a frame selected pasted the copy onto the page on top of the frame; it now goes into the layer's parent just above it (in an auto layout frame, the item after it, so the layout grows), keeping today's behaviour for a page-level layer, several layers, an instance's children and a board atom. Tests: `paste_sibling_tests` (5) | | 2026-11-08 | minor | M8, #2109: in vector edit mode the Align commands (`align.left` to `align.bottom`, Alt+A/H/D/W/V/S) and Distribute horizontal and vertical spacing act on the selected points when neither `ids` nor `id` is given (either one targets layers), as in Figma (measured in Figma on 2026-11-08): each point moves along one axis only, to its box's left, horizontal centre, right, top, vertical centre or bottom, and distribute spaces the points evenly between the outermost two in order along the axis; handles go with their vertex, a single point stays, with no point selected nothing moves (the layer is not aligned to its frame, as measured in Figma), and one undo restores them. The Design panel draws the alignment row first, with a Distribute menu from three points. Numbers unchanged. | | 2026-11-08 | patch | Number fields: scrubbing a label moves half a step a point, not a step, as measured in Figma (X from 100: +6 for a 12.2 px drag, +31 for 61.2 px; rotation 6° and opacity 5% for 12.2 px); Shift (x10), Alt (x0.1) and the speed by height are kept on top of it and were not measured, and no field's scrub direction changed | | 2026-11-17 | patch | M8: each page keeps its view in a session: going back to a page (the Pages list, `page.select`, Previous/Next page) shows it where it was left instead of fitting it again; a new page is still fitted, and going to the page shown moves nothing (`page_view_tests`) | From 3ae4971b5fea17627d82dc6cb6112d2063781dfe Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 16:51:49 -0500 Subject: [PATCH 029/114] docs: the #2355 paste note gets its own dated bullet Co-Authored-By: Claude Opus 5.5 --- docs/ui-parity.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index fcd4212c6..dac2960bd 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -159,9 +159,9 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look presenting. The paint bucket's tooltip shows Shift+B (B still works). - **Fixed (2026-10-17):** Shift+Cmd/Ctrl+V (Paste over selection) and Alt+Cmd/Ctrl+V (Paste properties) work on the desktop (they were bound but didn't act there, #716); Cmd/Ctrl+V pastes an - image copied in another app (#663). With one layer inside a frame selected, Cmd/Ctrl+V pastes - into its parent just above it (in an auto layout frame, the item after it), #2355. Counts above - unchanged (the suite checks bindings). + image copied in another app (#663). Counts above unchanged (the suite checks bindings). +- **Fixed (2026-11-13):** with one layer inside a frame selected, Cmd/Ctrl+V pastes into its parent + just above it (in an auto layout frame, the item after it), #2355. - **Where the documentation disagrees with itself** (noted per row): pixel grid (Shift+' or Cmd+'), letter spacing (Alt or Cmd with < >; Cmd would be the font size keys, Alt bound), Windows remove fill (Alt+/ or Alt+,; Alt+, is letter spacing), the Layers panel on Windows (Alt+1 From d21aebab4b586b3e0584a0392b5241cad5511028 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Wed, 18 Nov 2026 14:16:20 +0700 Subject: [PATCH 030/114] M3: combining components gives every variant the properties any of them had A property added to a set goes to all its variants (component.addProperty), but Combine as variants kept each component's own definitions, so a property made on one component before combining was missing from the others: their layers couldn't be bound to it ("the component has no property") and an instance switched to one of them dropped its value. make_variant_set now gives every variant the properties any of them has (share_props, through the give_prop step addProperty uses too); a variant with a property of that name keeps its own. Tests: variant_shared_props_tests. --- crates/engine/src/cmd/component/props.rs | 58 ++++++++++++++----- crates/engine/src/cmd/component/variants.rs | 4 +- crates/engine/src/lib.rs | 2 + .../engine/src/variant_shared_props_tests.rs | 58 +++++++++++++++++++ docs/components-parity.md | 5 +- 5 files changed, 110 insertions(+), 17 deletions(-) create mode 100644 crates/engine/src/variant_shared_props_tests.rs diff --git a/crates/engine/src/cmd/component/props.rs b/crates/engine/src/cmd/component/props.rs index 97bef3ce2..8ef066d37 100644 --- a/crates/engine/src/cmd/component/props.rs +++ b/crates/engine/src/cmd/component/props.rs @@ -218,6 +218,49 @@ fn set_prop_defs(doc: &mut Document, c: NodeId, rename: Option<(&str, &str)>, f: Ok(()) } +/// Give each of components `comps` that lacks it property `name` (`def`), and their existing +/// instances its default. +fn give_prop(doc: &mut Document, comps: &[NodeId], name: &str, def: &PropDef) -> Result<()> { + for c in comps { + if prop_defs(doc, *c).contains_key(name) { + continue; + } + set_prop_defs(doc, *c, None, |m| { + m.insert(name.to_string(), def.clone()); + })?; + if !takes_value(def) { + continue; + } + for inst in instances_of(doc, *c) { + if let NodeKind::Instance { props, .. } = &mut doc.get_mut(inst)?.kind { + props.entry(name.to_string()).or_insert_with(|| prop_default_value(def)); + } + } + } + Ok(()) +} + +/// Give every one of components `comps` (the variants of a set) the properties any of them has: +/// a set's properties belong to all its variants, as `component.addProperty` gives them, so one +/// made on a component before it was combined stays on an instance switched to another variant. +/// A variant that has a property of that name keeps its own. +pub(super) fn share_props(doc: &mut Document, comps: &[NodeId]) -> Result<()> { + let mut all: Vec<(String, PropDef)> = Vec::new(); + for c in comps { + if let Some(NodeKind::Component { props, prop_order, .. }) = doc.node(*c).map(|n| &n.kind) { + for (k, d) in ordered_props(props, prop_order) { + if !all.iter().any(|(n, _)| n == k) { + all.push((k.clone(), d.clone())); + } + } + } + } + for (name, def) in &all { + give_prop(doc, comps, name, def)?; + } + Ok(()) +} + fn valid_prop_name(cmd: &str, name: &str) -> Result { let name = name.trim(); if name.is_empty() || name.contains([',', '=']) || name.chars().count() > 200 { @@ -295,20 +338,7 @@ pub(super) fn add_prop_for(cmd: &str, s: &mut Session, p: &Value) -> Result return Err(bad(cmd, "type: boolean|text|instanceSwap|variant|slot")), }; - for c in &comps { - set_prop_defs(doc, *c, None, |m| { - m.insert(name.clone(), def.clone()); - })?; - // Existing instances get the default. - if !takes_value(&def) { - continue; - } - for inst in instances_of(doc, *c) { - if let NodeKind::Instance { props, .. } = &mut doc.get_mut(inst)?.kind { - props.entry(name.clone()).or_insert_with(|| prop_default_value(&def)); - } - } - } + give_prop(doc, &comps, &name, &def)?; if let Some(l) = layer { bind(cmd, doc, l, Some(&name), None)?; } diff --git a/crates/engine/src/cmd/component/variants.rs b/crates/engine/src/cmd/component/variants.rs index 96de6ba3a..be43bced0 100644 --- a/crates/engine/src/cmd/component/variants.rs +++ b/crates/engine/src/cmd/component/variants.rs @@ -68,7 +68,8 @@ pub fn can_add_variant(doc: &Document, id: NodeId) -> bool { } /// Wrap `ids` (z-sorted main components) in a new component set, naming them "Property 1=Default", -/// "Property 1=VariantN" unless already in prop=value form. Returns the set. +/// "Property 1=VariantN" unless already in prop=value form, each with the component properties +/// any of them has. Returns the set. fn make_variant_set(cmd: &str, doc: &mut Document, ids: &[NodeId]) -> Result { let set = wrap_in_set(cmd, doc, ids)?; for (k, i) in ids.iter().enumerate() { @@ -77,6 +78,7 @@ fn make_variant_set(cmd: &str, doc: &mut Document, ids: &[NodeId]) -> Result (NodeId, NodeId) { + let f = idv(&ex(s, "frame.create", json!({"x": x, "y": 0, "width": 120, "height": 40, "name": name}))); + let t = idv(&ex(s, "text.create", json!({"text": "Button", "x": 8, "y": 8, "parent": f}))); + (idv(&ex(s, "component.create", json!({"ids": [f]}))), t) +} + +/// `id`'s component property `name` as `component.properties` lists it. +fn property(s: &mut Session, id: NodeId, name: &str) -> Option { + let all = ex(s, "component.properties", json!({"id": id})); + all["properties"].as_array().and_then(|l| l.iter().find(|p| p["name"] == name).cloned()) +} + +#[test] +fn a_property_made_before_combining_goes_to_every_variant() { + let mut s = Session::new(); + let (a, label) = component(&mut s, "State=Default", 0.0); + let (b, b_label) = component(&mut s, "State=Hover", 200.0); + ex(&mut s, "component.addProperty", json!({"id": a, "name": "Text", "type": "text", "layer": label})); + let of_b = idv(&ex(&mut s, "instance.create", json!({"component": b, "x": 0, "y": 300}))); + ex(&mut s, "component.combineVariants", json!({"ids": [a, b]})); + healthy(&s); + let shared = property(&mut s, b, "Text").expect("the other variant has the property"); + assert_eq!((shared["type"].clone(), shared["default"].clone()), (json!("text"), json!("Button"))); + // The other variant's text can be bound to it, and its instance then shows the default. + ex(&mut s, "component.bindProperty", json!({"layer": b_label, "property": "Text"})); + assert_eq!(property(&mut s, of_b, "Text").map(|p| p["value"].clone()), Some(json!("Button"))); + // An instance switched to the other variant keeps the value it was given. + let of_a = idv(&ex(&mut s, "instance.create", json!({"component": a, "x": 200, "y": 300}))); + ex(&mut s, "instance.setProperties", json!({"ids": [of_a], "properties": {"Text": "Buy"}})); + ex(&mut s, "instance.setProperties", json!({"ids": [of_a], "properties": {"State": "Hover"}})); + assert_eq!(property(&mut s, of_a, "Text").map(|p| p["value"].clone()), Some(json!("Buy"))); + healthy(&s); +} + +#[test] +fn a_variant_keeps_its_own_property_of_the_same_name() { + let mut s = Session::new(); + let (a, _) = component(&mut s, "State=Default", 0.0); + let (b, _) = component(&mut s, "State=Hover", 200.0); + ex(&mut s, "component.addProperty", json!({"id": a, "name": "Icon", "type": "text", "default": "Star"})); + ex(&mut s, "component.addProperty", json!({"id": b, "name": "Icon", "type": "boolean", "default": false})); + ex(&mut s, "component.combineVariants", json!({"ids": [a, b]})); + healthy(&s); + assert_eq!(property(&mut s, a, "Icon").map(|p| p["type"].clone()), Some(json!("text"))); + assert_eq!(property(&mut s, b, "Icon").map(|p| p["type"].clone()), Some(json!("boolean"))); +} diff --git a/docs/components-parity.md b/docs/components-parity.md index 3776a4f96..73d1d8ced 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -1,6 +1,6 @@ # Components, variants, styles and variables parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-14 · **Change:** minor (renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (combining components gives every variant the properties any of them had; renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); 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 @@ -17,7 +17,7 @@ accounts). | Per-layer overrides with reset; kept across main edits, nested swaps, copy/paste | done | main edits match a full rebuild exactly at 2,000 instances | | What an instance overrides: fills, strokes, effects, visibility, layer names, text content and every text property (resizing included), auto layout padding, gap and alignment, layout grids, export settings, prototype interactions, nested swaps and property values; the size and resizing (hug, fill, fixed, min and max) of layers inside it; an instance's own resizing (hug or fixed) follows its main's unless its size is overridden, measured: a plain instance turns Fixed when its main does (a child set to Fill along the hugging axis) and back to Hug with it, one whose width was typed keeps it, and Fill in its own auto layout parent is its own | done | each kept when the main changes that property, reset per group; opacity and corner radius too (documentation silent); size and resizing are kept through relayout, undo, save, `.fig` and REST import and detach, and stay with the instance on push | | What it doesn't: position, rotation, constraints and absolute or grid placement of layers inside it, its auto layout direction and other settings, its structure | done | refused with a message, the fields greyed out (Delete on a layer inside an instance hides it instead of removing it, as the help center says it does); the instance itself resizes and its layers follow the main's constraints | -| Component sets / variants, add variant, switch | done | Combine as variants is in the Object menu, and the canvas and layers context menu and the Design panel offer it when two or more main components are selected; Add variant on a main component not in a set yet makes it a set of itself and the new variant, one undo step (#903); components that are variants already aren't combined again (it used to put a set inside a set) | +| Component sets / variants, add variant, switch | done | Combine as variants is in the Object menu, and the canvas and layers context menu and the Design panel offer it when two or more main components are selected; Add variant on a main component not in a set yet makes it a set of itself and the new variant, one undo step (#903); components that are variants already aren't combined again (it used to put a set inside a set); combining gives every variant the component properties any of them had, so another variant's layers can be bound to one made before combining | | A main's copy within its file is an instance of it: Duplicate, Alt-drag, Copy then Paste | done | a variant duplicated in its set stays a new variant and a whole set copies as a new set; only the copied roots become instances (a main inside a copied frame is copied as a main); Cut then Paste and pastes into other files keep the component (#892) | | A component can't contain its own instance, directly or through other components | done | refused with the loop named (creating, placing, swapping, switching variants, moving, pasting, an instance-swap value); each variant counts as its own component, so a variant may hold a sibling variant's instance unless that one leads back to it; a dropped instance lands on the page; a file holding a loop opens with one instance detached and a note, any other file unchanged; a loop merged in a live session stops expanding where an instance would show itself again (#1084) | | Switching variants keeps overrides where names match and both variants had the same value; text layers keep theirs | done | | @@ -80,6 +80,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-11-18 | patch | M3: Combine as variants gives every variant the component properties any of the components had (as a property added to a set goes to all its variants); a property made on one component before combining was missing from the others, so their layers couldn't be bound to it and an instance switched to them dropped its value. A variant with a property of the same name keeps its own. Tests: `variant_shared_props_tests`. | | 2026-11-18 | patch | M3, #2368: a text field that isn't being edited ends a value too long for it with an ellipsis and shows the whole value on hover (a secret field shows none), so the variant value "Down left" no longer reads "Down lef"; screen readers and editing keep the whole value (`field_ellipsis_tests`). Grade unchanged. | | 2026-11-14 | patch | M3, #2354: the Local variables window resizes from its edges and corners, width and height (minimum 600 x 240), and keeps its size and place while the app runs. | | 2026-11-07 | patch | M3, #2090: an instance's own resizing follows its main's unless its size is overridden. Measured in Figma: a plain instance turns Fixed when its main's width does (a child set to Fill along it) and back to Hug with it; an instance whose width was typed keeps it; Fill in its own auto layout parent is kept. Tests: `components_behaviour_tests::a_plain_instances_resizing_follows_the_mains_root_both_ways` and the instance resizing tests beside it. | From e4bc5678552bd6ba9a0ac86d38ede2c2b912c9d1 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 31 Oct 2026 08:15:52 +0700 Subject: [PATCH 031/114] M3: library analytics count insertions and detachments of styles and variables Applying a style or variable, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and library.usage give them over the chosen period. --- ROADMAP.md | 3 +- apps/figcraft-server/src/disk.rs | 1 + .../src/library_assets_tests.rs | 39 +++++- apps/figcraft-server/src/store.rs | 12 +- apps/figcraft-server/src/store/backend.rs | 2 + apps/figcraft-server/src/store/library.rs | 95 ++++++++++----- crates/collab-net/src/link.rs | 5 +- crates/collab/src/message.rs | 20 ++- crates/doc/src/library.rs | 31 +++++ crates/engine/src/assets/library.rs | 57 ++++++++- crates/engine/src/assets/library_server.rs | 12 +- crates/engine/src/cmd/library.rs | 44 ++++++- crates/engine/src/cmd/styles.rs | 12 ++ crates/engine/src/lib.rs | 2 + .../engine/src/library_asset_counts_tests.rs | 115 ++++++++++++++++++ crates/engine/src/sharing/background/tests.rs | 5 +- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/panels/assets_panel.rs | 39 ++++-- crates/ui-egui/src/usage_summary_tests.rs | 30 +++++ docs/collab-protocol.md | 8 +- docs/components-parity.md | 5 +- docs/gaps.md | 12 +- docs/mcp.md | 2 +- docs/roadmap.md | 3 +- docs/server.md | 5 +- 25 files changed, 484 insertions(+), 77 deletions(-) create mode 100644 crates/engine/src/library_asset_counts_tests.rs create mode 100644 crates/ui-egui/src/usage_summary_tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index ad2ae9f69..107a11f96 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-18 · **Change:** minor (web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-18 · **Change:** minor (library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -366,6 +366,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. | | 2026-11-15 | patch | CLI usage and operation failures escape terminal controls in paths and error text, using the same printable-text rule as info and script diagnostics; exit codes and ordinary quotes and paths stay unchanged. | diff --git a/apps/figcraft-server/src/disk.rs b/apps/figcraft-server/src/disk.rs index 219bce324..19cbfc8d3 100644 --- a/apps/figcraft-server/src/disk.rs +++ b/apps/figcraft-server/src/disk.rs @@ -28,6 +28,7 @@ pub const LINKS: &str = "links.json"; pub const LIBRARY: &str = "library.bin"; pub const USAGE: &str = "usage.json"; pub const ACTIONS: &str = "actions.json"; +pub const ASSET_ACTIONS: &str = "asset-actions.json"; const SNAP_MAGIC: &[u8; 4] = b"FCSN"; const LOG_MAGIC: &[u8; 4] = b"FCLG"; diff --git a/apps/figcraft-server/src/library_assets_tests.rs b/apps/figcraft-server/src/library_assets_tests.rs index 4c9b8aaef..4da1aba8d 100644 --- a/apps/figcraft-server/src/library_assets_tests.rs +++ b/apps/figcraft-server/src/library_assets_tests.rs @@ -79,7 +79,7 @@ fn styles_and_variables_are_counted_per_layer_and_file() { // Bo takes the style off one layer and the variable off its only one. ex(&mut b, "style.detach", json!({"ids": [two], "which": "fill"})); ex(&mut b, "variable.bind", json!({"ids": [three], "field": "fill"})); - let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["layers"] == 1 && u["variables"].as_array().is_some_and(Vec::is_empty)); + let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["layers"] == 1 && u["variables"][0]["layers"] == 0); assert_eq!(u["styles"].as_array().unwrap().len(), 1, "{u}"); server.stop(); } @@ -143,3 +143,40 @@ fn answer(raw: &mut Raw) -> LibraryReply { other => panic!("not a library answer: {other:?}"), } } + +#[test] +fn inserts_and_detaches_count_per_style_and_variable_in_the_period() { + let dir = TempDir::new("library-asset-actions"); + let cfg = config(dir.path()); + let mut server = crate::start(&cfg).unwrap(); + let addr = server.addr(); + let mut a = session("Ada"); + let r = rect(&mut a, 0); + ex(&mut a, "style.create", json!({"type": "paint", "name": "Brand", "from": r.0})); + let collection = ex(&mut a, "variable.createCollection", json!({"name": "Tokens"})); + ex(&mut a, "variable.create", json!({"name": "Accent", "type": "color", "collection": collection["id"], "value": "#0D99FF"})); + let p = publish(&mut a, dir.path(), addr); + ex(&mut a, "library.publishToServer", json!({})); + + let mut b = session("Bo"); + let lid = ex(&mut b, "library.add", json!({"path": p.view}))["id"].as_str().unwrap().to_string(); + let (one, two) = (rect(&mut b, 0), rect(&mut b, 100)); + ex(&mut b, "library.applyStyle", json!({"library": lid, "style": "Brand", "ids": [one.0, two.0]})); + ex(&mut b, "style.detach", json!({"ids": [two.0], "which": "fill"})); + ex(&mut b, "library.bindVariable", json!({"library": lid, "variable": "Accent", "ids": [two.0], "field": "fill"})); + + let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["insertions"] == 2 && u["variables"][0]["insertions"] == 1); + assert_eq!(u["assetActionsKnown"], true, "{u}"); + assert_eq!(u["styles"][0]["detachments"], 1, "{u}"); + assert_eq!(u["variables"][0]["detachments"], 0, "{u}"); + assert_eq!(u["insertions"], 0, "components count on their own: {u}"); + + // An undo and a redo count once, and a style no layer uses any more stays listed. + ex(&mut b, "edit.undo", json!({})); + ex(&mut b, "edit.redo", json!({})); + ex(&mut b, "style.detach", json!({"ids": [one.0], "which": "fill"})); + let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["detachments"] == 2); + assert_eq!((u["styles"][0]["insertions"].clone(), u["styles"][0]["layers"].clone()), (json!(2), json!(0)), "{u}"); + assert_eq!(u["variables"][0]["insertions"], 1, "{u}"); + server.stop(); +} diff --git a/apps/figcraft-server/src/store.rs b/apps/figcraft-server/src/store.rs index 2e713deb2..fbf4bc2db 100644 --- a/apps/figcraft-server/src/store.rs +++ b/apps/figcraft-server/src/store.rs @@ -40,8 +40,8 @@ use std::path::{Path, PathBuf}; use std::time::{Instant, SystemTime, UNIX_EPOCH}; use figcraft_collab::message::{ - Access, Admin, AdminReply, AssetUsage, ClientMsg, Detached, FileDetached, FileInfo, FileRow, FileUsage, HostInfo, LibraryReply, LibraryReq, - LinkInfo, MAX_OWNED, NewLink, OwnedFile, PluginReply, PluginReq, ReportInfo, Usage, WeekActions, + Access, Admin, AdminReply, AssetActions, AssetUsage, ClientMsg, Detached, FileDetached, FileInfo, FileRow, FileUsage, HostInfo, LibraryReply, + LibraryReq, LinkInfo, MAX_OWNED, NewLink, OwnedFile, PluginReply, PluginReq, ReportInfo, Usage, WeekActions, }; use figcraft_collab::{Change, NodeId, Replica, Server, same_secret}; use figcraft_collab_net::hub::{Admission, Backend, Closing, Handled, OpenFile, ip_blocks, ip_key}; @@ -52,7 +52,7 @@ use sha2::{Digest, Sha256}; use crate::abuse::{Abuse, AbuseConfig, Action}; use crate::codes::{self, Sealed}; use crate::directory::{Directory, DirectoryConfig}; -use crate::disk::{self, ACTIONS, LIBRARY, LINKS, LOG, LOG_HEADER, META, SNAPSHOT, USAGE}; +use crate::disk::{self, ACTIONS, ASSET_ACTIONS, LIBRARY, LINKS, LOG, LOG_HEADER, META, SNAPSHOT, USAGE}; mod backend; mod files; @@ -298,6 +298,8 @@ struct UsageCache { list: Vec, /// Insertions and detachments week by week, over every file (kept in `actions.json`). weeks: Vec, + /// The same for styles and variables (kept in `asset-actions.json`). + asset_weeks: Vec>, dirty: bool, written: u64, } @@ -321,6 +323,8 @@ struct UsageEntry { styles: Vec<(String, u32)>, #[serde(default, skip_serializing_if = "Vec::is_empty")] variables: Vec<(String, u32)>, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + asset_peaks: Vec<(String, u32, u32)>, } fn is_zero(n: &u64) -> bool { @@ -560,7 +564,7 @@ impl Store { /// A file folder's description and links, after checking its snapshot and log. Leftover /// temporary files (writes cut short) are removed. fn check(&self, path: &Path) -> Result { - for name in [SNAPSHOT, LOG, META, LINKS, USAGE, ACTIONS] { + for name in [SNAPSHOT, LOG, META, LINKS, USAGE, ACTIONS, ASSET_ACTIONS] { let tmp = disk::temp_of(&path.join(name)); if tmp.exists() { let _ = fs::remove_file(&tmp); diff --git a/apps/figcraft-server/src/store/backend.rs b/apps/figcraft-server/src/store/backend.rs index 5d4a3bfe9..42900e6b8 100644 --- a/apps/figcraft-server/src/store/backend.rs +++ b/apps/figcraft-server/src/store/backend.rs @@ -278,6 +278,8 @@ impl Backend for Store { LibraryReq::Actions => self.library_actions(file).map_or_else(failed, LibraryReply::Actions), LibraryReq::ReportAssets(a) => self.report_assets(file, a).map_or_else(failed, |()| LibraryReply::Noted), LibraryReq::Assets => self.library_assets(file).map_or_else(failed, LibraryReply::Assets), + LibraryReq::ReportAssetActions(a) => self.report_asset_actions(file, a).map_or_else(failed, |()| LibraryReply::Noted), + LibraryReq::AssetActions => self.library_asset_actions(file).map_or_else(failed, LibraryReply::AssetActions), } } diff --git a/apps/figcraft-server/src/store/library.rs b/apps/figcraft-server/src/store/library.rs index 322c906e8..10337a451 100644 --- a/apps/figcraft-server/src/store/library.rs +++ b/apps/figcraft-server/src/store/library.rs @@ -1,9 +1,9 @@ use figcraft_collab::message::MAX_ASSET_USAGE; use super::{ - ACTIONS, Action, AssetUsage, BUSY_DOWNLOADS, Cursor, Detached, FILES, FileDetached, FileUsage, IpAddr, LIBRARY, LibraryMeta, LibraryReply, - MAX_FIRST_LIBRARY_VERSION, MAX_REPORTED, MAX_USAGE_FILE, MAX_USERS, MAX_WEEK_ROWS, MAX_WEEKS, META, NO_PUBLIC_LIBRARY, NodeId, Path, PathBuf, - Store, USAGE, USAGE_WRITE_EVERY, Usage, UsageCache, UsageEntry, WeekActions, clean_name, disk, fs, now, write_json, + ACTIONS, ASSET_ACTIONS, Action, AssetActions, AssetUsage, BUSY_DOWNLOADS, Cursor, Detached, FILES, FileDetached, FileUsage, IpAddr, LIBRARY, + LibraryMeta, LibraryReply, MAX_FIRST_LIBRARY_VERSION, MAX_REPORTED, MAX_USAGE_FILE, MAX_USERS, MAX_WEEK_ROWS, MAX_WEEKS, META, NO_PUBLIC_LIBRARY, + NodeId, Path, PathBuf, Store, USAGE, USAGE_WRITE_EVERY, Usage, UsageCache, UsageEntry, WeekActions, clean_name, disk, fs, now, write_json, }; /// Which of a file's totals a report brings. @@ -46,49 +46,55 @@ fn read_kept(path: &Path) -> Vec { disk::read_capped(path, MAX_USAGE_FILE).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default() } +/// Raise the highest `kind` totals in `peaks` to `counts`, each from what `last` says was reported +/// before them; what grew past them, by how much. +fn grow(peaks: &mut Vec<(K, u32, u32)>, counts: &[(K, u32)], kind: Count, last: impl Fn(&K) -> u32) -> Vec<(K, u32)> { + let mut grown = Vec::new(); + for (c, n) in counts { + let at = match peaks.iter().position(|p| p.0 == *c) { + Some(at) => at, + None if peaks.len() < MAX_REPORTED => { + peaks.push((c.clone(), 0, 0)); + peaks.len() - 1 + } + None => continue, + }; + let Some(p) = peaks.get_mut(at) else { continue }; + let peak = if kind == Count::Inserted { &mut p.1 } else { &mut p.2 }; + let base = (*peak).max(last(c)); + if *n > base { + grown.push((c.clone(), *n - base)); + } + *peak = base.max(*n); + } + grown +} + impl UsageEntry { /// Raise this file's highest `kind` totals to `counts`; what grew past them, by how much. /// A detach total reported before peaks were kept starts from that report. fn grow_peaks(&mut self, counts: &[(NodeId, u32)], kind: Count) -> Vec<(NodeId, u32)> { - let mut grown = Vec::new(); - for &(c, n) in counts { - let last = if kind == Count::Detached { self.detached.iter().find(|d| d.0 == c).map_or(0, |d| d.1) } else { 0 }; - let at = match self.peaks.iter().position(|p| p.0 == c) { - Some(at) => at, - None if self.peaks.len() < MAX_REPORTED => { - self.peaks.push((c, 0, 0)); - self.peaks.len() - 1 - } - None => continue, - }; - let Some(p) = self.peaks.get_mut(at) else { continue }; - let peak = if kind == Count::Inserted { &mut p.1 } else { &mut p.2 }; - let base = (*peak).max(last); - if n > base { - grown.push((c, n - base)); - } - *peak = base.max(n); - } - grown + let detached = &self.detached; + grow(&mut self.peaks, counts, kind, |c| if kind == Count::Detached { detached.iter().find(|d| d.0 == *c).map_or(0, |d| d.1) } else { 0 }) } } /// Add `grown` to this week's `kind` counts in `weeks`, dropping weeks older than [`MAX_WEEKS`] /// and, past [`MAX_WEEK_ROWS`], the oldest rows. -fn add_to_week(weeks: &mut Vec, grown: &[(NodeId, u32)], kind: Count, t: u64) { +fn add_to_week(weeks: &mut Vec>, grown: &[(K, u32)], kind: Count, t: u64) { let week = week_of(t); weeks.retain(|w| w.week.saturating_add(MAX_WEEKS * WEEK) > week); - for &(component, n) in grown { - let at = match weeks.iter().position(|w| w.week == week && w.component == component) { + for (component, n) in grown { + let at = match weeks.iter().position(|w| w.week == week && w.component == *component) { Some(at) => at, None => { - weeks.push(WeekActions { week, component, insertions: 0, detachments: 0 }); + weeks.push(WeekActions { week, component: component.clone(), insertions: 0, detachments: 0 }); weeks.len() - 1 } }; if let Some(w) = weeks.get_mut(at) { let slot = if kind == Count::Inserted { &mut w.insertions } else { &mut w.detachments }; - *slot = slot.saturating_add(n); + *slot = slot.saturating_add(*n); } } if weeks.len() > MAX_WEEK_ROWS { @@ -184,8 +190,9 @@ impl Store { } if !self.usage.contains_key(file) { let path = self.dir(file).join(USAGE); - let (list, weeks) = (read_kept(&path), read_kept(&self.dir(file).join(ACTIONS))); - self.usage.insert(file.to_string(), UsageCache { list, weeks, dirty: false, written: now() }); + let dir = self.dir(file); + let (list, weeks, asset_weeks) = (read_kept(&path), read_kept(&dir.join(ACTIONS)), read_kept(&dir.join(ASSET_ACTIONS))); + self.usage.insert(file.to_string(), UsageCache { list, weeks, asset_weeks, dirty: false, written: now() }); } Ok(self.usage.get_mut(file)) } @@ -234,6 +241,31 @@ impl Store { }) } + /// A file's library's styles' and variables' insertions and detachments week by week, over + /// the last [`MAX_WEEKS`] weeks (none when it has no library). + pub fn library_asset_actions(&mut self, file: &str) -> Result>, String> { + let since = week_of(now()).saturating_sub((MAX_WEEKS - 1) * WEEK); + let weeks = self.usage_of(file)?.map(|u| u.asset_weeks.as_slice()).unwrap_or_default(); + Ok(weeks.iter().filter(|w| w.week >= since).cloned().collect()) + } + + /// Note how many times one file has inserted and detached a file's library's styles and + /// variables: what its totals grew past their highest counts in this week. + pub fn report_asset_actions(&mut self, file: &str, actions: AssetActions) -> Result<(), String> { + for (counts, kind) in [(actions.inserted, Count::Inserted), (actions.detached, Count::Detached)] { + let mut grown = Vec::new(); + self.report(file, &actions.file, known_assets(counts), |e, counts| { + grown = grow(&mut e.asset_peaks, &counts, kind, |_| 0); + !grown.is_empty() + })?; + if let (false, Some(u)) = (grown.is_empty(), self.usage.get_mut(file)) { + add_to_week(&mut u.asset_weeks, &grown, kind, now()); + u.dirty = true; + } + } + Ok(()) + } + /// Keep how many layers of one file use a file's library's styles and variables (as /// [`Self::report_usage`] keeps its usage, beside it). pub fn report_assets(&mut self, file: &str, assets: AssetUsage) -> Result<(), String> { @@ -325,7 +357,8 @@ impl Store { if let Err(e) = write_json(&root.join(file).join(USAGE), &u.list) { log::warn!("file {file}: library usage couldn't be kept: {e}"); } - if let Err(e) = write_json(&root.join(file).join(ACTIONS), &u.weeks) { + let actions = write_json(&root.join(file).join(ACTIONS), &u.weeks); + if let Err(e) = actions.and_then(|()| write_json(&root.join(file).join(ASSET_ACTIONS), &u.asset_weeks)) { log::warn!("file {file}: library analytics couldn't be kept: {e}"); } (u.dirty, u.written) = (false, t); diff --git a/crates/collab-net/src/link.rs b/crates/collab-net/src/link.rs index 30bc587c3..198022a09 100644 --- a/crates/collab-net/src/link.rs +++ b/crates/collab-net/src/link.rs @@ -277,7 +277,10 @@ impl LiveLink for NetLink { let spawned = std::thread::Builder::new().name("library-fetch".into()).spawn(move || { for (link, req) in jobs { // A report's answer says nothing about the library (and an older server refuses it). - let report = matches!(req, LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_)); + let report = matches!( + req, + LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_) | LibraryReq::ReportAssetActions(_) + ); let reply = manage::library(&link, req, &limits, CONNECT); if !report { inbox.push(Event::Library { link, reply }); diff --git a/crates/collab/src/message.rs b/crates/collab/src/message.rs index 07adbb2af..1ba0896aa 100644 --- a/crates/collab/src/message.rs +++ b/crates/collab/src/message.rs @@ -629,6 +629,15 @@ pub struct AssetUsage { pub variables: Vec<(String, u32)>, } +/// How many times one file has inserted and detached a library's styles and variables, as its app +/// reports them: its name and its totals of each (by their ids in the library). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct AssetActions { + pub file: String, + pub inserted: Vec<(String, u32)>, + pub detached: Vec<(String, u32)>, +} + /// A file's last usage report, with when it came (seconds since 1970, UTC). #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct FileUsage { @@ -655,9 +664,9 @@ pub struct FileDetached { /// 1970 UTC, a Monday at 00:00), over every file that reported it: instances inserted (placed, /// pasted or duplicated) and detached, counted when the server first heard of them. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct WeekActions { +pub struct WeekActions { pub week: u64, - pub component: NodeId, + pub component: K, pub insertions: u32, pub detachments: u32, } @@ -692,6 +701,12 @@ pub enum LibraryReq { ReportAssets(AssetUsage), /// The style and variable reports of the files that use the library. Assets, + /// How many times the asking file has inserted and detached the library's styles and variables + /// (answered with [`LibraryReply::Noted`]). + ReportAssetActions(AssetActions), + /// The library's styles' and variables' insertions and detachments week by week (answered with + /// [`LibraryReply::AssetActions`]). + AssetActions, } /// The answer to a [`LibraryReq`] (the first one on a connection answers [`OpenLibrary`]). @@ -727,6 +742,7 @@ pub enum LibraryReply { Detached(Vec), Actions(Vec), Assets(Vec), + AssetActions(Vec>), } /// Opens a connection to a server's plugin directory (instead of [`Hello`]). Anyone who can reach diff --git a/crates/doc/src/library.rs b/crates/doc/src/library.rs index 35279aae4..828e1605b 100644 --- a/crates/doc/src/library.rs +++ b/crates/doc/src/library.rs @@ -217,6 +217,10 @@ pub struct Libraries { /// or duplicated; reported like [`Self::detached`]), at most [`MAX_DETACH_COUNTS`] components. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub inserted: Vec, + /// How often this document has inserted and detached each library style and variable + /// (reported like [`Self::detached`]), at most [`MAX_DETACH_COUNTS`] of them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub asset_counts: Vec, } /// Most library components a document counts detaches for. @@ -233,6 +237,17 @@ pub struct DetachCount { pub count: u32, } +/// Inserts and detaches of one library style or variable in a document. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct AssetCount { + /// The library's id. + pub library: String, + /// Its id in the library. + pub key: String, + pub inserted: u32, + pub detached: u32, +} + /// Count one more instance of component `key` of library `library` in `list` (a component not /// counted yet is left out once [`MAX_DETACH_COUNTS`] are). fn count(list: &mut Vec, library: &str, key: NodeId) { @@ -256,6 +271,21 @@ impl Libraries { count(&mut self.inserted, library, key); } + /// Count `n` more inserts (or, with `detach`, detaches) of style or variable `key` of library + /// `library` (one not counted yet is left out once [`MAX_DETACH_COUNTS`] are). + pub fn count_asset(&mut self, library: &str, key: &str, detach: bool, n: u32) { + let at = self.asset_counts.iter().position(|c| c.library == library && c.key == key); + let at = at.or_else(|| { + let room = self.asset_counts.len() < MAX_DETACH_COUNTS; + room.then(|| self.asset_counts.push(AssetCount { library: library.to_string(), key: key.to_string(), inserted: 0, detached: 0 }))?; + Some(self.asset_counts.len() - 1) + }); + if let Some(c) = at.and_then(|at| self.asset_counts.get_mut(at)) { + let total = if detach { &mut c.detached } else { &mut c.inserted }; + *total = total.saturating_add(n); + } + } + /// Whether nothing is enabled, kept or counted. pub fn is_empty(&self) -> bool { self.enabled.is_empty() @@ -266,6 +296,7 @@ impl Libraries { && self.variables.is_empty() && self.detached.is_empty() && self.inserted.is_empty() + && self.asset_counts.is_empty() } /// Serde helper: leave the field out of files that use no libraries. diff --git a/crates/engine/src/assets/library.rs b/crates/engine/src/assets/library.rs index 785e6c748..5c8baa1f1 100644 --- a/crates/engine/src/assets/library.rs +++ b/crates/engine/src/assets/library.rs @@ -83,14 +83,57 @@ pub fn asset_root(doc: &Document, id: NodeId) -> Option { chain.into_iter().rfind(|c| doc.node(*c).is_some_and(is_asset)) } +/// The styles and variables layer `n` links to, each once. +fn asset_links(n: &Node) -> BTreeSet<&str> { + style_links(n).map(String::as_str).chain(n.bound.values().map(String::as_str)).collect() +} + +/// The library and the id there of a local copy of a library style or variable. +fn asset_record<'a>(doc: &'a Document, local: &str) -> Option<&'a ImportedRecord> { + doc.libraries.styles.iter().chain(&doc.libraries.variables).find(|r| r.local == local) +} + +/// How many layers link to each local copy of a library style or variable. +fn library_links(doc: &Document) -> BTreeMap { + let mut links = BTreeMap::new(); + if doc.libraries.styles.is_empty() && doc.libraries.variables.is_empty() { + return links; + } + for local in doc.nodes().flat_map(asset_links).filter(|l| asset_record(doc, l).is_some()) { + *links.entry(local.to_string()).or_default() += 1; + } + links +} + +/// Run `edit`, a user's applying (or, with `detach`, detaching) of styles or variables, and count +/// the layers it links to library copies (or unlinks from them) for the libraries' analytics. A +/// style replaced by another isn't a detach: only what the action names counts. +pub(crate) fn counting_links(s: &mut crate::Session, detach: bool, edit: impl FnOnce(&mut crate::Session) -> Result) -> Result { + let before = library_links(s.doc()?); + let out = edit(s)?; + let after = library_links(s.doc()?); + let (from, to) = if detach { (&after, &before) } else { (&before, &after) }; + let grown: Vec<_> = to.iter().map(|(l, n)| (l, n.saturating_sub(from.get(l).copied().unwrap_or(0)))).filter(|g| g.1 > 0).collect(); + for (local, n) in grown { + let doc = s.doc_mut()?; + if let Some(r) = asset_record(doc, local).cloned() { + doc.libraries_mut().count_asset(&r.library, &r.key, detach, n); + } + } + Ok(out) +} + /// Count the instances of library components among `roots` (new layers: placed, pasted or -/// duplicated) and in what they hold as inserted, for the libraries' analytics. An instance inside -/// another instance is part of it and isn't counted on its own. +/// duplicated) and in what they hold as inserted, and the library styles and variables of the +/// rest, for the libraries' analytics. An instance inside another instance is part of it and isn't +/// counted on its own, and what an instance uses is counted as the instance alone. pub(crate) fn count_inserted(doc: &mut Document, roots: &[NodeId]) { - if doc.libraries.components.is_empty() { + let l = &doc.libraries; + if l.components.is_empty() && l.styles.is_empty() && l.variables.is_empty() { return; } let mut found = Vec::new(); + let mut assets = Vec::new(); let mut stack = roots.to_vec(); while let Some(id) = stack.pop() { let Some(n) = doc.node(id) else { continue }; @@ -99,12 +142,18 @@ pub(crate) fn count_inserted(doc: &mut Document, roots: &[NodeId]) { let root = asset_root(doc, component); found.extend(doc.libraries.components.iter().find(|r| Some(r.root) == root).map(|r| (r.library.clone(), r.key))); } - _ => stack.extend(n.children.iter().copied()), + _ => { + stack.extend(n.children.iter().copied()); + assets.extend(asset_links(n).into_iter().filter_map(|l| asset_record(doc, l)).cloned()); + } } } for (library, key) in found { doc.libraries_mut().count_insert(&library, key); } + for r in assets { + doc.libraries_mut().count_asset(&r.library, &r.key, false, 1); + } } /// Components the layers of `root` use: mains of instances, instance swap defaults and values. diff --git a/crates/engine/src/assets/library_server.rs b/crates/engine/src/assets/library_server.rs index 81889be5d..3d42e7c98 100644 --- a/crates/engine/src/assets/library_server.rs +++ b/crates/engine/src/assets/library_server.rs @@ -15,7 +15,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::io::Cursor; use std::sync::Arc; -use figcraft_collab::message::{AssetUsage, Detached, LibraryReply, LibraryReq, MAX_ASSET_USAGE, Usage}; +use figcraft_collab::message::{AssetActions, AssetUsage, Detached, LibraryReply, LibraryReq, MAX_ASSET_USAGE, Usage}; use figcraft_doc::{DetachCount, Document, ImportedRecord, NodeId, NodeKind, PublishedLibrary}; use crate::live::{NetReply, NetRequest}; @@ -123,6 +123,15 @@ pub fn asset_usage(doc: &Document, library: &str) -> Option { Some(AssetUsage { file: doc.name.clone(), styles: most_used(styles), variables: most_used(variables) }) } +/// How many times `doc` has inserted and detached `library`'s styles and variables, its totals; +/// `None` when it has done neither. +pub fn asset_actions(doc: &Document, library: &str) -> Option { + let counts: Vec<_> = doc.libraries.asset_counts.iter().filter(|c| c.library == library).collect(); + let totals = + |n: fn(&figcraft_doc::AssetCount) -> u32| counts.iter().filter(|c| n(c) > 0).map(|c| (c.key.clone(), n(c))).take(MAX_ASSET_USAGE).collect(); + (!counts.is_empty()).then(|| AssetActions { file: doc.name.clone(), inserted: totals(|c| c.inserted), detached: totals(|c| c.detached) }) +} + /// `counts`, the most used first, at most [`MAX_ASSET_USAGE`]. fn most_used(counts: BTreeMap<&str, u32>) -> Vec<(String, u32)> { let mut list: Vec<(String, u32)> = counts.into_iter().map(|(k, n)| (k.to_string(), n)).collect(); @@ -270,6 +279,7 @@ impl Session { detached(doc, &l.id).map(LibraryReq::ReportDetached), inserted(doc, &l.id).map(LibraryReq::ReportInserted), asset_usage(doc, &l.id).map(LibraryReq::ReportAssets), + asset_actions(doc, &l.id).map(LibraryReq::ReportAssetActions), ]; let fetch = LibraryReq::Fetch { have, usage: Some(usage(doc, &l.id)) }; std::iter::once(fetch).chain(reports.into_iter().flatten()).map(|req| (l.path.clone(), req)) diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index d8e2e6893..e562b142b 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -436,6 +436,8 @@ fn usage_cmd(s: &mut Session, p: &Value) -> Result { Err(EngineError::Waiting) => return Err(EngineError::Waiting), _ => None, }; + let asset_weeks = asset_week_rows(s, &link, since)?; + let asset_actions = asset_period(asset_weeks.as_deref().unwrap_or_default()); let m = &lib.manifest; // Component → (instances, files using it, instances detached). let mut per: std::collections::BTreeMap = std::collections::BTreeMap::new(); @@ -481,30 +483,62 @@ fn usage_cmd(s: &mut Session, p: &Value) -> Result { "files": rows, "components": components, "assetsKnown": assets.is_some(), - "styles": asset_rows(assets.iter().flatten().map(|a| &a.styles), |id| { + "assetActionsKnown": asset_weeks.is_some(), + "styles": asset_rows(assets.iter().flatten().map(|a| &a.styles), &asset_actions, |id| { m.style(id).map(|x| json!({"name": x.name, "type": x.kind})) }), - "variables": asset_rows(assets.iter().flatten().map(|a| &a.variables), |id| { + "variables": asset_rows(assets.iter().flatten().map(|a| &a.variables), &asset_actions, |id| { let v = m.variable(id)?; Some(json!({"name": v.name, "collection": m.collection(&v.collection).map(|c| c.name.clone())})) }), })) } -/// The style or variable reports' totals, the most used first: each one's `id`, `layers` and -/// `files`, with what `describe` says of it (nothing for one no longer published). -fn asset_rows<'a>(reports: impl Iterator>, describe: impl Fn(&str) -> Option) -> Vec { +/// The styles' and variables' weeks overlapping a period from `since`; `None` from a server from +/// before them. +fn asset_week_rows(s: &mut Session, link: &str, since: u64) -> Result>>> { + match s.library_request(link, LibraryReq::AssetActions) { + Ok(LibraryReply::AssetActions(w)) => Ok(Some(w.into_iter().filter(|w| w.week.saturating_add(7 * 86_400) > since).collect())), + Err(EngineError::Waiting) => Err(EngineError::Waiting), + _ => Ok(None), + } +} + +/// Each style's or variable's insertions and detachments in `weeks`. +fn asset_period(weeks: &[WeekActions]) -> std::collections::BTreeMap<&str, (u64, u64)> { + let mut per = std::collections::BTreeMap::<&str, (u64, u64)>::new(); + for w in weeks { + let e = per.entry(&w.component).or_default(); + e.0 += u64::from(w.insertions); + e.1 += u64::from(w.detachments); + } + per +} + +/// The style or variable reports' totals, the most used first: each one's `id`, `layers`, `files`, +/// `insertions` and `detachments` in the period, with what `describe` says of it (nothing for one +/// no longer published). One only inserted or detached is listed too, when it's of this kind. +fn asset_rows<'a>( + reports: impl Iterator>, + actions: &std::collections::BTreeMap<&str, (u64, u64)>, + describe: impl Fn(&str) -> Option, +) -> Vec { let mut per = std::collections::BTreeMap::<&str, (u64, u64)>::new(); for (id, n) in reports.flatten() { let e = per.entry(id).or_default(); e.0 += u64::from(*n); e.1 += 1; } + for id in actions.keys().filter(|id| describe(id).is_some()) { + per.entry(id).or_default(); + } let mut rows: Vec<_> = per.into_iter().collect(); rows.sort_by_key(|r| std::cmp::Reverse(r.1.0)); let row = |(id, (layers, files)): (&str, (u64, u64))| { let mut r = describe(id).unwrap_or_else(|| json!({})); + let (insertions, detachments) = actions.get(id).copied().unwrap_or_default(); (r["id"], r["layers"], r["files"]) = (json!(id), json!(layers), json!(files)); + (r["insertions"], r["detachments"]) = (json!(insertions), json!(detachments)); r }; rows.into_iter().map(row).collect() diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index 710eec76e..f5a0dd6a0 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -302,6 +302,10 @@ fn paragraph_style_of(n: &Node, range: Option<(usize, usize)>) -> Option Result { + crate::library::counting_links(s, true, |s| detach_style(s, p)) +} + +fn detach_style(s: &mut Session, p: &Value) -> Result { let cmd = "style.detach"; let which = req_string(cmd, p, "which")?; if which == "text" { @@ -458,6 +462,10 @@ pub fn apply_style_ref(doc: &mut Document, id: NodeId, field: &str, sid: Option< } pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { + crate::library::counting_links(s, false, |s| apply_style(s, p)) +} + +fn apply_style(s: &mut Session, p: &Value) -> Result { let cmd = "style.apply"; let st = req_string(cmd, p, "style")?; let style = s.doc()?.style(&st).cloned().ok_or_else(|| bad(cmd, format!("no style `{st}`")))?; @@ -846,6 +854,10 @@ pub fn sync_list_styles(doc: &mut Document, before: &Document, ids: &[NodeId]) { /// `variable.bind`: bind (or with no variable, unbind) `field` of the targets. pub fn bind(s: &mut Session, p: &Value) -> Result { + crate::library::counting_links(s, string(p, "variable").is_none(), |s| bind_field(s, p)) +} + +fn bind_field(s: &mut Session, p: &Value) -> Result { let cmd = "variable.bind"; let field = req_string(cmd, p, "field")?; let var = string(p, "variable"); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a74219fb6..3e4af48c3 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -404,6 +404,8 @@ mod keymap_tests; #[cfg(test)] mod layout_suggest_tests; #[cfg(test)] +mod library_asset_counts_tests; +#[cfg(test)] mod library_beacon_tests; #[cfg(test)] mod library_path_tests; diff --git a/crates/engine/src/library_asset_counts_tests.rs b/crates/engine/src/library_asset_counts_tests.rs new file mode 100644 index 000000000..faacb880c --- /dev/null +++ b/crates/engine/src/library_asset_counts_tests.rs @@ -0,0 +1,115 @@ +//! What a file counts as inserting and detaching a library's styles and variables, as the help +//! center's library analytics page says: applying one, or copying or duplicating content that uses +//! it, inserts it; the Detach button detaches it. Content that is an instance counts as the +//! instance alone, and local styles and variables count nothing. An undo takes its count back. + +use serde_json::{Value, json}; + +use crate::Session; +use crate::components::tests::{ex, idv}; +use crate::library_server::asset_actions; +use figcraft_doc::{AssetCount, NodeId, PublishedLibrary}; + +/// A file with a published library holding a paint style, a colour variable and a Card, and a +/// second file that uses it: the second session, the library's id and its keys. +fn user() -> (Session, String, Value) { + let mut a = Session::new(); + let r = idv(&ex(&mut a, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))); + let style = ex(&mut a, "style.create", json!({"type": "paint", "name": "Brand", "from": r.0})); + let coll = ex(&mut a, "variable.createCollection", json!({"name": "Tokens"})); + ex(&mut a, "variable.create", json!({"name": "Accent", "type": "color", "collection": coll["id"], "value": "#0D99FF"})); + let card = idv(&ex(&mut a, "frame.create", json!({"x": 0, "y": 100, "width": 100, "height": 40, "name": "Card"}))); + ex(&mut a, "style.apply", json!({"ids": [card.0], "style": style["id"]})); + ex(&mut a, "component.create", json!({"ids": [card.0]})); + ex(&mut a, "library.publish", json!({})); + let lib: PublishedLibrary = a.doc().unwrap().published.as_deref().unwrap().clone(); + let path = std::env::temp_dir().join(format!("figcraft-asset-counts-{}-{:?}.figcraft", std::process::id(), std::thread::current().id())); + ex(&mut a, "file.save", json!({"path": path.to_string_lossy()})); + let mut b = Session::new(); + let id = ex(&mut b, "library.add", json!({"path": path.to_string_lossy()}))["id"].as_str().unwrap().to_string(); + assert_eq!(lib.manifest.id, id); + (b, id, json!({"style": "Brand", "variable": "Accent"})) +} + +fn rect(s: &mut Session, x: i32) -> NodeId { + idv(&ex(s, "shape.rectangle", json!({"x": x, "y": 0, "width": 40, "height": 40}))) +} + +/// (inserted, detached) of the style and of the variable, as `doc` keeps them. +fn counts(s: &Session) -> ((u32, u32), (u32, u32)) { + let of = |key: &str| { + s.doc().unwrap().libraries.asset_counts.iter().find(|c: &&AssetCount| c.key.starts_with(key)).map_or((0, 0), |c| (c.inserted, c.detached)) + }; + (of("S:"), of("VariableID:")) +} + +#[test] +fn applying_counts_once_per_layer_that_takes_it() { + let (mut s, lib, _) = user(); + let (one, two) = (rect(&mut s, 0), rect(&mut s, 100)); + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0, two.0]})); + assert_eq!(counts(&s).0, (2, 0)); + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]})); + assert_eq!(counts(&s).0, (2, 0), "a layer that has it already adds nothing"); + let three = rect(&mut s, 200); + ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": [three.0], "field": "fill"})); + assert_eq!(counts(&s).1, (1, 0)); +} + +#[test] +fn duplicating_and_pasting_content_counts_what_it_uses() { + let (mut s, lib, _) = user(); + let one = rect(&mut s, 0); + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]})); + ex(&mut s, "select.set", json!({"ids": [one.0]})); + ex(&mut s, "edit.duplicate", json!({})); + assert_eq!(counts(&s).0, (2, 0), "the copy inserts it too"); + ex(&mut s, "select.set", json!({"ids": [one.0]})); + ex(&mut s, "edit.copy", json!({})); + ex(&mut s, "edit.paste", json!({})); + assert_eq!(counts(&s).0, (3, 0)); +} + +#[test] +fn an_instance_counts_as_its_component_alone() { + let (mut s, lib, _) = user(); + let i = idv(&ex(&mut s, "library.place", json!({"library": lib, "component": "Card", "x": 0, "y": 0}))); + assert_eq!(counts(&s).0, (0, 0), "placing it"); + ex(&mut s, "select.set", json!({"ids": [i.0]})); + ex(&mut s, "edit.duplicate", json!({})); + assert_eq!(counts(&s).0, (0, 0), "duplicating it"); + assert_eq!(s.doc().unwrap().libraries.inserted[0].count, 2); +} + +#[test] +fn only_the_detach_buttons_detach() { + let (mut s, lib, _) = user(); + let (one, two) = (rect(&mut s, 0), rect(&mut s, 100)); + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0, two.0]})); + ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": [two.0], "field": "stroke"})); + ex(&mut s, "style.detach", json!({"ids": [one.0, two.0], "which": "fill"})); + assert_eq!(counts(&s).0, (2, 2)); + ex(&mut s, "variable.bind", json!({"ids": [two.0], "field": "stroke"})); + assert_eq!(counts(&s).1, (1, 1)); + // Another style in its place isn't a detach of the first. + let local = ex(&mut s, "style.create", json!({"type": "paint", "name": "Mine", "from": one.0})); + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]})); + ex(&mut s, "style.apply", json!({"ids": [one.0], "style": local["id"]})); + assert_eq!(counts(&s).0, (3, 2)); +} + +#[test] +fn local_styles_count_nothing_and_undo_takes_a_count_back() { + let (mut s, lib, _) = user(); + let one = rect(&mut s, 0); + let local = ex(&mut s, "style.create", json!({"type": "paint", "name": "Mine", "from": one.0})); + ex(&mut s, "style.apply", json!({"ids": [one.0], "style": local["id"]})); + ex(&mut s, "style.detach", json!({"ids": [one.0], "which": "fill"})); + assert!(s.doc().unwrap().libraries.asset_counts.is_empty()); + assert!(asset_actions(s.doc().unwrap(), &lib).is_none()); + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]})); + let report = asset_actions(s.doc().unwrap(), &lib).unwrap(); + assert_eq!((report.inserted.len(), report.detached.len()), (1, 0)); + ex(&mut s, "edit.undo", json!({})); + assert_eq!(counts(&s).0, (0, 0)); +} diff --git a/crates/engine/src/sharing/background/tests.rs b/crates/engine/src/sharing/background/tests.rs index 6f98841df..cd9bc951c 100644 --- a/crates/engine/src/sharing/background/tests.rs +++ b/crates/engine/src/sharing/background/tests.rs @@ -98,10 +98,13 @@ fn library(w: &mut Wire, req: LibraryReq) -> LibraryReply { LibraryReply::Published { version: 1 } } (LibraryReq::Usage, _) => LibraryReply::Usage(Vec::new()), - (LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_), _) => LibraryReply::Noted, + (LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_) | LibraryReq::ReportAssetActions(_), _) => { + LibraryReply::Noted + } (LibraryReq::Detached, _) => LibraryReply::Detached(Vec::new()), (LibraryReq::Actions, _) => LibraryReply::Actions(Vec::new()), (LibraryReq::Assets, _) => LibraryReply::Assets(Vec::new()), + (LibraryReq::AssetActions, _) => LibraryReply::AssetActions(Vec::new()), } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index fcabb5d8f..fecdc3882 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -290,6 +290,8 @@ mod ui_params_tests; #[cfg(test)] mod ui_scale_tests; #[cfg(test)] +mod usage_summary_tests; +#[cfg(test)] mod variable_picker_tests; #[cfg(test)] mod variables_export_ui_tests; diff --git a/crates/ui-egui/src/panels/assets_panel.rs b/crates/ui-egui/src/panels/assets_panel.rs index 41f7762ff..4d516d50d 100644 --- a/crates/ui-egui/src/panels/assets_panel.rs +++ b/crates/ui-egui/src/panels/assets_panel.rs @@ -1028,22 +1028,32 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) { } let actions = v["actionsKnown"].as_bool().unwrap_or(false); let inserted_n = |n: u64| trn("{n} inserted", n as usize, &[]); - if actions { + let Some(kind) = usage_kind(ui, w, usage_id, &v) else { + ui.add_space(8.0); + return; + }; + if let Some((i, d)) = period_totals(&v, kind) { let label = USAGE_PERIODS.iter().find(|p| p.0 == days).map_or(USAGE_PERIODS[0].2, |p| p.2); - let (i, d) = (v["insertions"].as_u64().unwrap_or(0), v["detachments"].as_u64().unwrap_or(0)); let counts = trf("{insertions} · {detachments}", &[("insertions", &inserted_n(i)), ("detachments", &trn("{n} detached", d as usize, &[]))]); hint(ui, &trf("{period}: {counts}", &[("period", &tr(label)), ("counts", &counts)])); } else { hint(ui, tr("This server doesn't count insertions")); } - let Some(kind) = usage_kind(ui, w, usage_id, &v) else { - ui.add_space(8.0); - return; - }; + if v["assetsKnown"].as_bool() == Some(true) && v[kind].as_array().is_none_or(Vec::is_empty) { + hint(ui, tr("Nothing counted yet")); + } if kind != "components" { for a in v[kind].as_array().into_iter().flatten().take(USAGE_ROWS) { let (n, f) = (a["layers"].as_u64().unwrap_or(0), a["files"].as_u64().unwrap_or(0)); let counts = trf("{instances} in {files}", &[("instances", &trn("{n} layers", n as usize, &[])), ("files", &files_n(f))]); + // Inserted and detached in the period, after what it counts in all. + let (added, gone) = (a["insertions"].as_u64().unwrap_or(0), a["detachments"].as_u64().unwrap_or(0)); + let counts = if added > 0 { trf("{used} · {inserted}", &[("used", &counts), ("inserted", &inserted_n(added))]) } else { counts }; + let counts = if gone > 0 { + trf("{used} · {detached}", &[("used", &counts), ("detached", &trn("{n} detached", gone as usize, &[]))]) + } else { + counts + }; usage_row(ui, w, a["name"].as_str().unwrap_or(tr("(no longer published)")), &counts); } ui.add_space(8.0); @@ -1067,6 +1077,17 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) { ui.add_space(8.0); } +/// What the `kind` list of a Show usage answer adds up to in its period: insertions and +/// detachments, `None` from a server that doesn't count them for that kind. +pub(crate) fn period_totals(v: &Value, kind: &str) -> Option<(u64, u64)> { + let known = if kind == "components" { "actionsKnown" } else { "assetActionsKnown" }; + (v[known].as_bool() == Some(true)).then(|| { + let rows = v[kind].as_array().map_or(&[][..], Vec::as_slice); + let sum = |key: &str| rows.iter().filter_map(|r| r[key].as_u64()).sum(); + (sum("insertions"), sum("detachments")) + }) +} + /// Which list Show usage shows: `components`, `styles` or `variables` (a choice kept with the /// answer's `id`), `None` for nothing to list. A server from before style and variable reports /// shows just components, and says so. @@ -1092,11 +1113,7 @@ fn usage_kind(ui: &mut Ui, w: f32, id: Id, v: &Value) -> Option<&'static str> { }); }); ui.data_mut(|d| d.insert_temp(id, at)); - let kind = KINDS.get(at)?.0; - if v[kind].as_array().is_none_or(Vec::is_empty) { - hint(ui, tr("Nothing counted yet")); - } - Some(kind) + Some(KINDS.get(at)?.0) } /// A Show usage row: two lines, as the counts don't leave a name room on one. diff --git a/crates/ui-egui/src/usage_summary_tests.rs b/crates/ui-egui/src/usage_summary_tests.rs new file mode 100644 index 000000000..4a512cc85 --- /dev/null +++ b/crates/ui-egui/src/usage_summary_tests.rs @@ -0,0 +1,30 @@ +//! Show usage's period line sums the list the Type choice shows, so it never reads 0 above a list +//! with counts, and a server that doesn't count a kind says so for that kind alone. + +use serde_json::json; + +use crate::panels::assets_panel::period_totals; + +#[test] +fn the_period_line_sums_the_list_shown() { + let v = json!({ + "actionsKnown": true, + "assetActionsKnown": true, + "insertions": 0, + "detachments": 0, + "components": [], + "styles": [{"insertions": 3, "detachments": 1}, {"insertions": 2, "detachments": 0}], + "variables": [{"insertions": 1, "detachments": 4}], + }); + assert_eq!(period_totals(&v, "components"), Some((0, 0))); + assert_eq!(period_totals(&v, "styles"), Some((5, 1))); + assert_eq!(period_totals(&v, "variables"), Some((1, 4))); +} + +#[test] +fn a_server_that_doesnt_count_a_kind_has_no_totals_for_it() { + let v = json!({"actionsKnown": true, "components": [{"insertions": 2, "detachments": 1}], "styles": [{"layers": 3}]}); + assert_eq!(period_totals(&v, "components"), Some((2, 1))); + assert_eq!(period_totals(&v, "styles"), None, "a server from before them"); + assert_eq!(period_totals(&json!({}), "components"), None); +} diff --git a/docs/collab-protocol.md b/docs/collab-protocol.md index 41c73190d..a3e9ccae5 100644 --- a/docs/collab-protocol.md +++ b/docs/collab-protocol.md @@ -257,7 +257,7 @@ Client → server: | `Manage {protocol, key, client_version}` | Instead of `Hello`: manage a server's files with its key. | | `Admin {publish {name, snapshot} \| files \| links {file} \| createLink {file, access, label} \| revoke {file, link} \| remove {file}}` | A request on a managing connection; each gets one `Admin` reply, in order. | | `OpenLibrary {protocol, file, token, client_version}` | Instead of `Hello`: use a file's team library with one of the file's share links. | -| `Library {fetch {have?, usage?} \| publish {archive} \| usage \| reportDetached {file, components} \| detached \| reportInserted {file, components} \| actions \| reportAssets {file, styles, variables} \| assets}` | A request on a library connection; each gets one `Library` reply, in order. `usage` is `{file, components: [(id, instances)]}`; `reportDetached` gives the asking file's detached instances per component the same way (answered `noted`), `detached` asks for every file's. The last two are newer: a server from before them can't read them and refuses the request. | +| `Library {fetch {have?, usage?} \| publish {archive} \| usage \| reportDetached {file, components} \| detached \| reportInserted {file, components} \| actions \| reportAssets {file, styles, variables} \| assets \| reportAssetActions {file, inserted, detached} \| assetActions}` | A request on a library connection; each gets one `Library` reply, in order. `usage` is `{file, components: [(id, instances)]}`; `reportDetached` gives the asking file's detached instances per component the same way (answered `noted`), `detached` asks for every file's. The last two are newer: a server from before them can't read them and refuses the request. | | `Signal {kind, text}` | Ephemeral presence, only after the server's `ready`: `chat` (the cursor chat message; empty: closed), `spotlight` (`"on"`, or empty: stopped) or `name` (your new name: the server keeps it, cleaned like a hello's, and sends everyone, you too, your `PeerJoined`; never passed on as a signal). | | `OpenPlugins {protocol, key, client_version}` | Instead of `Hello`: use the server's plugin directory; `key` empty to browse, the server key to publish too. | | `OpenHosting {protocol, client_version, file, owner}` | Instead of `Hello`: ask about the server's hosting; publish without the key (`Admin publish`) when it is open to the public; with a file's id and owner token, manage that file (`Admin links \| createLink \| revoke \| rename \| remove` of it). Answered with `Hosting` or `Refused`. | @@ -279,7 +279,7 @@ Server → client: | `Refused {reason}` | The connection is refused (protocol version, token, session full, a message out of place). | | `Pong` | Keep-alive. | | `Admin {ready \| published {file, edit, view} \| files \| links \| link \| done \| failed {reason}}` | A managing connection's answer: the key is right, a published file with its first two links (tokens shown once), listings, a new link, done, or why not. | -| `Library {ready {access} \| library {version, archive} \| unchanged {version} \| empty \| published {version} \| usage [{usage, updated}] \| failed {reason} \| noted \| detached [{detached, updated}] \| actions [{week, component, insertions, detachments}] \| assets [{file, styles, variables}]}` | A library connection's answer: the link is right (with its access), the library (a `.figcraft` archive holding it), no newer version, no library yet, kept, the usage reports, or why not; then (newer) a detach report kept, and the detach reports. | +| `Library {ready {access} \| library {version, archive} \| unchanged {version} \| empty \| published {version} \| usage [{usage, updated}] \| failed {reason} \| noted \| detached [{detached, updated}] \| actions [{week, component, insertions, detachments}] \| assets [{file, styles, variables}] \| assetActions [{week, component, insertions, detachments}]}` | A library connection's answer: the link is right (with its access), the library (a `.figcraft` archive holding it), no newer version, no library yet, kept, the usage reports, or why not; then (newer) a detach report kept, and the detach reports. | | `Signal {client_id, signal: {kind, text}}` | Someone's cursor chat or spotlight, cleaned by the server; `ready` (about the client itself, after its welcome): signals may be sent. Only to clients whose hello announced `signals`. | | `Hosting {open, operator, terms, idle_secs, max_file_mb, expires?}` | The answer to `OpenHosting`, and after a welcome to clients whose hello announced `hosting`: anyone may publish, how to reach the operator, the terms (a URL), how long files published without the key are kept unopened, the largest file, and this file's expiry (seconds since 1970). | | `Admin {hosted {file, edit, view, owner, expires?} \| listing [row] \| reports [report] \| blocked [ip]}` | A file published without the key with its links and owner token (shown once), and the answers to the later managing requests. | @@ -848,7 +848,9 @@ resuming with its offline edits, and leaving the session going back to snapshot styles or variables sends `reportAssets` with how many of its layers use each (at most 250 of each kind, the most used first; none is a report too, so a file that stops using them stops counting); the server keeps the latest in the same `usage.json` entry and answers `assets` with - them. The variants are appended to the enums, so the older messages keep their bytes; an older server refuses the new + them. It sends `reportAssetActions` with its totals of inserted and detached styles and variables, + counted over the weeks as for components (`asset-actions.json`), and `assetActions` answers with + those weeks (`component` is the style's or variable's id). The variants are appended to the enums, so the older messages keep their bytes; an older server refuses the new requests, and the app ignores that. *Built* (the plugin directory; operating it: [`server.md`](server.md#plugin-directory), publishing and diff --git a/docs/components-parity.md b/docs/components-parity.md index 73d1d8ced..bb2a3e2ab 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -1,6 +1,6 @@ # Components, variants, styles and variables parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (combining components gives every variant the properties any of them had; renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (library analytics count insertions and detachments of styles and variables; combining components gives every variant the properties any of them had; renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); 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 @@ -54,7 +54,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Go to main component from an instance of a library component | done | opens the library file in a tab, or brings it to the front, on the page holding the main, selected and zoomed to; a variant goes to that variant. Team libraries on a server are refused with a note; no Return to instance yet | | Library updates available; overrides kept | done | a library file saved again within two seconds of being read, at the same length, is read again (its time stamp can't prove it unchanged; #652) | | Team libraries: publish to a `figcraft-server` under the file, enable by a share link (a view link reads it), background update checks | done | [server.md](server.md#team-libraries); no team-wide library list or accounts ([gaps](gaps.md) #10) | -| Library analytics | partial | instances per component and the files using them, and the instances each file detached (per component and per file), as apps report them; insertions and detachments week by week for a year (Show usage: the past 30 days, 90 days or year), for components; the layers and files using each style and variable, without insertions, detachments or modes; no chart | +| Library analytics | partial | instances per component and the files using them, and the instances each file detached (per component and per file), as apps report them; insertions and detachments week by week for a year (Show usage: the past 30 days, 90 days or year), for components; the layers and files using each style and variable, with their insertions and detachments over the same periods, no modes; no chart | | Swap library (instances, styles and variables to another library's of the same names, overrides kept) | done | what has no match stays and is listed; one undo step | ## Styles and variables @@ -80,6 +80,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. | | 2026-11-18 | patch | M3: Combine as variants gives every variant the component properties any of the components had (as a property added to a set goes to all its variants); a property made on one component before combining was missing from the others, so their layers couldn't be bound to it and an instance switched to them dropped its value. A variant with a property of the same name keeps its own. Tests: `variant_shared_props_tests`. | | 2026-11-18 | patch | M3, #2368: a text field that isn't being edited ends a value too long for it with an ellipsis and shows the whole value on hover (a secret field shows none), so the variant value "Down left" no longer reads "Down lef"; screen readers and editing keep the whole value (`field_ellipsis_tests`). Grade unchanged. | | 2026-11-14 | patch | M3, #2354: the Local variables window resizes from its edges and corners, width and height (minimum 600 x 240), and keeps its size and place while the app runs. | diff --git a/docs/gaps.md b/docs/gaps.md index 8e1d60686..bb3ede386 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where FigCraft falls short of Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: 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; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; 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; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (gap 10: library analytics count insertions and detachments of styles and variables; gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: 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; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; 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; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The @@ -23,7 +23,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | 7 | CPU canvas where Figma uses the GPU | Hardware/performance | 30–60 | [hardware-parity](hardware-parity.md) | | 8 | Platform QA: Linux and the browser left (Windows pass done 2026-10-11) | Stability/platforms | 10–20 | [hardware-parity](hardware-parity.md) | | 9 | Figma Draw: pen pressure on macOS/Linux tablets (multi-edit, brushes, pressure, text on a path and pattern fills landed) | Feature | 1–3 | [target-app-parity](target-app-parity.md) | -| 10 | Team libraries: no team-wide lists or accounts; analytics count insertions for components only | Feature | 4–8 | [components-parity](components-parity.md) | +| 10 | Team libraries: no team-wide lists or accounts; analytics don't count modes | Feature | 4–8 | [components-parity](components-parity.md) | | 11 | Spell check | Feature | 4–8 | [target-app-parity](target-app-parity.md) | | 12 | Video fills; HEIC images | File format | 5–10 | [file-format-parity](file-format-parity.md) | | 13 | Vector tail: none left (boolean hit testing on the result landed 2026-10-11) | Feature | — | [target-app-parity](target-app-parity.md) | @@ -378,11 +378,10 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe - **Impact:** illustration-flavoured work moved into Figma Draw in 2025. - **Estimate:** 1–3 h once winit (or a platform tablet API behind it) reports pressure there. -### 10. Team libraries: no team-wide lists or accounts; analytics count insertions for components only +### 10. Team libraries: no team-wide lists or accounts; analytics don't count modes - **Missing:** libraries listed for a whole team or organization (each file enables a library by - its link), accounts and per-person library permissions, insertions, detachments and mode counts for - styles and variables (they count layers and files using them; a component's instances, - insertions and detachments are counted, the last two week by week), + its link), accounts and per-person library permissions, mode counts (a component's instances and a style's + or variable's layers are counted, with their insertions and detachments week by week), update notices pushed by the server (apps ask every 30 seconds while the Assets panel shows). - **Evidence:** a file's library is published to `figcraft-server` under the file and enabled in other files by a share link, with per-asset versions, updates with overrides kept, usage counts @@ -618,6 +617,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | Gap 10: library analytics count insertions and detachments of styles and variables; modes stay on the missing list. | | 2026-11-18 | minor | Gap 6: the plugin directory works in the browser build, so that item leaves the missing list; what's installed there lasts as long as the page. Team libraries on a server work there too. | | 2026-11-17 | minor | Gap 7: a pan past the canvas image shows a coarse image of the area around the view (desktop), not the bare page colour; `canvas.uncovered` in `ui.inspect`. Numbers unchanged. Tests: `surround_tests`, `background::tests::the_image_around_the_view_fills_what_the_render_leaves_and_the_page_colour_the_rest` | | 2026-11-17 | minor | Gap 7: the strips a pan uncovers render in parallel bands (rows of a tall strip, columns of a wide one), 3–5× quicker pans on effect-heavy pages. Numbers unchanged. Tests: `band_tests::columns_match_one_piece_rendering`, `band_tests::a_tall_or_wide_part_of_a_view_matches_one_piece_rendering`; timings: `pan_bench_tests` | diff --git a/docs/mcp.md b/docs/mcp.md index 0a557c6b2..8940fa184 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1028,7 +1028,7 @@ most when it can't be reached). `library.acceptUpdates` takes it, overrides kept. The app's own background checks ask only about team libraries added (`library.add`) or checked (`library.check {library?}`) on this computer, so opening a file that names another one contacts nothing (#1097). -- `library.usage {library?, days?}` → `{id, name, assetsKnown, styles [{id, name, type, layers, files}], variables [{id, name, collection, layers, files}], instances, detached, detachesKnown, days, +- `library.usage {library?, days?}` → `{id, name, assetsKnown, assetActionsKnown, styles [{id, name, type, layers, files, insertions, detachments}], variables [{id, name, collection, layers, files, insertions, detachments}], instances, detached, detachesKnown, days, insertions, detachments, actionsKnown, weeks: [{week, insertions, detachments}], files: [{name, updated, instances, detached}], components: [{id, name, instances, files, detached, insertions, detachments}]}`: what the files using it reported (each fetch reports the asking document's name diff --git a/docs/roadmap.md b/docs/roadmap.md index 78f4d4df3..b797063a6 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # FigCraft roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (the browser build uses team libraries and plugin directories on a server; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; 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); 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; 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); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); 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); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); 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; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); 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; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (library analytics count insertions and detachments of styles and variables; the browser build uses team libraries and plugin directories on a server; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; 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); 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; 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); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); 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); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); 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; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); 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; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) Forward-looking plan. Where FigCraft stands today: [`ROADMAP.md`](../ROADMAP.md) and [`target-app-parity.md`](target-app-parity.md); the full ranked list: [`gaps.md`](gaps.md). Hours @@ -76,6 +76,7 @@ blockers. | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-10 | minor | Zoomed-out images: the canvas's copies of an image shown smaller than its pixels now also come at 256, 512, 1024 and 2048 px, the smallest that holds what the screen shows, and images of 4096 px or less get them too (they were drawn from the image itself at any size). On a page of 237 photos, about 4.6 GB decoded against the 512 MB cache, every zoomed-out render decoded them again: 3.4 s a frame at 1% before, 0.9 s the first time and 4 ms after; peak memory 3.9 → 2.3 GB. Exports, and images shown at their own size or larger, still draw from the image itself. | | 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. | diff --git a/docs/server.md b/docs/server.md index 37f0182d9..c7cbe3093 100644 --- a/docs/server.md +++ b/docs/server.md @@ -254,8 +254,9 @@ which other files use without anyone copying the library file around. layers use each of the library's styles and variables. **Show usage** in the library file (`library.usage`) lists the files and the instances and detaches of each component, the insertions and detachments of the past 30 days, 90 days or year, and, by its Type choice, the - layers and files using each style and variable. Layers inside instances count for their - component. Files are + layers and files using each style and variable with their insertions and detachments. Applying + a style or variable, or copying or duplicating content that uses it, inserts it, and the Detach + button detaches it. Layers inside instances count for their component. Files are told apart by their names; a file's report changes only when its usage does. The server counts what a file's totals grow past their highest in the week it hears of it, keeps a year of weeks, and counts an undo and a redo once. A server from before these counts refuses the reports From 64b662b86983fb302644ba450be53222c2615e22 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 31 Oct 2026 10:04:21 +0700 Subject: [PATCH 032/114] M3: Show usage's rows are drawn by small helpers --- crates/ui-egui/src/panels/assets_panel.rs | 85 ++++++++++++++--------- 1 file changed, 52 insertions(+), 33 deletions(-) diff --git a/crates/ui-egui/src/panels/assets_panel.rs b/crates/ui-egui/src/panels/assets_panel.rs index 4d516d50d..9d58a81c5 100644 --- a/crates/ui-egui/src/panels/assets_panel.rs +++ b/crates/ui-egui/src/panels/assets_panel.rs @@ -1014,27 +1014,19 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) { }; let files = v["files"].as_array().map_or(0, Vec::len); let instances = v["instances"].as_u64().unwrap_or(0); - let files_n = |n: u64| trn("{n} files", n as usize, &[]); - let instances_n = |n: u64| trn("{n} instances", n as usize, &[]); - // Detached instances, beside what they are counted with (a server from before them keeps none). let known = v["detachesKnown"].as_bool().unwrap_or(false); - let with_detached = |used: String, n: u64| { - if known && n > 0 { trf("{used} · {detached}", &[("used", &used), ("detached", &trn("{n} detached", n as usize, &[]))]) } else { used } - }; let used = trf("Used in {files} · {instances}", &[("files", &files_n(files as u64)), ("instances", &instances_n(instances))]); - hint(ui, &with_detached(used, v["detached"].as_u64().unwrap_or(0))); + hint(ui, &with_detached(known, used, v["detached"].as_u64().unwrap_or(0))); if !known { hint(ui, tr("This server doesn't count detached instances")); } - let actions = v["actionsKnown"].as_bool().unwrap_or(false); - let inserted_n = |n: u64| trn("{n} inserted", n as usize, &[]); let Some(kind) = usage_kind(ui, w, usage_id, &v) else { ui.add_space(8.0); return; }; if let Some((i, d)) = period_totals(&v, kind) { let label = USAGE_PERIODS.iter().find(|p| p.0 == days).map_or(USAGE_PERIODS[0].2, |p| p.2); - let counts = trf("{insertions} · {detachments}", &[("insertions", &inserted_n(i)), ("detachments", &trn("{n} detached", d as usize, &[]))]); + let counts = trf("{insertions} · {detachments}", &[("insertions", &inserted_n(i)), ("detachments", &detached_n(d))]); hint(ui, &trf("{period}: {counts}", &[("period", &tr(label)), ("counts", &counts)])); } else { hint(ui, tr("This server doesn't count insertions")); @@ -1042,39 +1034,66 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) { if v["assetsKnown"].as_bool() == Some(true) && v[kind].as_array().is_none_or(Vec::is_empty) { hint(ui, tr("Nothing counted yet")); } - if kind != "components" { - for a in v[kind].as_array().into_iter().flatten().take(USAGE_ROWS) { - let (n, f) = (a["layers"].as_u64().unwrap_or(0), a["files"].as_u64().unwrap_or(0)); - let counts = trf("{instances} in {files}", &[("instances", &trn("{n} layers", n as usize, &[])), ("files", &files_n(f))]); - // Inserted and detached in the period, after what it counts in all. - let (added, gone) = (a["insertions"].as_u64().unwrap_or(0), a["detachments"].as_u64().unwrap_or(0)); - let counts = if added > 0 { trf("{used} · {inserted}", &[("used", &counts), ("inserted", &inserted_n(added))]) } else { counts }; - let counts = if gone > 0 { - trf("{used} · {detached}", &[("used", &counts), ("detached", &trn("{n} detached", gone as usize, &[]))]) - } else { - counts - }; - usage_row(ui, w, a["name"].as_str().unwrap_or(tr("(no longer published)")), &counts); - } - ui.add_space(8.0); - return; + if kind == "components" { + component_rows(ui, w, &v, known); + } else { + asset_rows(ui, w, &v, kind); } + ui.add_space(8.0); +} + +fn files_n(n: u64) -> String { + trn("{n} files", n as usize, &[]) +} + +fn instances_n(n: u64) -> String { + trn("{n} instances", n as usize, &[]) +} + +fn inserted_n(n: u64) -> String { + trn("{n} inserted", n as usize, &[]) +} + +fn detached_n(n: u64) -> String { + trn("{n} detached", n as usize, &[]) +} + +/// `used`, with the detached instances beside it (a server from before them keeps none: `known`). +fn with_detached(known: bool, used: String, n: u64) -> String { + if known && n > 0 { trf("{used} · {detached}", &[("used", &used), ("detached", &detached_n(n))]) } else { used } +} + +/// `used`, with the insertions counted in the period after it. +fn with_inserted(used: String, n: u64) -> String { + if n > 0 { trf("{used} · {inserted}", &[("used", &used), ("inserted", &inserted_n(n))]) } else { used } +} + +/// Show usage's rows for a style or variable list. +fn asset_rows(ui: &mut Ui, w: f32, v: &Value, kind: &str) { + for a in v[kind].as_array().into_iter().flatten().take(USAGE_ROWS) { + let (n, f) = (a["layers"].as_u64().unwrap_or(0), a["files"].as_u64().unwrap_or(0)); + let counts = trf("{instances} in {files}", &[("instances", &trn("{n} layers", n as usize, &[])), ("files", &files_n(f))]); + let counts = with_detached(true, with_inserted(counts, a["insertions"].as_u64().unwrap_or(0)), a["detachments"].as_u64().unwrap_or(0)); + usage_row(ui, w, a["name"].as_str().unwrap_or(tr("(no longer published)")), &counts); + } +} + +/// Show usage's rows for the components; `known`: the server counts detached instances. +fn component_rows(ui: &mut Ui, w: f32, v: &Value, known: bool) { + let actions = v["actionsKnown"].as_bool().unwrap_or(false); for c in v["components"].as_array().into_iter().flatten().take(USAGE_ROWS) { let name = c["name"].as_str().unwrap_or(tr("(no longer published)")); let (n, f) = (c["instances"].as_u64().unwrap_or(0), c["files"].as_u64().unwrap_or(0)); let gone = c["detached"].as_u64().unwrap_or(0); // A component only detached (no instances left anywhere) says just that. let right = if n == 0 && known && gone > 0 { - trn("{n} detached", gone as usize, &[]) + detached_n(gone) } else { - with_detached(trf("{instances} in {files}", &[("instances", &instances_n(n)), ("files", &files_n(f))]), gone) + with_detached(known, trf("{instances} in {files}", &[("instances", &instances_n(n)), ("files", &files_n(f))]), gone) }; - // Inserted in the period, after what the component counts in all. - let added = c["insertions"].as_u64().unwrap_or(0); - let right = if actions && added > 0 { trf("{used} · {inserted}", &[("used", &right), ("inserted", &inserted_n(added))]) } else { right }; - usage_row(ui, w, name, &right); + let added = if actions { c["insertions"].as_u64().unwrap_or(0) } else { 0 }; + usage_row(ui, w, name, &with_inserted(right, added)); } - ui.add_space(8.0); } /// What the `kind` list of a Show usage answer adds up to in its period: insertions and From b63368e39cbd3a2a3df630b2021027c7763fb44a Mon Sep 17 00:00:00 2001 From: bflatastic Date: Wed, 18 Nov 2026 14:08:11 +0700 Subject: [PATCH 033/114] M3: a style or variable applied or detached inside an instance counts nothing counting_links compared library_links, which walked every node, so applying or detaching a library style or variable on an instance or a layer in it counted, while duplicating that instance counts only its component. library_links now walks the pages and skips instances with what they hold, as count_inserted does. Test: library_asset_counts_tests::applying_and_detaching_inside_an_instance_counts_nothing (an instance, its layer, a nested instance and its layer). The server test waits for the detachments too, not only the insertions. --- .../src/library_assets_tests.rs | 7 +++- crates/engine/src/assets/library.rs | 15 +++++-- .../engine/src/library_asset_counts_tests.rs | 41 ++++++++++++++++++- 3 files changed, 58 insertions(+), 5 deletions(-) diff --git a/apps/figcraft-server/src/library_assets_tests.rs b/apps/figcraft-server/src/library_assets_tests.rs index 4da1aba8d..5941e4980 100644 --- a/apps/figcraft-server/src/library_assets_tests.rs +++ b/apps/figcraft-server/src/library_assets_tests.rs @@ -165,7 +165,12 @@ fn inserts_and_detaches_count_per_style_and_variable_in_the_period() { ex(&mut b, "style.detach", json!({"ids": [two.0], "which": "fill"})); ex(&mut b, "library.bindVariable", json!({"library": lid, "variable": "Accent", "ids": [two.0], "field": "fill"})); - let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["insertions"] == 2 && u["variables"][0]["insertions"] == 1); + let u = usage_when(&mut a, &mut b, |u| { + u["assetActionsKnown"] == true + && u["styles"][0]["insertions"] == 2 + && u["styles"][0]["detachments"] == 1 + && u["variables"][0]["insertions"] == 1 + }); assert_eq!(u["assetActionsKnown"], true, "{u}"); assert_eq!(u["styles"][0]["detachments"], 1, "{u}"); assert_eq!(u["variables"][0]["detachments"], 0, "{u}"); diff --git a/crates/engine/src/assets/library.rs b/crates/engine/src/assets/library.rs index 5c8baa1f1..054710464 100644 --- a/crates/engine/src/assets/library.rs +++ b/crates/engine/src/assets/library.rs @@ -93,14 +93,23 @@ fn asset_record<'a>(doc: &'a Document, local: &str) -> Option<&'a ImportedRecord doc.libraries.styles.iter().chain(&doc.libraries.variables).find(|r| r.local == local) } -/// How many layers link to each local copy of a library style or variable. +/// How many layers link to each local copy of a library style or variable. An instance and the +/// layers in it don't count: an instance counts as its component alone, as in [`count_inserted`]. fn library_links(doc: &Document) -> BTreeMap { let mut links = BTreeMap::new(); if doc.libraries.styles.is_empty() && doc.libraries.variables.is_empty() { return links; } - for local in doc.nodes().flat_map(asset_links).filter(|l| asset_record(doc, l).is_some()) { - *links.entry(local.to_string()).or_default() += 1; + let mut stack = doc.pages.clone(); + while let Some(id) = stack.pop() { + let Some(n) = doc.node(id) else { continue }; + if matches!(n.kind, NodeKind::Instance { .. }) { + continue; + } + stack.extend(n.children.iter().copied()); + for local in asset_links(n).into_iter().filter(|l| asset_record(doc, l).is_some()) { + *links.entry(local.to_string()).or_default() += 1; + } } links } diff --git a/crates/engine/src/library_asset_counts_tests.rs b/crates/engine/src/library_asset_counts_tests.rs index faacb880c..e0f4fe456 100644 --- a/crates/engine/src/library_asset_counts_tests.rs +++ b/crates/engine/src/library_asset_counts_tests.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; use crate::Session; use crate::components::tests::{ex, idv}; use crate::library_server::asset_actions; -use figcraft_doc::{AssetCount, NodeId, PublishedLibrary}; +use figcraft_doc::{AssetCount, NodeId, NodeKind, PublishedLibrary}; /// A file with a published library holding a paint style, a colour variable and a Card, and a /// second file that uses it: the second session, the library's id and its keys. @@ -81,6 +81,45 @@ fn an_instance_counts_as_its_component_alone() { assert_eq!(s.doc().unwrap().libraries.inserted[0].count, 2); } +/// Applying and detaching a library style or variable on an instance, on a layer in it, or on a +/// layer of an instance nested in it counts nothing either: what an instance uses counts as it. +#[test] +fn applying_and_detaching_inside_an_instance_counts_nothing() { + let (mut s, lib, _) = user(); + let placed = idv(&ex(&mut s, "library.place", json!({"library": lib, "component": "Card", "x": 0, "y": 0}))); + // A Button holding a rectangle and an Icon instance (the Icon holds a dot), and a Button instance. + let icon = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 200, "width": 24, "height": 24, "name": "Icon"}))); + ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 8, "height": 8, "parent": icon.0})); + let icon = idv(&ex(&mut s, "component.create", json!({"ids": [icon.0]}))); + let button = idv(&ex(&mut s, "frame.create", json!({"x": 100, "y": 200, "width": 80, "height": 40, "name": "Button"}))); + ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 80, "height": 40, "parent": button.0})); + ex(&mut s, "instance.create", json!({"component": icon.0, "parent": button.0, "x": 4, "y": 4})); + let button = idv(&ex(&mut s, "component.create", json!({"ids": [button.0]}))); + let i = idv(&ex(&mut s, "instance.create", json!({"component": button.0, "x": 300, "y": 200}))); + let (layer, nested, deep) = { + let d = s.doc().unwrap(); + let kids = |id: NodeId| d.node(id).unwrap().children.clone(); + let nested = kids(i).into_iter().find(|k| matches!(d.node(*k).unwrap().kind, NodeKind::Instance { .. })).unwrap(); + let layer = kids(i).into_iter().find(|k| *k != nested).unwrap(); + (layer, nested, kids(nested)[0]) + }; + let targets = [placed.0, i.0, layer.0, nested.0, deep.0]; + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": targets})); + ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": targets, "field": "stroke"})); + let d = s.doc().unwrap(); + assert!(d.node(deep).unwrap().styles.fill.is_some() && !d.node(deep).unwrap().bound.is_empty(), "the nested layer took both"); + ex(&mut s, "style.detach", json!({"ids": targets, "which": "fill"})); + ex(&mut s, "variable.bind", json!({"ids": targets, "field": "stroke"})); + assert_eq!(counts(&s), ((0, 0), (0, 0))); + // The same on a plain layer counts. + let plain = rect(&mut s, 600); + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [plain.0]})); + ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": [plain.0], "field": "stroke"})); + ex(&mut s, "style.detach", json!({"ids": [plain.0], "which": "fill"})); + ex(&mut s, "variable.bind", json!({"ids": [plain.0], "field": "stroke"})); + assert_eq!(counts(&s), ((1, 1), (1, 1))); +} + #[test] fn only_the_detach_buttons_detach() { let (mut s, lib, _) = user(); From 2b175686ba290bcb64b158945f7e353b92e74168 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Wed, 18 Nov 2026 19:16:42 +0700 Subject: [PATCH 034/114] M3: Show usage's answer is drawn by its own function, tested --- crates/ui-egui/src/panels/assets_panel.rs | 22 +++++--- crates/ui-egui/src/usage_summary_tests.rs | 63 ++++++++++++++++++++++- 2 files changed, 75 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/panels/assets_panel.rs b/crates/ui-egui/src/panels/assets_panel.rs index 9d58a81c5..9ee6c0dfe 100644 --- a/crates/ui-egui/src/panels/assets_panel.rs +++ b/crates/ui-egui/src/panels/assets_panel.rs @@ -1008,10 +1008,16 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) { }); app.run_background(&ui.ctx().clone(), USAGE, json!({"days": period.unwrap_or(days)}), done); } - let Some(v) = shown else { - ui.add_space(8.0); - return; - }; + match shown { + Some(v) => usage_answer(ui, w, usage_id, &v), + None => ui.add_space(8.0), + } +} + +/// Show usage's answer `v`: what uses the library, the period's insertions and detachments and +/// the rows of the list chosen (the choice kept with `id`). +pub(crate) fn usage_answer(ui: &mut Ui, w: f32, id: Id, v: &Value) { + let days = v["days"].as_u64().unwrap_or(USAGE_PERIODS[0].0); let files = v["files"].as_array().map_or(0, Vec::len); let instances = v["instances"].as_u64().unwrap_or(0); let known = v["detachesKnown"].as_bool().unwrap_or(false); @@ -1020,11 +1026,11 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) { if !known { hint(ui, tr("This server doesn't count detached instances")); } - let Some(kind) = usage_kind(ui, w, usage_id, &v) else { + let Some(kind) = usage_kind(ui, w, id, v) else { ui.add_space(8.0); return; }; - if let Some((i, d)) = period_totals(&v, kind) { + if let Some((i, d)) = period_totals(v, kind) { let label = USAGE_PERIODS.iter().find(|p| p.0 == days).map_or(USAGE_PERIODS[0].2, |p| p.2); let counts = trf("{insertions} · {detachments}", &[("insertions", &inserted_n(i)), ("detachments", &detached_n(d))]); hint(ui, &trf("{period}: {counts}", &[("period", &tr(label)), ("counts", &counts)])); @@ -1035,9 +1041,9 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) { hint(ui, tr("Nothing counted yet")); } if kind == "components" { - component_rows(ui, w, &v, known); + component_rows(ui, w, v, known); } else { - asset_rows(ui, w, &v, kind); + asset_rows(ui, w, v, kind); } ui.add_space(8.0); } diff --git a/crates/ui-egui/src/usage_summary_tests.rs b/crates/ui-egui/src/usage_summary_tests.rs index 4a512cc85..e9ce53fb9 100644 --- a/crates/ui-egui/src/usage_summary_tests.rs +++ b/crates/ui-egui/src/usage_summary_tests.rs @@ -1,9 +1,11 @@ //! Show usage's period line sums the list the Type choice shows, so it never reads 0 above a list -//! with counts, and a server that doesn't count a kind says so for that kind alone. +//! with counts, and a server that doesn't count a kind says so for that kind alone. The answer draws +//! its totals, its period and the rows of the list chosen. use serde_json::json; -use crate::panels::assets_panel::period_totals; +use crate::live_tests::{flat, has_text}; +use crate::panels::assets_panel::{period_totals, usage_answer}; #[test] fn the_period_line_sums_the_list_shown() { @@ -28,3 +30,60 @@ fn a_server_that_doesnt_count_a_kind_has_no_totals_for_it() { assert_eq!(period_totals(&v, "styles"), None, "a server from before them"); assert_eq!(period_totals(&json!({}), "components"), None); } + +/// The texts Show usage draws for the answer `v` with the Type choice at `kind` (0 components, +/// 1 styles, 2 variables). +fn drawn(v: &serde_json::Value, kind: usize) -> Vec { + let ctx = egui::Context::default(); + let id = egui::Id::new("usage"); + ctx.data_mut(|d| d.insert_temp(id.with("kind"), kind)); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| usage_answer(ui, 600.0, id, v)); + out.textures_delta.clear(); + flat(&out.shapes) +} + +#[test] +fn show_usage_draws_the_totals_the_period_and_the_list_chosen() { + let v = json!({ + "days": 90, + "files": [{}, {}], + "instances": 5, + "detachesKnown": true, + "detached": 3, + "actionsKnown": true, + "assetActionsKnown": true, + "assetsKnown": true, + "components": [ + {"name": "Button", "instances": 4, "files": 2, "detached": 2, "insertions": 6, "detachments": 2}, + {"name": "Gone", "instances": 0, "files": 0, "detached": 3}, + ], + "styles": [{"name": "Brand", "layers": 7, "files": 3, "insertions": 2, "detachments": 0}], + "variables": [], + }); + let components = drawn(&v, 0); + for text in [ + "Used in 2 files · 5 instances · 3 detached", + "Past 90 days: 6 inserted · 2 detached", + "4 instances in 2 files · 2 detached · 6 inserted", + "3 detached", + ] { + assert!(has_text(&components, text), "{text}"); + } + let styles = drawn(&v, 1); + assert!(has_text(&styles, "Past 90 days: 2 inserted · 0 detached")); + assert!(has_text(&styles, "7 layers in 3 files · 2 inserted")); + assert!(has_text(&drawn(&v, 2), "Nothing counted yet"), "an empty list says so"); +} + +#[test] +fn show_usage_from_an_older_server_says_what_it_doesnt_count() { + let shapes = drawn(&json!({"files": [{}, {}], "instances": 5, "components": []}), 0); + for text in [ + "Used in 2 files · 5 instances", + "This server doesn't count detached instances", + "This server doesn't count styles and variables", + "This server doesn't count insertions", + ] { + assert!(has_text(&shapes, text), "{text}"); + } +} From 9e45db68859a0709b64cf93fb43994f7fcab1503 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:06:35 +0700 Subject: [PATCH 035/114] Keep asset-action peaks when usage rows evict, and report every count CodeRabbit's majors on #1735: evicting a file from the capped usage list dropped asset_peaks, so a later identical report was counted twice. Retention now includes asset_updated, and the file just heard from is kept even when timestamps tie. The document keeps up to 1000 asset counts, but each wire message is still capped at 250, so reports are sent in batches an older server will accept. Tests: evicting_capped_usage_rows_keeps_asset_peaks_so_a_repeat_report_is_not_counted_twice and asset_action_reports_cover_every_count_past_the_message_cap. Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com> --- .../src/library_assets_tests.rs | 36 +++++++++++++++++- apps/figcraft-server/src/store.rs | 5 ++- apps/figcraft-server/src/store/library.rs | 18 +++++++-- crates/engine/src/assets/library_server.rs | 38 ++++++++++++++++--- .../engine/src/library_asset_counts_tests.rs | 33 +++++++++++++++- 5 files changed, 118 insertions(+), 12 deletions(-) diff --git a/apps/figcraft-server/src/library_assets_tests.rs b/apps/figcraft-server/src/library_assets_tests.rs index 5941e4980..d5d6744e9 100644 --- a/apps/figcraft-server/src/library_assets_tests.rs +++ b/apps/figcraft-server/src/library_assets_tests.rs @@ -5,12 +5,15 @@ use std::time::{Duration, Instant}; -use figcraft_collab::message::{Access, AssetUsage, ClientMsg, LibraryReply, LibraryReq, MAX_ASSET_USAGE, OpenLibrary, PROTOCOL, ServerMsg}; +use figcraft_collab::message::{ + Access, AssetActions, AssetUsage, ClientMsg, LibraryReply, LibraryReq, MAX_ASSET_USAGE, OpenLibrary, PROTOCOL, ServerMsg, Usage, +}; use figcraft_collab_net::Invite; use figcraft_doc::NodeId; use figcraft_engine::Session; use serde_json::{Value, json}; +use crate::store::{MAX_USERS, Store}; use crate::test_util::{Raw, TempDir, config, publish, session}; fn ex(s: &mut Session, cmd: &str, p: Value) -> Value { @@ -185,3 +188,34 @@ fn inserts_and_detaches_count_per_style_and_variable_in_the_period() { assert_eq!(u["variables"][0]["insertions"], 1, "{u}"); server.stop(); } + +#[test] +fn evicting_capped_usage_rows_keeps_asset_peaks_so_a_repeat_report_is_not_counted_twice() { + let dir = TempDir::new("library-asset-peaks-evict"); + let cfg = config(dir.path()); + let mut server = crate::start(&cfg).unwrap(); + let addr = server.addr(); + let mut a = session("Ada"); + let r = rect(&mut a, 0); + ex(&mut a, "style.create", json!({"type": "paint", "name": "Brand", "from": r.0})); + let p = publish(&mut a, dir.path(), addr); + ex(&mut a, "library.publishToServer", json!({})); + let file = Invite::parse(&p.edit).unwrap().file; + server.stop(); + drop(server); + + let mut store = Store::open(dir.path(), cfg.store()).unwrap(); + for i in 0..MAX_USERS { + store.report_usage(&file, Usage { file: format!("Old{i}"), components: Vec::new() }).unwrap(); + } + let actions = AssetActions { file: "Kept".into(), inserted: vec![("Brand".into(), 2)], detached: Vec::new() }; + store.report_asset_actions(&file, actions.clone()).unwrap(); + // One more usage-only file would evict "Kept" if asset activity did not count for retention. + store.report_usage(&file, Usage { file: "Extra".into(), components: Vec::new() }).unwrap(); + store.report_asset_actions(&file, actions).unwrap(); + let weeks = store.library_asset_actions(&file).unwrap(); + let brand: Vec<_> = weeks.iter().filter(|w| w.component == "Brand").collect(); + assert_eq!(brand.len(), 1, "{weeks:?}"); + assert_eq!(brand[0].insertions, 2, "lost peaks would grow the same totals again: {weeks:?}"); + assert_eq!(brand[0].detachments, 0, "{weeks:?}"); +} diff --git a/apps/figcraft-server/src/store.rs b/apps/figcraft-server/src/store.rs index fbf4bc2db..d75a24f1b 100644 --- a/apps/figcraft-server/src/store.rs +++ b/apps/figcraft-server/src/store.rs @@ -103,7 +103,7 @@ pub const NO_PUBLIC_LIBRARY: &str = "on this public server only files published /// Most files whose usage of one library is kept (the least recently changed go first), and most /// components one file's report keeps. -const MAX_USERS: usize = 200; +pub(crate) const MAX_USERS: usize = 200; const MAX_REPORTED: usize = 1_000; /// Largest `usage.json` (and `actions.json`) read. const MAX_USAGE_FILE: u64 = 16 << 20; @@ -325,6 +325,9 @@ struct UsageEntry { variables: Vec<(String, u32)>, #[serde(default, skip_serializing_if = "Vec::is_empty")] asset_peaks: Vec<(String, u32, u32)>, + /// When this file last reported style or variable insertions or detachments (seconds since 1970, UTC). + #[serde(default, skip_serializing_if = "is_zero")] + asset_updated: u64, } fn is_zero(n: &u64) -> bool { diff --git a/apps/figcraft-server/src/store/library.rs b/apps/figcraft-server/src/store/library.rs index 10337a451..4cb32f4e6 100644 --- a/apps/figcraft-server/src/store/library.rs +++ b/apps/figcraft-server/src/store/library.rs @@ -256,7 +256,13 @@ impl Store { let mut grown = Vec::new(); self.report(file, &actions.file, known_assets(counts), |e, counts| { grown = grow(&mut e.asset_peaks, &counts, kind, |_| 0); - !grown.is_empty() + if grown.is_empty() { + return false; + } + // Heard from for retention: evicting the row would drop asset_peaks, the + // baseline grow uses so a later identical report is not counted twice. + e.asset_updated = now(); + true })?; if let (false, Some(u)) = (grown.is_empty(), self.usage.get_mut(file)) { add_to_week(&mut u.asset_weeks, &grown, kind, now()); @@ -329,7 +335,7 @@ impl Store { let at = match u.list.iter().position(|e| e.usage.file == name) { Some(at) => at, None => { - u.list.push(UsageEntry { usage: Usage { file: name, components: Vec::new() }, ..UsageEntry::default() }); + u.list.push(UsageEntry { usage: Usage { file: name.clone(), components: Vec::new() }, ..UsageEntry::default() }); u.list.len() - 1 } }; @@ -338,7 +344,13 @@ impl Store { return Ok(()); } if u.list.len() > MAX_USERS { - u.list.sort_by_key(|e| std::cmp::Reverse(e.updated.max(e.detached_updated))); + // The file just heard from stays, even when several share a timestamp (now() is + // seconds). Asset-action reports use asset_updated so their peaks are not dropped + // in favour of a usage-only row from the same second. + u.list.sort_by_key(|e| { + let recent = e.usage.file == name; + std::cmp::Reverse((e.updated.max(e.detached_updated).max(e.asset_updated), recent)) + }); u.list.truncate(MAX_USERS); } u.dirty = true; diff --git a/crates/engine/src/assets/library_server.rs b/crates/engine/src/assets/library_server.rs index 3d42e7c98..f8ddf0e50 100644 --- a/crates/engine/src/assets/library_server.rs +++ b/crates/engine/src/assets/library_server.rs @@ -124,14 +124,42 @@ pub fn asset_usage(doc: &Document, library: &str) -> Option { } /// How many times `doc` has inserted and detached `library`'s styles and variables, its totals; -/// `None` when it has done neither. +/// `None` when it has done neither. Every count the document keeps is included (up to +/// [`figcraft_doc::MAX_DETACH_COUNTS`]); the wire message is capped at [`MAX_ASSET_USAGE`], so +/// [`asset_action_reports`] splits them into batches an older server still accepts. pub fn asset_actions(doc: &Document, library: &str) -> Option { let counts: Vec<_> = doc.libraries.asset_counts.iter().filter(|c| c.library == library).collect(); - let totals = - |n: fn(&figcraft_doc::AssetCount) -> u32| counts.iter().filter(|c| n(c) > 0).map(|c| (c.key.clone(), n(c))).take(MAX_ASSET_USAGE).collect(); + let totals = |n: fn(&figcraft_doc::AssetCount) -> u32| counts.iter().filter(|c| n(c) > 0).map(|c| (c.key.clone(), n(c))).collect(); (!counts.is_empty()).then(|| AssetActions { file: doc.name.clone(), inserted: totals(|c| c.inserted), detached: totals(|c| c.detached) }) } +/// Reports for the server, each with at most [`MAX_ASSET_USAGE`] inserted and detached counts. +pub fn asset_action_reports(doc: &Document, library: &str) -> Vec { + let Some(full) = asset_actions(doc, library) else { return Vec::new() }; + chunk_asset_actions(full) +} + +fn chunk_asset_actions(actions: AssetActions) -> Vec { + let AssetActions { file, inserted, detached } = actions; + if inserted.is_empty() && detached.is_empty() { + return Vec::new(); + } + let mut out = Vec::new(); + let mut i = 0; + let mut d = 0; + loop { + let ins: Vec<_> = inserted.get(i..).unwrap_or(&[]).iter().take(MAX_ASSET_USAGE).cloned().collect(); + let det: Vec<_> = detached.get(d..).unwrap_or(&[]).iter().take(MAX_ASSET_USAGE).cloned().collect(); + if ins.is_empty() && det.is_empty() { + break; + } + i += ins.len(); + d += det.len(); + out.push(AssetActions { file: file.clone(), inserted: ins, detached: det }); + } + out +} + /// `counts`, the most used first, at most [`MAX_ASSET_USAGE`]. fn most_used(counts: BTreeMap<&str, u32>) -> Vec<(String, u32)> { let mut list: Vec<(String, u32)> = counts.into_iter().map(|(k, n)| (k.to_string(), n)).collect(); @@ -279,10 +307,10 @@ impl Session { detached(doc, &l.id).map(LibraryReq::ReportDetached), inserted(doc, &l.id).map(LibraryReq::ReportInserted), asset_usage(doc, &l.id).map(LibraryReq::ReportAssets), - asset_actions(doc, &l.id).map(LibraryReq::ReportAssetActions), ]; + let asset_reports = asset_action_reports(doc, &l.id).into_iter().map(LibraryReq::ReportAssetActions); let fetch = LibraryReq::Fetch { have, usage: Some(usage(doc, &l.id)) }; - std::iter::once(fetch).chain(reports.into_iter().flatten()).map(|req| (l.path.clone(), req)) + std::iter::once(fetch).chain(reports.into_iter().flatten()).chain(asset_reports).map(|req| (l.path.clone(), req)) }) .collect(); // Confined to automation roots, nothing reaches a server (#1095). diff --git a/crates/engine/src/library_asset_counts_tests.rs b/crates/engine/src/library_asset_counts_tests.rs index e0f4fe456..1eb3a1403 100644 --- a/crates/engine/src/library_asset_counts_tests.rs +++ b/crates/engine/src/library_asset_counts_tests.rs @@ -7,8 +7,9 @@ use serde_json::{Value, json}; use crate::Session; use crate::components::tests::{ex, idv}; -use crate::library_server::asset_actions; -use figcraft_doc::{AssetCount, NodeId, NodeKind, PublishedLibrary}; +use crate::library_server::{asset_action_reports, asset_actions}; +use figcraft_collab::message::MAX_ASSET_USAGE; +use figcraft_doc::{AssetCount, Document, NodeId, NodeKind, PublishedLibrary}; /// A file with a published library holding a paint style, a colour variable and a Card, and a /// second file that uses it: the second session, the library's id and its keys. @@ -152,3 +153,31 @@ fn local_styles_count_nothing_and_undo_takes_a_count_back() { ex(&mut s, "edit.undo", json!({})); assert_eq!(counts(&s).0, (0, 0)); } + +#[test] +fn asset_action_reports_cover_every_count_past_the_message_cap() { + let mut doc = Document::new("File"); + let n = MAX_ASSET_USAGE + 1; + let libraries = std::sync::Arc::make_mut(&mut doc.libraries); + for i in 0..n { + let key = format!("s{i}"); + libraries.count_asset("Lib", &key, false, 1); + libraries.count_asset("Lib", &key, true, 2); + } + // Another library's counts do not belong in these reports. + libraries.count_asset("Other", "x", false, 9); + libraries.count_asset("Other", "x", true, 9); + + let full = asset_actions(&doc, "Lib").unwrap(); + assert_eq!(full.inserted.len(), n, "the document's counts are not truncated"); + assert_eq!(full.detached.len(), n); + + let reports = asset_action_reports(&doc, "Lib"); + assert!(reports.len() >= 2, "one message cannot carry {n} counts"); + assert!(reports.iter().all(|r| r.file == "File" && r.inserted.len() <= MAX_ASSET_USAGE && r.detached.len() <= MAX_ASSET_USAGE)); + let inserted: Vec<_> = reports.iter().flat_map(|r| r.inserted.iter().cloned()).collect(); + let detached: Vec<_> = reports.iter().flat_map(|r| r.detached.iter().cloned()).collect(); + assert_eq!(inserted, full.inserted); + assert_eq!(detached, full.detached); + assert!(asset_action_reports(&doc, "Missing").is_empty()); +} From 23e5877e6bd4a9c451e227dbcc16a322c427c07f Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:04:11 +0700 Subject: [PATCH 036/114] Wait for style layers to clear, and cover a full asset-peak cap inserts_and_detaches_count_per_style_and_variable_in_the_period returned as soon as detachments reached 2, then asserted layers == 0. Asset-action reports can arrive before the usage snapshot, so CI saw layers still at 1. The wait now requires both. Sonar on the same-repo vehicle (#2451) evaluated the coverage gate at 79.74% of 232 new lines (one line under 80%). A unit test covers grow's branch that drops a new key once peaks are already at MAX_REPORTED. Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com> --- apps/figcraft-server/src/library_assets_tests.rs | 2 +- apps/figcraft-server/src/store/library.rs | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/apps/figcraft-server/src/library_assets_tests.rs b/apps/figcraft-server/src/library_assets_tests.rs index d5d6744e9..9cbf24e1d 100644 --- a/apps/figcraft-server/src/library_assets_tests.rs +++ b/apps/figcraft-server/src/library_assets_tests.rs @@ -183,7 +183,7 @@ fn inserts_and_detaches_count_per_style_and_variable_in_the_period() { ex(&mut b, "edit.undo", json!({})); ex(&mut b, "edit.redo", json!({})); ex(&mut b, "style.detach", json!({"ids": [one.0], "which": "fill"})); - let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["detachments"] == 2); + let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["detachments"] == 2 && u["styles"][0]["layers"] == 0); assert_eq!((u["styles"][0]["insertions"].clone(), u["styles"][0]["layers"].clone()), (json!(2), json!(0)), "{u}"); assert_eq!(u["variables"][0]["insertions"], 1, "{u}"); server.stop(); diff --git a/apps/figcraft-server/src/store/library.rs b/apps/figcraft-server/src/store/library.rs index 4cb32f4e6..42d284b04 100644 --- a/apps/figcraft-server/src/store/library.rs +++ b/apps/figcraft-server/src/store/library.rs @@ -390,3 +390,17 @@ fn library_file(dir: &Path, version: u64) -> PathBuf { let path = dir.join(library_name(version)); if path.exists() { path } else { dir.join(LIBRARY) } } + +#[cfg(test)] +mod grow_tests { + use super::*; + + #[test] + fn a_new_key_is_dropped_once_peaks_are_full() { + let mut peaks: Vec<(u32, u32, u32)> = (0..MAX_REPORTED as u32).map(|i| (i, 1, 0)).collect(); + let grown = grow(&mut peaks, &[(MAX_REPORTED as u32, 3)], Count::Inserted, |_| 0); + assert!(grown.is_empty(), "a key past the cap must not start a peak or count as growth"); + assert_eq!(peaks.len(), MAX_REPORTED); + assert!(peaks.iter().all(|p| p.0 < MAX_REPORTED as u32)); + } +} From 6c63071241a78c807d71b23e4a155123cb9ed22b Mon Sep 17 00:00:00 2001 From: bflatastic Date: Wed, 18 Nov 2026 19:27:59 +0700 Subject: [PATCH 037/114] M3: the Show usage test keys its choice with Id::unique --- crates/ui-egui/src/usage_summary_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/usage_summary_tests.rs b/crates/ui-egui/src/usage_summary_tests.rs index e9ce53fb9..72941743f 100644 --- a/crates/ui-egui/src/usage_summary_tests.rs +++ b/crates/ui-egui/src/usage_summary_tests.rs @@ -35,7 +35,7 @@ fn a_server_that_doesnt_count_a_kind_has_no_totals_for_it() { /// 1 styles, 2 variables). fn drawn(v: &serde_json::Value, kind: usize) -> Vec { let ctx = egui::Context::default(); - let id = egui::Id::new("usage"); + let id = egui::Id::unique("usage_summary_tests"); ctx.data_mut(|d| d.insert_temp(id.with("kind"), kind)); let mut out = ctx.run_ui(egui::RawInput::default(), |ui| usage_answer(ui, 600.0, id, v)); out.textures_delta.clear(); From e94ecfca7a2ebc6c427a0ed58ed5f9e082298906 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 14 Nov 2026 20:44:01 -0500 Subject: [PATCH 038/114] M5: the arrow keys move a layer along the canvas axes inside a rotated parent (#2372) transform.nudge applied the step in the parent's local space, so Down inside a frame rotated 90 degrees moved the layer sideways. The step is now turned into the parent's space first (falling back to the plain step if the parent's transform is not invertible). Auto layout children are unchanged. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/engine/src/cmd/edit.rs | 2 + .../cmd/edit/nudge_rotated_parent_tests.rs | 92 +++++++++++++++++++ crates/engine/src/cmd/edit/select.rs | 13 ++- docs/ui-parity.md | 3 +- 4 files changed, 108 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/edit/nudge_rotated_parent_tests.rs diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 00a237c21..cc2391ef5 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -20,6 +20,8 @@ mod select; mod vector_clipboard; pub use vector_clipboard::clipboard_svg; #[cfg(test)] +mod nudge_rotated_parent_tests; +#[cfg(test)] mod vector_clipboard_tests; pub(crate) use clipboard::apply_copied_props; diff --git a/crates/engine/src/cmd/edit/nudge_rotated_parent_tests.rs b/crates/engine/src/cmd/edit/nudge_rotated_parent_tests.rs new file mode 100644 index 000000000..f1ab3ba48 --- /dev/null +++ b/crates/engine/src/cmd/edit/nudge_rotated_parent_tests.rs @@ -0,0 +1,92 @@ +//! The arrow keys move a layer along the canvas axes whatever its parent's rotation (#2372). + +use serde_json::{Value, json}; + +use crate::Session; +use crate::params::id_of; +use figcraft_doc::NodeId; + +fn frame(s: &mut Session, parent: Option, w: f64, h: f64, rotation: f64) -> NodeId { + let mut p = json!({"x": 10, "y": 20, "width": w, "height": h}); + if let (Some(par), Some(o)) = (parent, p.as_object_mut()) { + o.insert("parent".into(), json!(par)); + } + let r = s.execute("frame.create", &p).unwrap(); + let id = id_of(&r["id"]).unwrap(); + if rotation != 0.0 { + s.execute("node.set", &json!({"id": id, "props": {"rotation": rotation}})).unwrap(); + } + id +} + +fn world(s: &Session, id: NodeId) -> (f64, f64) { + let c = s.doc().unwrap().world_transform(id).as_coeffs(); + (c[4], c[5]) +} + +fn nudge(s: &mut Session, id: NodeId, params: Value) { + let mut p = params; + if let Some(o) = p.as_object_mut() { + o.insert("ids".into(), json!([id])); + } + s.execute("transform.nudge", &p).unwrap(); +} + +fn moved_by(s: &mut Session, id: NodeId, params: Value) -> (f64, f64) { + let before = world(s, id); + nudge(s, id, params); + let after = world(s, id); + (after.0 - before.0, after.1 - before.1) +} + +fn near(got: (f64, f64), want: (f64, f64)) { + assert!((got.0 - want.0).abs() < 1e-6 && (got.1 - want.1).abs() < 1e-6, "moved by {got:?}, wanted {want:?}"); +} + +fn in_rotated(rotation: f64) -> (Session, NodeId) { + let mut s = Session::new(); + let outer = frame(&mut s, None, 400.0, 300.0, rotation); + let child = frame(&mut s, Some(outer), 100.0, 80.0, 0.0); + (s, child) +} + +#[test] +fn down_moves_a_child_of_a_frame_rotated_90_down_the_canvas() { + let (mut s, child) = in_rotated(90.0); + let k = s.prefs.nudge_small; + near(moved_by(&mut s, child, json!({"dx": 0, "dy": 1})), (0.0, k)); +} + +#[test] +fn right_moves_it_right_on_the_canvas() { + let (mut s, child) = in_rotated(90.0); + let k = s.prefs.nudge_small; + near(moved_by(&mut s, child, json!({"dx": 1, "dy": 0})), (k, 0.0)); +} + +#[test] +fn a_big_nudge_in_a_rotated_parent_follows_the_canvas_too() { + let (mut s, child) = in_rotated(90.0); + let k = s.prefs.nudge_big; + near(moved_by(&mut s, child, json!({"dx": 1, "dy": 0, "big": true})), (k, 0.0)); +} + +#[test] +fn a_child_of_an_unrotated_frame_moves_as_before() { + let (mut s, child) = in_rotated(0.0); + let k = s.prefs.nudge_small; + let local_before = s.doc().unwrap().node(child).unwrap().transform.as_coeffs(); + near(moved_by(&mut s, child, json!({"dx": 1, "dy": 0})), (k, 0.0)); + let local_after = s.doc().unwrap().node(child).unwrap().transform.as_coeffs(); + assert!((local_after[4] - local_before[4] - k).abs() < 1e-6 && (local_after[5] - local_before[5]).abs() < 1e-6); +} + +#[test] +fn a_layer_two_rotated_frames_deep_moves_along_the_canvas() { + let mut s = Session::new(); + let outer = frame(&mut s, None, 500.0, 400.0, 45.0); + let inner = frame(&mut s, Some(outer), 300.0, 200.0, 30.0); + let child = frame(&mut s, Some(inner), 100.0, 80.0, 0.0); + let k = s.prefs.nudge_small; + near(moved_by(&mut s, child, json!({"dx": 0, "dy": 1})), (0.0, k)); +} diff --git a/crates/engine/src/cmd/edit/select.rs b/crates/engine/src/cmd/edit/select.rs index 17f80af6b..9d8fa822e 100644 --- a/crates/engine/src/cmd/edit/select.rs +++ b/crates/engine/src/cmd/edit/select.rs @@ -184,8 +184,19 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { // Children in an auto layout flow move one place instead (see `al_keys`). for i in &ids { if crate::al_keys::flowing_parent(doc, *i).is_none() && (dx, dy) != (0.0, 0.0) { + // The step is along the canvas axes; the layer's transform is in its parent's space. + let (lx, ly) = match doc.node(*i).and_then(|n| n.parent) { + Some(par) => { + let inv = doc.world_transform(par).inverse(); + let o = inv * figcraft_geom::Point::new(0.0, 0.0); + let q = inv * figcraft_geom::Point::new(dx, dy); + let (lx, ly) = (q.x - o.x, q.y - o.y); + if lx.is_finite() && ly.is_finite() { (lx, ly) } else { (dx, dy) } + } + None => (dx, dy), + }; let n = doc.get_mut(*i)?; - n.transform = Affine::translate((dx, dy)) * n.transform; + n.transform = Affine::translate((lx, ly)) * n.transform; changed = true; } } diff --git a/docs/ui-parity.md b/docs/ui-parity.md index dac2960bd..f05c3e244 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -71,7 +71,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's move and rotation (the move of its centre in the page frame, then the turn about the copy's own centre, or the selection's centre for several layers; not its size), also after a Duplicate whose copy was moved, as long as the copies stay selected and the selection hasn't changed (measured in Figma's web app, 2026-11-12); Alt going down or up mid-drag turns the move into a copy or back to the original, with Shift a copy kept to one axis (`alt_pressed_during_a_drag_turns_the_move_into_a_copy`, `alt_shift_drag_on_a_selected_layer_duplicates_it`; measured in Figma's web app, 2026-11-08) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | | Scale tool (K): handles about the opposite handle, live factor, panel | done | Dragging a handle ignores the origin grid and pivots on the opposite handle's point (the opposite corner, or the opposite edge's middle for an edge, which scales both ways), with Alt on the centre; the origin grid (`tool.scaleAnchor`) starts at the centre and sets only what the Scale field and the W and H fields keep fixed (W and H with a non-centre origin are unmeasured). Measured in Figma's web app, 2026-11-09. Tests: `a_scale_handle_drag_pivots_on_the_opposite_handle_whatever_the_origin`, `the_scale_origin_starts_at_the_centre`. Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin, which starts at the centre, as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`. | -| Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | +| Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children; the arrow keys move along the canvas axes inside a rotated parent, as in Figma, #2372 | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; the object snap threshold is 4.5 screen pixels, measured against Figma (snapped at a gap of 4.4 screen px, not at 4.6, at 100% and 200% zoom, 2026-11-08; the equal-spacing snap shares it), but the ruler-guide and rotation-origin thresholds (5 px), the red guide's look and snapping with Snap to pixel grid off are not yet compared with Figma's (`guide_snap_tests`, `transform_behaviour_tests`) | | 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) | @@ -210,6 +210,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-18 | patch | M5, #2372: the arrow keys move a layer along the canvas axes inside a rotated parent (the step was applied along the parent's axes, so Down moved a child of a frame rotated 90 degrees sideways); auto layout children are unchanged | | 2026-11-18 | patch | M1, #2355: Cmd/Ctrl+V with one layer inside a frame selected pasted the copy onto the page on top of the frame; it now goes into the layer's parent just above it (in an auto layout frame, the item after it, so the layout grows), keeping today's behaviour for a page-level layer, several layers, an instance's children and a board atom. Tests: `paste_sibling_tests` (5) | | 2026-11-08 | minor | M8, #2109: in vector edit mode the Align commands (`align.left` to `align.bottom`, Alt+A/H/D/W/V/S) and Distribute horizontal and vertical spacing act on the selected points when neither `ids` nor `id` is given (either one targets layers), as in Figma (measured in Figma on 2026-11-08): each point moves along one axis only, to its box's left, horizontal centre, right, top, vertical centre or bottom, and distribute spaces the points evenly between the outermost two in order along the axis; handles go with their vertex, a single point stays, with no point selected nothing moves (the layer is not aligned to its frame, as measured in Figma), and one undo restores them. The Design panel draws the alignment row first, with a Distribute menu from three points. Numbers unchanged. | | 2026-11-08 | patch | Number fields: scrubbing a label moves half a step a point, not a step, as measured in Figma (X from 100: +6 for a 12.2 px drag, +31 for 61.2 px; rotation 6° and opacity 5% for 12.2 px); Shift (x10), Alt (x0.1) and the speed by height are kept on top of it and were not measured, and no field's scrub direction changed | From 4806b95e8e529b7a77a26a04364dffcc35971645 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 14 Nov 2026 22:52:12 -0500 Subject: [PATCH 039/114] M5: a drag from a child of a selected frame moves the frame (#2360) A press on a layer inside a selected one now drags the selection, and a click without a drag selects that layer (also in Dev Mode and for a single selection), as in Figma. Cmd/Ctrl, Shift and layers outside the selection are unchanged. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/engine/src/canvas/tools.rs | 4 +- crates/engine/src/canvas/tools/drag.rs | 18 +++-- crates/engine/src/canvas/tools/draw.rs | 5 +- .../engine/src/selection_behaviour_tests.rs | 68 +++++++++++++++++++ docs/ui-parity.md | 3 +- 5 files changed, 89 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index 86418b814..c60483fcf 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -444,8 +444,8 @@ pub(crate) enum Gesture { /// A Shift-press on this selected layer: it leaves the selection on release, unless the /// press became a drag. deselect: Option, - /// A press on one layer of a multi-selection that keeps the selection to drag it all: a - /// release without a drag selects just this layer. + /// A press on one layer of a multi-selection, or on a layer inside a selected one, that + /// keeps the selection to drag it all: a release without a drag selects just this layer. keep: Option, }, Resize { diff --git a/crates/engine/src/canvas/tools/drag.rs b/crates/engine/src/canvas/tools/drag.rs index b41613f97..9e19c57f2 100644 --- a/crates/engine/src/canvas/tools/drag.rs +++ b/crates/engine/src/canvas/tools/drag.rs @@ -92,8 +92,14 @@ impl Session { // inside, the frame or canvas behind it, or a layer stacked below the selected layer the // press is in) drags the selection. In a gap between selected layers, what's there is hit. let in_own_box = |s: NodeId| selection_box(&doc, &[s]).is_some_and(|q| in_quad(&q, ev.p())); + // A press on a layer inside a selected one (a child of a selected frame) drags the + // selection too, and a click selects that layer; Cmd/Ctrl keeps the deep pick. + let in_selected = |t: NodeId| sel.iter().any(|s| *s != t && doc.is_ancestor(*s, t)); let behind_sel = |t: Option| { - t.is_none_or(|t| sel.iter().any(|s| *s != t && (doc.is_ancestor(t, *s) || (in_own_box(*s) && paints_below(&doc, t, *s))))) + t.is_none_or(|t| { + (!ev.cmd && in_selected(t)) + || sel.iter().any(|s| *s != t && (doc.is_ancestor(t, *s) || (in_own_box(*s) && paints_below(&doc, t, *s)))) + }) }; // What the press hit (a label or a painted layer): a click that doesn't become a drag // selects just it. A press that reaches nothing above the selection uses the selection as @@ -116,8 +122,12 @@ impl Session { let without_target = || sel.iter().copied().filter(|x| *x != target).collect::>(); // A release without a drag narrows the selection to the layer the press hit. A // selected frame's name label sits outside the selection bounds, so it counts too. - let keep = clicked - .filter(|c| (label.is_some() || in_sel_box) && !ev.cmd && (sel.contains(c) || sel.iter().any(|s| doc.is_ancestor(*s, *c)))); + // A layer inside a selected one counts as well: the press drags the selection, and + // a click selects that layer. + let keep = clicked.filter(|c| { + !ev.cmd + && (((label.is_some() || in_sel_box) && (sel.contains(c) || sel.iter().any(|s| doc.is_ancestor(*s, *c)))) || in_selected(*c)) + }); let new_sel = if keep.is_some() { sel.clone() } else if ev.shift && deselect.is_none() { @@ -135,7 +145,7 @@ impl Session { if !edits { if deselect.is_some() { self.set_selection(without_target()); - } else if let Some(k) = keep.filter(|_| sel.len() > 1) { + } else if let Some(k) = keep.filter(|k| sel.as_slice() != [*k]) { self.set_selection(vec![k]); } return Ok(()); diff --git a/crates/engine/src/canvas/tools/draw.rs b/crates/engine/src/canvas/tools/draw.rs index 43110681c..dea4aab47 100644 --- a/crates/engine/src/canvas/tools/draw.rs +++ b/crates/engine/src/canvas/tools/draw.rs @@ -176,10 +176,11 @@ impl Session { let sel = self.selection().into_iter().filter(|x| *x != d).collect(); self.set_selection(sel); } else if let Some(k) = keep { - // A click (not a drag) on one layer of a multi-selection selects just it. + // A click (not a drag) on one layer of a multi-selection, or on a layer + // inside a selected one, selects just it. let doc = self.doc()?.clone(); let sel = self.selection(); - if sel.len() > 1 && (sel.contains(&k) || sel.iter().any(|s| doc.is_ancestor(*s, k))) { + if sel.as_slice() != [k] && (sel.contains(&k) || sel.iter().any(|s| doc.is_ancestor(*s, k))) { self.set_selection(vec![k]); } } diff --git a/crates/engine/src/selection_behaviour_tests.rs b/crates/engine/src/selection_behaviour_tests.rs index 0499996ff..b2aed52cf 100644 --- a/crates/engine/src/selection_behaviour_tests.rs +++ b/crates/engine/src/selection_behaviour_tests.rs @@ -562,3 +562,71 @@ fn shift_click_takes_a_layer_out_where_nothing_can_move() { s.pointer(&ev(PointerKind::Up, 520.0, 20.0, SHIFT)).unwrap(); assert_eq!(s.selection(), vec![k.empty], "Shift-click still takes the layer out"); } + +/// A top-level 300 x 300 frame with a filled 100 x 100 rectangle at (50, 50) and a nested frame +/// at (200, 200 80x80) holding a rectangle at (210, 210 40x40). +fn frame_with_child(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) { + let f = id(&ex(s, "frame.create", json!({"x": 0, "y": 0, "width": 300, "height": 300}))); + let c = id(&ex(s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100, "parent": f}))); + let n = id(&ex(s, "frame.create", json!({"x": 180, "y": 180, "width": 100, "height": 100, "parent": f}))); + let gc = id(&ex(s, "shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 40, "parent": n}))); + (f, c, n, gc) +} + +#[test] +fn a_drag_from_a_child_of_a_selected_frame_moves_the_frame() { + let mut s = Session::new(); + let (f, c, _n, gc) = frame_with_child(&mut s); + let sib = id(&ex(&mut s, "shape.rectangle", json!({"x": 90, "y": 90, "width": 30, "height": 30}))); + let at = |s: &Session, i: NodeId| s.doc().unwrap().world_bounds(i).unwrap().origin(); + let local = |s: &Session, i: NodeId| { + let d = s.doc().unwrap(); + let n = d.node(i).unwrap(); + let c = n.transform.as_coeffs(); + (c[4], c[5]) + }; + let c_local = local(&s, c); + // (selection before, press point, modifiers, selection after, the layers that move by (10, 10), derivation) + let rows: Vec<(Vec, (f64, f64), Mods, Vec, Vec, &str)> = vec![ + (vec![f], (60.0, 60.0), NONE, vec![f], vec![f, c, gc], "a drag from a child of the selected frame moves the frame"), + (vec![f], (220.0, 220.0), NONE, vec![f], vec![f, c, gc], "a drag from a grandchild moves the top-level frame"), + (vec![], (60.0, 60.0), NONE, vec![c], vec![c], "with nothing selected the child is picked and moved"), + (vec![f], (60.0, 60.0), CMD, vec![c], vec![c], "Cmd picks the deepest layer and moves it"), + (vec![f], (100.0, 100.0), NONE, vec![sib], vec![sib], "a sibling painted above the frame takes the press"), + ]; + for (before, from, m, after, moved, why) in rows { + let all = [f, c, gc, sib]; + let home: Vec = all.iter().map(|i| at(&s, *i)).collect(); + ex(&mut s, "select.set", json!({"ids": before})); + drag(&mut s, from, (from.0 + 10.0, from.1 + 10.0), m); + assert_eq!(sorted(s.selection()), sorted(after), "{why}"); + for (i, h) in all.iter().zip(&home) { + // The frame carries its children: they move in the world, not in their local space. + let d = if moved.contains(i) { 10.0 } else { 0.0 }; + assert_eq!(at(&s, *i), Point::new(h.x + d, h.y + d), "{why}"); + } + assert_eq!(local(&s, c), if moved == [c] { (c_local.0 + 10.0, c_local.1 + 10.0) } else { c_local }, "{why}: the child's local position"); + assert!(s.undo().unwrap(), "{why}: one undo step"); + for (i, h) in all.iter().zip(&home) { + assert_eq!(at(&s, *i), *h, "{why}: undo restores"); + } + } +} + +#[test] +fn a_click_on_a_child_of_a_selected_frame_selects_the_child() { + let mut s = Session::new(); + let (f, c, n, gc) = frame_with_child(&mut s); + let home = s.doc().unwrap().world_bounds(c).unwrap().origin(); + for (p, want) in [((60.0, 60.0), c), ((190.0, 190.0), n)] { + ex(&mut s, "select.set", json!({"ids": [f]})); + click(&mut s, p.0, p.1, NONE); + assert_eq!(s.selection(), vec![want], "a click selects the layer inside the selected frame"); + } + assert_eq!(s.doc().unwrap().world_bounds(c).unwrap().origin(), home, "nothing moved"); + let _ = gc; + s.tool.dev_mode = true; + ex(&mut s, "select.set", json!({"ids": [f]})); + click(&mut s, 60.0, 60.0, NONE); + assert_eq!(s.selection(), vec![c], "in Dev Mode too"); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f05c3e244..94ad714ae 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -57,7 +57,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Item | Status | Notes | |---|---|---| -| Click, Shift-click, marquee, Shift-marquee toggle | done | Shift-drag on a selected layer moves the selection, kept to the dominant axis with no 45° snap (#498; `shift_drag_moves_the_selection`; measured in Figma's web app, 2026-11-08); a marquee selects the top-level layers it touches, by the box and a rotated shape by its outline (rectangle and ellipse measured, the other shapes by the same code); a partly covered top-level frame or section gives the layers in it the marquee touches, an enclosed one is selected itself, an empty frame on touch; a drag from a frame's background selects that frame only when the marquee also takes another top-level frame (then whole), and also takes what it touches outside it; selecting a frame whole keeps the marquee at the top level (a partly covered frame then comes whole too); locked and hidden layers are skipped (`marquee_behaviour_tests`, `selection_behaviour_tests`; measured in Figma's web app, 2026-11-11; Shift and Cmd/Ctrl marquees not measured) (a locked layer selected from the panel ignores the arrow keys and the nudge commands; its properties still edit; measured in Figma's web app, 2026-11-10) | +| Click, Shift-click, marquee, Shift-marquee toggle | done | Shift-drag on a selected layer moves the selection, kept to the dominant axis with no 45° snap (#498; `shift_drag_moves_the_selection`; measured in Figma's web app, 2026-11-08); with a frame selected, a drag that starts on one of its children moves the frame and a click selects the child, as in Figma (#2360; `a_drag_from_a_child_of_a_selected_frame_moves_the_frame`, `a_click_on_a_child_of_a_selected_frame_selects_the_child`); a marquee selects the top-level layers it touches, by the box and a rotated shape by its outline (rectangle and ellipse measured, the other shapes by the same code); a partly covered top-level frame or section gives the layers in it the marquee touches, an enclosed one is selected itself, an empty frame on touch; a drag from a frame's background selects that frame only when the marquee also takes another top-level frame (then whole), and also takes what it touches outside it; selecting a frame whole keeps the marquee at the top level (a partly covered frame then comes whole too); locked and hidden layers are skipped (`marquee_behaviour_tests`, `selection_behaviour_tests`; measured in Figma's web app, 2026-11-11; Shift and Cmd/Ctrl marquees not measured) (a locked layer selected from the panel ignores the arrow keys and the nudge commands; its properties still edit; measured in Figma's web app, 2026-11-10) | | Deep select (Cmd/Ctrl-click, Cmd/Ctrl-marquee) | done | | | Select layer menu (every layer under the click) | done | shown only with more than one layer under the pointer; locked layers are listed with a padlock in the leading column and are selectable there, as Lock and unlock layers' note says (measured in Figma's web app, 2026-11-10; the "more than one layer" gate was measured on a single locked layer only) (`select_layer_marks_locked_layers_with_a_padlock_and_picks_them`, `select_layer_needs_more_than_one_layer_under_the_pointer`) | | Escape with layers selected | done | clears the selection at once, whatever the nesting; it never selects the parent. Measured in the Figma web app (2026-11-08) with a rectangle in a group in a frame, selected from the canvas (a double-click into the group), from the Layers panel, and after Tab moved the selection to its sibling: one Escape selects nothing, a second leaves nothing selected. Escape still leaves text and vector editing, ends gestures and the pen first, and ends the focus view once nothing or the focused frame is selected (`selection_behaviour_tests`, `devfocus_tests`) | @@ -210,6 +210,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-19 | patch | M5, #2360: with a frame selected, a drag that starts on one of its children moves the frame and a click selects the child (a press on a layer inside a selected one drags the selection), as in Figma; Cmd/Ctrl, Shift and layers outside the frame are unchanged. | | 2026-11-18 | patch | M5, #2372: the arrow keys move a layer along the canvas axes inside a rotated parent (the step was applied along the parent's axes, so Down moved a child of a frame rotated 90 degrees sideways); auto layout children are unchanged | | 2026-11-18 | patch | M1, #2355: Cmd/Ctrl+V with one layer inside a frame selected pasted the copy onto the page on top of the frame; it now goes into the layer's parent just above it (in an auto layout frame, the item after it, so the layout grows), keeping today's behaviour for a page-level layer, several layers, an instance's children and a board atom. Tests: `paste_sibling_tests` (5) | | 2026-11-08 | minor | M8, #2109: in vector edit mode the Align commands (`align.left` to `align.bottom`, Alt+A/H/D/W/V/S) and Distribute horizontal and vertical spacing act on the selected points when neither `ids` nor `id` is given (either one targets layers), as in Figma (measured in Figma on 2026-11-08): each point moves along one axis only, to its box's left, horizontal centre, right, top, vertical centre or bottom, and distribute spaces the points evenly between the outermost two in order along the axis; handles go with their vertex, a single point stays, with no point selected nothing moves (the layer is not aligned to its frame, as measured in Figma), and one undo restores them. The Design panel draws the alignment row first, with a Distribute menu from three points. Numbers unchanged. | From 944fe8616cdd7c79f99e014d1bbaaac58869941d Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 15 Nov 2026 00:35:17 -0500 Subject: [PATCH 040/114] M5: the frame_with_child doc comment gives the layers' real positions (#2377 review) The nested frame is 100 x 100 at (180, 180) and its rectangle is 40 x 40 at (200, 200), as the code creates them. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 driver, no subagent --- crates/engine/src/selection_behaviour_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/selection_behaviour_tests.rs b/crates/engine/src/selection_behaviour_tests.rs index b2aed52cf..62583e695 100644 --- a/crates/engine/src/selection_behaviour_tests.rs +++ b/crates/engine/src/selection_behaviour_tests.rs @@ -563,8 +563,8 @@ fn shift_click_takes_a_layer_out_where_nothing_can_move() { assert_eq!(s.selection(), vec![k.empty], "Shift-click still takes the layer out"); } -/// A top-level 300 x 300 frame with a filled 100 x 100 rectangle at (50, 50) and a nested frame -/// at (200, 200 80x80) holding a rectangle at (210, 210 40x40). +/// A top-level 300 x 300 frame with a filled 100 x 100 rectangle at (50, 50) and a nested 100 x 100 +/// frame at (180, 180) holding a 40 x 40 rectangle at (200, 200). fn frame_with_child(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) { let f = id(&ex(s, "frame.create", json!({"x": 0, "y": 0, "width": 300, "height": 300}))); let c = id(&ex(s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100, "parent": f}))); From b5d43a7de2a2af6b79f9bf5077180721bc476b85 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 19 Nov 2026 00:47:42 +0700 Subject: [PATCH 041/114] M8: a Shift-click range in the Layers panel keeps a frame, not its covered children, as in Figma (#2330) The change from #2330 by @TrevorBrown-dev, as one commit. --- crates/ui-egui/src/layers_behaviour_tests.rs | 58 ++++++++++++++++++++ crates/ui-egui/src/layers_keys_tests.rs | 36 ++++++++++++ crates/ui-egui/src/panels/layers.rs | 18 +++++- docs/ui-parity.md | 5 +- 4 files changed, 113 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/layers_behaviour_tests.rs b/crates/ui-egui/src/layers_behaviour_tests.rs index d5dff9bd0..2bd7aabe8 100644 --- a/crates/ui-egui/src/layers_behaviour_tests.rs +++ b/crates/ui-egui/src/layers_behaviour_tests.rs @@ -951,6 +951,64 @@ fn search_fields_keep_their_text_in_the_middle() { assert!(off < 1.0, "Search assets is {off} points off the middle"); } +#[test] +fn a_shift_range_across_frames_keeps_a_frame_and_not_its_covered_children() { + let mut s = Session::new(); + let frame1 = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 100, "name": "Frame 1"})).unwrap()); + let rect2 = rect(&mut s, "Rect 2", 0.0, Some(frame1)); + let rect3 = rect(&mut s, "Rect 3", 30.0, Some(frame1)); + let frame2 = id(s.execute("frame.create", &json!({"x": 200, "y": 0, "width": 100, "height": 100, "name": "Frame 2"})).unwrap()); + let rect4 = rect(&mut s, "Rect 4", 0.0, Some(frame2)); + s.execute("select.none", &json!({})).unwrap(); + let mut u = Ui::new(s); + u.app.ui.expanded.extend([frame1, frame2]); + u.frame(vec![]); + let (row4, row2) = (u.row_at(rect4), u.row_at(rect2)); + click(&mut u, row4, Modifiers::NONE); + click(&mut u, row2, SHIFT); + assert_eq!( + sorted(u.app.session.selection()), + sorted(vec![rect4, frame1]), + "the range keeps Frame 1 and drops its covered children {rect3:?} and {rect2:?}" + ); +} + +#[test] +fn a_second_shift_click_after_a_reverse_cross_frame_range_extends_the_range() { + let mut s = Session::new(); + let frame1 = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 100, "name": "Frame 1"})).unwrap()); + let rect2 = rect(&mut s, "Rect 2", 0.0, Some(frame1)); + let rect3 = rect(&mut s, "Rect 3", 30.0, Some(frame1)); + let frame2 = id(s.execute("frame.create", &json!({"x": 200, "y": 0, "width": 100, "height": 100, "name": "Frame 2"})).unwrap()); + let rect4 = rect(&mut s, "Rect 4", 0.0, Some(frame2)); + s.execute("select.none", &json!({})).unwrap(); + let mut u = Ui::new(s); + u.app.ui.expanded.extend([frame1, frame2]); + u.frame(vec![]); + let (row2, row4, row3) = (u.row_at(rect2), u.row_at(rect4), u.row_at(rect3)); + click(&mut u, row2, Modifiers::NONE); + click(&mut u, row4, SHIFT); + assert_eq!(sorted(u.app.session.selection()), sorted(vec![rect4, frame1])); + // Rows run Frame 2, Rect 4, Frame 1, Rect 3, Rect 2: the range from Rect 2 to Rect 3 is those two. + click(&mut u, row3, SHIFT); + assert_eq!(sorted(u.app.session.selection()), sorted(vec![rect3, rect2]), "the range still runs from Rect 2, not a toggle"); +} + +#[test] +fn a_shift_range_inside_one_frame_is_unchanged() { + let mut s = Session::new(); + let frame = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 100, "name": "F"})).unwrap()); + let kids = [0.0, 30.0, 60.0].map(|x| rect(&mut s, "k", x, Some(frame))); + s.execute("select.none", &json!({})).unwrap(); + let mut u = Ui::new(s); + u.app.ui.expanded.insert(frame); + u.frame(vec![]); + let (first, last) = (u.row_at(kids[0]), u.row_at(kids[2])); + click(&mut u, first, Modifiers::NONE); + click(&mut u, last, SHIFT); + assert_eq!(sorted(u.app.session.selection()), sorted(kids.to_vec())); +} + /// The centre of `id`'s icon, a top-level row: the row's left edge is the first point from the /// left at which the pointer is over it, and the icon's centre is 8 (margin) + 4 + 22 points /// further right. diff --git a/crates/ui-egui/src/layers_keys_tests.rs b/crates/ui-egui/src/layers_keys_tests.rs index 63f8ce74c..cb9fe17cc 100644 --- a/crates/ui-egui/src/layers_keys_tests.rs +++ b/crates/ui-egui/src/layers_keys_tests.rs @@ -76,6 +76,42 @@ fn up_and_down_walk_the_rows_and_shift_extends() { assert_eq!(doc.node(c).unwrap().transform.translation().x, 200.0); } +#[test] +fn a_keyboard_shift_range_keeps_an_anchor_covered_by_a_selected_frame() { + let mut s = Session::new(); + let frame1 = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 100, "name": "Frame 1"})).unwrap()); + let mk = |s: &mut Session, name: &str, parent: NodeId| { + id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20, "parent": parent, "props": {"name": name}})).unwrap()) + }; + let rect2 = mk(&mut s, "Rect 2", frame1); + let rect3 = mk(&mut s, "Rect 3", frame1); + let frame2 = id(s.execute("frame.create", &json!({"x": 200, "y": 0, "width": 100, "height": 100, "name": "Frame 2"})).unwrap()); + let rect4 = mk(&mut s, "Rect 4", frame2); + s.execute("select.none", &json!({})).unwrap(); + let mut u = Ui::new(s); + u.app.ui.expanded.extend([frame1, frame2]); + u.frame(vec![]); + click_row(&mut u, rect2); + let p4 = u.row_at(rect4); + let shift = Modifiers { shift: true, ..Default::default() }; + u.frame_with(vec![Event::PointerMoved(p4)], shift); + let button = |pressed| Event::PointerButton { pos: p4, button: egui::PointerButton::Primary, pressed, modifiers: shift }; + u.frame_with(vec![button(true)], shift); + u.frame_with(vec![button(false)], shift); + let mut got = sel(&u); + got.sort(); + let mut want = vec![rect4, frame1]; + want.sort(); + assert_eq!(got, want, "the pointer range keeps the frame"); + // Rows: Frame 2, Rect 4, Frame 1, Rect 3, Rect 2. Shift+Down runs from Rect 2 (the anchor). + key(&mut u, Key::ArrowDown, true); + let mut got = sel(&u); + got.sort(); + let mut want = vec![rect3, rect2]; + want.sort(); + assert_eq!(got, want, "the keyboard range extends from Rect 2's row, not from the current row"); +} + #[test] fn left_and_right_open_close_and_move_between_levels() { let (mut u, _, frame, child, _) = setup(); diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index b7fe8c308..72c916391 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -637,6 +637,14 @@ fn matching(doc: &Document, id: NodeId, q: &str, out: &mut Vec) { } } +/// The range anchor while it is still part of the selection: selected itself, or covered by a +/// selected frame (a range across parents selects the frame and not its children). +fn live_anchor(app: &FigApp, sel: &[NodeId]) -> Option { + let a = app.ui.layer_anchor?; + let covered = || app.session.ds().is_ok_and(|ds| ds.doc.ancestors(a).iter().any(|p| sel.contains(p))); + (sel.contains(&a) || covered()).then_some(a) +} + /// Arrow keys while the layers panel has the keyboard: Up/Down select the row above or below /// (Shift extends the range from the anchor), Left collapses a row or goes to its parent, Right /// expands a row or goes to its first child. Returns whether the key was used. @@ -669,7 +677,7 @@ pub(crate) fn key_nav(app: &mut FigApp, key: egui::Key, shift: bool) -> bool { let Some((j, next)) = j.and_then(|j| rows.get(j).map(|r| (j, r.id))) else { return true }; if shift { // The rows from the anchor to the new one, with the moving end last. - let anchor = app.ui.layer_anchor.filter(|a| sel.contains(a)).unwrap_or(cur); + let anchor = live_anchor(app, &sel).unwrap_or(cur); let a = rows.iter().position(|r| r.id == anchor).unwrap_or(i); let ids: Vec = if a <= j { rows.get(a..=j).unwrap_or_default().iter().map(|r| r.id).collect() @@ -909,7 +917,8 @@ fn select_clicked(app: &mut FigApp, rows: &[Row], sel: &[NodeId], id: NodeId, m: app.ui.pages_focus = None; let order: Vec = rows.iter().map(|r| r.id).collect(); let pos = |x: NodeId| order.iter().position(|o| *o == x); - let anchor = app.ui.layer_anchor.filter(|a| sel.contains(a)).and_then(pos); + let live = live_anchor(app, sel); + let anchor = live.and_then(pos); if m.shift && let (Some(ai), Some(bi)) = (anchor, pos(id)) { @@ -921,6 +930,11 @@ fn select_clicked(app: &mut FigApp, rows: &[Row], sel: &[NodeId], id: NodeId, m: s.push(*x); } } + // A layer under a selected ancestor is covered by it, not a member of its own. + if let Ok(ds) = app.session.ds() { + let all = s.clone(); + s.retain(|x| !ds.doc.ancestors(*x).iter().any(|a| all.contains(a))); + } app.run("select.set", json!({"ids": s})); } else if m.shift || m.command { let mut s = sel.to_vec(); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 94ad714ae..6a9d101fd 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); 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 capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (M8: a Shift-click range in the Layers panel across parents keeps a frame and not its covered children, measured in Figma's web app on 2026-11-12; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); 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 capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -43,7 +43,7 @@ interaction feel only partly compared: the interactions measured so far, case by | 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`; selected hierarchies share a continuous background with rounded outer corners, including nested selections | +| 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`; a range across parents keeps a frame and not its covered children (Rect 4 then Shift on Rect 2 in another frame gives Rect 4 and the frame between; measured in Figma's web app, 2026-11-12); 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) (a child's padlock can't be toggled while its parent is locked) | @@ -210,6 +210,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-19 | patch | M8: a Shift-click range in the Layers panel keeps a frame and not its covered children: a range across parents selects a frame whose row is inside it, and drops the rows under that frame, as measured in Figma's web app on 2026-11-12 (Rect 4 in one frame, Shift-click Rect 2 in another: Rect 4 and the second frame, 2 selected); a range among siblings is unchanged; Cmd with Shift reduces the combined set the same way, not measured | | 2026-11-19 | patch | M5, #2360: with a frame selected, a drag that starts on one of its children moves the frame and a click selects the child (a press on a layer inside a selected one drags the selection), as in Figma; Cmd/Ctrl, Shift and layers outside the frame are unchanged. | | 2026-11-18 | patch | M5, #2372: the arrow keys move a layer along the canvas axes inside a rotated parent (the step was applied along the parent's axes, so Down moved a child of a frame rotated 90 degrees sideways); auto layout children are unchanged | | 2026-11-18 | patch | M1, #2355: Cmd/Ctrl+V with one layer inside a frame selected pasted the copy onto the page on top of the frame; it now goes into the layer's parent just above it (in an auto layout frame, the item after it, so the layout grows), keeping today's behaviour for a page-level layer, several layers, an instance's children and a board atom. Tests: `paste_sibling_tests` (5) | From 64b0b4510881d7e7a28e65a8f6b7e10d521ccedd Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 00:56:10 +0700 Subject: [PATCH 042/114] M4: Outline stroke on a text without a stroke outlines its glyphs (#2405) A fill-only text was left as it was: Outline stroke skipped every layer without a visible stroke. A text now flattens in place into a vector of its glyphs, filled as the text was and keeping its colour style, constraints, visibility and lock; a text with no glyphs stays. --- crates/engine/src/cmd/structure.rs | 15 ++++++++++++ crates/engine/src/shapes_behaviour_tests.rs | 26 +++++++++++++++++++++ docs/target-app-parity.md | 3 ++- 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/structure.rs b/crates/engine/src/cmd/structure.rs index c73ef8b21..bf1c92d2f 100644 --- a/crates/engine/src/cmd/structure.rs +++ b/crates/engine/src/cmd/structure.rs @@ -577,6 +577,21 @@ fn outline_stroke(s: &mut Session, p: &Value) -> Result { let doc = s.doc_mut()?; let n = doc.get(i)?.clone(); if !n.has_visible_stroke() { + // A text without a stroke outlines its glyphs (#2405): flattened in place, filled as it was. + if matches!(n.kind, NodeKind::Text(_)) { + match flatten(s, &json!({"ids": [i]})) { + Ok(r) => { + if let Some(v) = id_of(&r["id"]) { + let o = s.doc_mut()?.get_mut(v)?; + (o.styles.fill, o.styles.effect) = (n.styles.fill, n.styles.effect); + (o.constraints, o.child_layout, o.visible, o.locked) = (n.constraints, n.child_layout, n.visible, n.locked); + out.push(v); + } + } + Err(EngineError::Disabled(..)) => {} // no glyphs (empty, or no font): nothing to outline + Err(e) => return Err(e), + } + } continue; } let closed = figcraft_doc::geometry::is_closed(&n); diff --git a/crates/engine/src/shapes_behaviour_tests.rs b/crates/engine/src/shapes_behaviour_tests.rs index f6611f991..4fad347ac 100644 --- a/crates/engine/src/shapes_behaviour_tests.rs +++ b/crates/engine/src/shapes_behaviour_tests.rs @@ -571,6 +571,32 @@ fn outline_stroke_outlines_every_selected_layer() { } } +#[test] +fn outline_stroke_outlines_a_text_without_a_stroke() { + // Fixed (#2405): a fill-only text was left as it was; its glyphs become a vector filled as the text was. + let mut s = Session::new(); + let t = create(&mut s, "text.create", json!({"text": "OPEN", "x": 10, "y": 20})); + ex(&mut s, "style.create", json!({"type": "paint", "name": "Ink", "value": ["#112233"]})); + ex(&mut s, "style.apply", json!({"ids": [t], "style": "Ink"})); + let before = node(&s, t); + let page = s.page().unwrap(); + let out = ex(&mut s, "vector.outlineStroke", json!({"ids": [t]})); + let ids: Vec = out["ids"].as_array().unwrap().iter().filter_map(id_of).collect(); + // Without a font nothing lays out, so there is nothing to outline (CI has no fonts). + if !figcraft_text::layout_node(&before).is_some_and(|(l, _)| !l.glyphs.is_empty()) { + assert!(ids.is_empty() && matches!(node(&s, t).kind, NodeKind::Text(_)), "no glyphs: the text stays: {out}"); + return; + } + assert_eq!(ids.len(), 1, "one outline: {out}"); + let v = node(&s, ids[0]); + assert!(matches!(v.kind, NodeKind::Vector { .. }), "the glyphs become a vector"); + assert_eq!((&v.fills, v.styles.fill), (&before.fills, before.styles.fill), "filled as the text was, colour style too"); + assert_eq!(s.doc().unwrap().node(page).unwrap().children, ids, "the outline stands in for the text"); + assert_eq!(s.selection(), ids, "the outline is selected"); + s.undo().unwrap(); + assert!(matches!(node(&s, t).kind, NodeKind::Text(_)), "undo brings the text back"); +} + #[test] fn node_set_non_numeric_miter_smoothing_paragraph_is_an_error() { let mut s = Session::new(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 941f4b807..409efe1d7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-18 · **Change:** minor (points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is @@ -651,6 +651,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-19 | patch | M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing. | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-09 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it (while the view moves, a detail is drawn only while it covers the whole view: past it the capped texture shows alone, with no sharp edge across the view, until the view settles); transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | | 2026-11-08 | minor | M8, #2109: in vector edit mode the Align commands (`align.left` to `align.bottom`, Alt+A/H/D/W/V/S) and Distribute horizontal and vertical spacing act on the selected points when no `ids` are given, as in Figma (measured in Figma on 2026-11-08): each point moves along one axis only, to its box's left, horizontal centre, right, top, vertical centre or bottom, and distribute spaces the points evenly between the outermost two in order along the axis; handles go with their vertex, a single point stays, with no point selected nothing moves (the layer is not aligned to its frame, as measured in Figma), and one undo restores them. The Design panel draws the alignment row first, with a Distribute menu from three points. Numbers unchanged. | From 98c47144586d11fe257d6a2913681c4251fea5ff Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 19 Nov 2026 01:19:39 +0700 Subject: [PATCH 043/114] M8: dragging near the canvas edge pans the view, as in Figma (#2015) (#2104) The change from #2104 by @TrevorBrown-dev, as one commit. --- crates/engine/src/canvas/tools.rs | 13 + crates/engine/src/lib.rs | 2 + crates/engine/src/view_autopan_tests.rs | 50 ++++ crates/engine/src/view_state.rs | 38 +++ crates/ui-egui/src/canvas.rs | 1 + crates/ui-egui/src/canvas/autopan.rs | 100 +++++++ crates/ui-egui/src/canvas/input.rs | 12 + crates/ui-egui/src/canvas/proto_canvas.rs | 80 +++++- crates/ui-egui/src/canvas_autopan_tests.rs | 301 +++++++++++++++++++++ crates/ui-egui/src/lib.rs | 2 + docs/prototyping-parity.md | 5 +- docs/ui-parity.md | 4 +- 12 files changed, 599 insertions(+), 9 deletions(-) create mode 100644 crates/engine/src/view_autopan_tests.rs create mode 100644 crates/ui-egui/src/canvas/autopan.rs create mode 100644 crates/ui-egui/src/canvas_autopan_tests.rs diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index c60483fcf..458845f65 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -623,4 +623,17 @@ impl ToolState { pub fn busy(&self) -> bool { !matches!(self.gesture, Gesture::None) } + + /// Whether the gesture under way pans the canvas when the pointer holds near the viewport's + /// edge (#2015): moving layers once past the drag slop, the selection box once it has grown + /// past it, and drawing a shape once it exists. Resizing, rotating, panning, text and vector + /// edits don't. `zoom`: screen px per page unit. + pub fn autopans(&self, zoom: f64) -> bool { + match &self.gesture { + Gesture::Move { moved, .. } => *moved, + Gesture::Marquee { .. } => self.overlay.marquee.is_some_and(|[x0, y0, x1, y1]| ((x1 - x0).hypot(y1 - y0) * zoom) >= DRAG_SLOP_PX), + Gesture::Draw { id, .. } => id.is_some(), + _ => false, + } + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6fe5633ad..82cef7891 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -658,6 +658,8 @@ mod version_preview_tests; #[cfg(test)] mod version_tests; #[cfg(test)] +mod view_autopan_tests; +#[cfg(test)] mod view_behaviour_tests; #[cfg(test)] mod vote_history_tests; diff --git a/crates/engine/src/view_autopan_tests.rs b/crates/engine/src/view_autopan_tests.rs new file mode 100644 index 000000000..0737850ca --- /dev/null +++ b/crates/engine/src/view_autopan_tests.rs @@ -0,0 +1,50 @@ +//! Canvas auto-pan (#2015): the speed a drag held near the viewport's edge pans the view at, as +//! measured in the incumbent at 100% (screen px per second, `40 x (15 - d)` clamped to 0..600, +//! `d` the pointer's distance inside the edge), and which gestures pan. + +use crate::ViewState; + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn the_speed_grows_40_px_per_second_for_each_px_inside_the_zone_up_to_600() { + for (d, speed) in [(40.0, 0.0), (25.0, 0.0), (15.0, 0.0), (12.0, 120.0), (8.0, 280.0), (2.0, 520.0), (0.0, 600.0), (-30.0, 600.0)] { + assert!(near(ViewState::autopan_speed(d), speed), "{d} px inside: {} px/s, wanted {speed}", ViewState::autopan_speed(d)); + } + assert_eq!(ViewState::autopan_speed(f64::NAN), 0.0); + assert!(near(ViewState::autopan_speed(f64::NEG_INFINITY), 600.0)); +} + +#[test] +fn the_velocity_points_toward_the_near_edge_on_each_axis() { + let (w, h) = (1000.0, 600.0); + let v = |x: f64, y: f64| ViewState::autopan_velocity(x, y, w, h); + assert_eq!(v(500.0, 300.0), (0.0, 0.0), "the middle"); + assert_eq!(v(1000.0 - 2.0, 300.0), (520.0, 0.0), "right edge: right"); + assert_eq!(v(2.0, 300.0), (-520.0, 0.0), "left edge: left"); + assert_eq!(v(500.0, 600.0 - 8.0), (0.0, 280.0), "bottom edge: down"); + assert_eq!(v(500.0, 12.0), (0.0, -120.0), "top edge: up"); + assert_eq!(v(1000.0 - 40.0, 300.0), (0.0, 0.0), "40 px in: none"); + assert_eq!(v(1000.0 - 15.0, 300.0), (0.0, 0.0), "15 px in: none"); + // A corner pans on both axes, each by its own distance. + assert_eq!(v(1000.0 - 12.0, 600.0 - 2.0), (120.0, 520.0)); + assert_eq!(v(8.0, 2.0), (-280.0, -520.0)); + // Past the edge, or outside the viewport altogether: the cap. + assert_eq!(v(1030.0, 300.0), (600.0, 0.0)); + assert_eq!(v(-500.0, 900.0), (-600.0, 600.0)); +} + +#[test] +fn panning_moves_the_view_by_the_velocity_in_screen_px_at_any_zoom() { + for zoom in [0.25, 1.0, 4.0] { + let mut v = ViewState { vw: 1000.0, vh: 600.0, zoom, cx: 50.0, cy: 70.0, ..Default::default() }; + assert!(v.autopan(998.0, 300.0, 0.5), "in the zone"); + assert!(near((v.cx - 50.0) * zoom, 260.0), "{zoom}: 520 px/s for half a second is 260 screen px"); + assert_eq!(v.cy, 70.0); + assert!(!v.autopan(500.0, 300.0, 0.5), "out of the zone"); + assert!(!v.autopan(998.0, 300.0, 0.0), "no time"); + assert!(!v.autopan(998.0, 300.0, f64::NAN), "no time"); + } +} diff --git a/crates/engine/src/view_state.rs b/crates/engine/src/view_state.rs index 8a8cc8a01..bff3195e2 100644 --- a/crates/engine/src/view_state.rs +++ b/crates/engine/src/view_state.rs @@ -159,6 +159,44 @@ impl ViewState { self.cx -= dx / z; self.cy -= dy / z; } + /// How near the viewport's edge a drag must hold the pointer to pan the canvas (screen px). + pub const AUTOPAN_ZONE_PX: f64 = 15.0; + /// Auto-pan speed gained for each pixel the pointer is closer to the edge (screen px/s). + pub const AUTOPAN_RATE: f64 = 40.0; + /// The fastest auto-pan, at the edge and beyond it (screen px/s). + pub const AUTOPAN_MAX: f64 = 600.0; + /// The speed (screen px/s) the canvas pans toward an edge while a drag holds the pointer + /// `d` px inside it (negative: outside), as measured in the incumbent: `40 x (15 - d)` + /// clamped to 0..600 (#2015). Constant while the pointer stays put, at every zoom. + pub fn autopan_speed(d: f64) -> f64 { + if d.is_nan() { + return 0.0; + } + (Self::AUTOPAN_RATE * (Self::AUTOPAN_ZONE_PX - d)).clamp(0.0, Self::AUTOPAN_MAX) + } + /// The velocity (screen px/s, positive: right and down) the canvas auto-pans at while a drag + /// holds the pointer at (`px`, `py`) in a viewport of `width` x `height` (both from its + /// top-left corner): toward each edge the pointer is near, each axis by its own distance, so a + /// corner pans both ways. + pub fn autopan_velocity(px: f64, py: f64, width: f64, height: f64) -> (f64, f64) { + let axis = |p: f64, len: f64| { + if p < len / 2.0 { -Self::autopan_speed(p) } else { Self::autopan_speed(len - p) } + }; + (axis(px, width), axis(py, height)) + } + /// Auto-pan for `dt` seconds with the pointer at (`px`, `py`) from the viewport's top-left + /// corner: moves the view by the velocity ([`Self::autopan_velocity`]) in screen px. True when + /// it moved. + pub fn autopan(&mut self, px: f64, py: f64, dt: f64) -> bool { + let (vx, vy) = Self::autopan_velocity(px, py, self.vw, self.vh); + if !(dt.is_finite() && dt > 0.0) || (vx == 0.0 && vy == 0.0) { + return false; + } + let z = self.zoom.max(1e-6); + self.cx += vx * dt / z; + self.cy += vy * dt / z; + true + } pub fn page_to_screen(&self, x: f64, y: f64) -> (f64, f64) { let (ox, oy) = self.origin(); ((x - ox) * self.zoom, (y - oy) * self.zoom) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 5de28c832..3d3f05082 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -14,6 +14,7 @@ use crate::i18n::{tr, trf, trn}; use crate::render_worker::{Done, Job, Worker}; use crate::theme::{COMPONENT, Tokens, doc_c32, regular, semibold}; +mod autopan; mod background; mod builder; mod input; diff --git a/crates/ui-egui/src/canvas/autopan.rs b/crates/ui-egui/src/canvas/autopan.rs new file mode 100644 index 000000000..e95f8451d --- /dev/null +++ b/crates/ui-egui/src/canvas/autopan.rs @@ -0,0 +1,100 @@ +//! Auto-pan: a drag that holds the pointer near the canvas's edge, or past it, pans the view +//! toward it, steadily while the pointer stays still (#2015). The rule lives in +//! [`figcraft_engine::ViewState::autopan_velocity`]; this applies it once a frame. + +use egui::{Context, Pos2}; + +use crate::FigApp; + +/// The longest frame the pan counts, so a stall doesn't jump the view. +const MAX_DT: f64 = 0.1; + +/// Pan the view for this frame with a drag's pointer at screen point `pos`. True when it panned, +/// so the caller feeds the engine the pointer again: the dragged layer, box, shape or connection +/// follows the document point now under it. Asks for another frame while the pointer is in the +/// zone, so the pan goes on when nothing else moves. +pub(crate) fn pan(app: &mut FigApp, ctx: &Context, pos: Pos2) -> bool { + let dt = f64::from(ctx.input(|i| i.unstable_dt)).clamp(0.0, MAX_DT); + let min = app.canvas.rect.min; + let (px, py) = (f64::from(pos.x - min.x), f64::from(pos.y - min.y)); + let Ok(ds) = app.session.ds_mut() else { return false }; + let (vx, vy) = figcraft_engine::ViewState::autopan_velocity(px, py, ds.view.vw, ds.view.vh); + if vx == 0.0 && vy == 0.0 { + return false; + } + // In the zone: the next frame pans too, even if the pointer never moves. + ctx.request_repaint(); + if !ds.view.autopan(px, py, dt) { + return false; + } + ds.revision += 1; + true +} + +/// The drag under way pans at the edge: a primary drag of the Move or a drawing tool that +/// [`figcraft_engine::tools::ToolState::autopans`] allows, with no text being edited. Not while a +/// manual pan (Space, or the middle button) is under way: that pan can carry the pointer off the +/// canvas, where the view must follow the pointer, not the edge speed. +pub(super) fn wanted(app: &FigApp, ctx: &Context) -> bool { + let Ok(ds) = app.session.ds() else { return false }; + app.canvas.dragging + && app.canvas.middle_pan.is_none() + && ds.text_edit.is_none() + && ds.vector_edit.is_none() + && ctx.input(|i| i.pointer.primary_down()) + && app.session.tool.autopans(ds.view.zoom) +} + +#[cfg(test)] +mod tests { + use egui::{Context, Pos2, RawInput, pos2}; + use figcraft_engine::Session; + + use crate::layers_drag_tests::Ui; + + /// Whether [`super::pan`] alone, with the pointer at `pos`, asks for the next frame. Run in a + /// context of its own, after a few settling passes, so nothing else in the app asks for one. + fn asks(u: &mut Ui, pos: Pos2) -> bool { + let ctx = Context::default(); + for _ in 0..3 { + ctx.run_ui(RawInput::default(), |_| {}).textures_delta.clear(); + } + let mut out = ctx.run_ui(RawInput::default(), |ui| { + super::pan(&mut u.app, ui.ctx(), pos); + }); + out.textures_delta.clear(); + out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.repaint_delay.is_zero()) + } + + #[test] + fn a_manual_pan_during_a_drag_does_not_autopan() { + let mut u = Ui::new(Session::new()); + let id = figcraft_engine::params::id_of( + &u.app.session.execute("shape.rectangle", &serde_json::json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap()["id"], + ); + assert!(id.is_some()); + u.frame(vec![]); + u.frame(vec![]); + let r = u.app.canvas.rect; + let p = u.app.to_screen(50.0, 25.0); + u.button(p, true); + u.frame(vec![egui::Event::PointerMoved(p + egui::vec2(12.0, 0.0))]); + let off = pos2(r.max.x + 30.0, p.y); + u.frame(vec![egui::Event::PointerMoved(off)]); + assert!(super::wanted(&u.app, &u.ctx), "a plain layer drag held off the canvas autopans"); + u.app.canvas.middle_pan = Some((off, 0.0, 0.0)); + assert!(!super::wanted(&u.app, &u.ctx), "a pan begun during the drag is the user's to steer"); + } + + #[test] + fn in_the_zone_it_asks_for_the_next_frame_and_outside_it_does_not() { + let mut u = Ui::new(Session::new()); + u.frame(vec![]); + u.frame(vec![]); + let r = u.app.canvas.rect; + assert!(asks(&mut u, pos2(r.max.x - 2.0, r.center().y)), "2 px inside the right edge"); + assert!(asks(&mut u, pos2(r.min.x - 20.0, r.max.y + 20.0)), "past the bottom-left corner"); + assert!(!asks(&mut u, r.center()), "the middle of the canvas"); + assert!(!asks(&mut u, pos2(r.max.x - 40.0, r.center().y)), "40 px inside the edge"); + } +} diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 1b177693e..1360697d8 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -226,6 +226,13 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo send(app, PointerKind::Up, at, &mods); } } + // A drag held past the edge pans toward it, the layer or box going with the pointer. + if super::autopan::wanted(app, &ctx) + && let Some(at) = ctx.input(|i| i.pointer.latest_pos()) + && super::autopan::pan(app, &ctx, at) + { + send(app, PointerKind::Move, at, &mods); + } // Leaving the canvas: nothing is hovered there any more. if !app.canvas.dragging && std::mem::take(&mut app.canvas.hovering) { left(app); @@ -377,6 +384,11 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo if force.is_some() { app.canvas.pressure = force; } + // A drag held near the edge pans before the move goes out, so it lands on the document point + // now under the pointer (and the pan goes on while the pointer is still: it asks for frames). + if kind == Some(PointerKind::Move) && super::autopan::wanted(app, &ctx) { + super::autopan::pan(app, &ctx, pos); + } if let Some(k) = kind { let at = if matches!(k, PointerKind::Down) { press_pos.unwrap_or(pos) } else { pos }; send(app, k, at, &mods); diff --git a/crates/ui-egui/src/canvas/proto_canvas.rs b/crates/ui-egui/src/canvas/proto_canvas.rs index b30fc604b..140d690cd 100644 --- a/crates/ui-egui/src/canvas/proto_canvas.rs +++ b/crates/ui-egui/src/canvas/proto_canvas.rs @@ -18,7 +18,9 @@ const HANDLE_R: f32 = 7.0; #[derive(Clone, Copy)] struct Drag { source: NodeId, - from: Pos2, + /// Where the connection leaves the layer, on the page: the view pans under a drag at the + /// edge (#2015). + from: figcraft_geom::Point, pos: Pos2, } @@ -246,13 +248,14 @@ pub fn draw(app: &FigApp, painter: &egui::Painter) { } match dragging { Some(d) => { + let from = app.to_screen(d.from.x, d.from.y); if let Some(t) = target_at(app, doc, page, d.source, d.pos) && let Some(r) = screen_rect(app, doc, t.node()) { painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(2.0, crate::theme::canvas_accent(painter.ctx())), StrokeKind::Outside); } - let dx = ((d.pos.x - d.from.x).abs() * 0.5).max(30.0) * if d.pos.x >= d.from.x { 1.0 } else { -1.0 }; - let pts = [d.from, d.from + vec2(dx, 0.0), d.pos - vec2(dx, 0.0), d.pos]; + let dx = ((d.pos.x - from.x).abs() * 0.5).max(30.0) * if d.pos.x >= from.x { 1.0 } else { -1.0 }; + let pts = [from, from + vec2(dx, 0.0), d.pos - vec2(dx, 0.0), d.pos]; painter.add(egui::epaint::CubicBezierShape::from_points_stroke( pts, false, @@ -260,7 +263,7 @@ pub fn draw(app: &FigApp, painter: &egui::Painter) { Stroke::new(2.0, crate::theme::canvas_accent(painter.ctx())), )); arrow(painter, &pts, crate::theme::canvas_accent(painter.ctx())); - plus_handle(painter, d.from, true); + plus_handle(painter, from, true); } None => { if ds.text_edit.is_none() { @@ -298,10 +301,15 @@ pub fn input(app: &mut FigApp, ui: &egui::Ui, resp: &egui::Response) -> bool { let Ok(ds) = app.session.ds() else { return false }; let (doc, page, sel) = (ds.doc.clone(), ds.page, ds.selection.clone()); if let Some(mut d) = drag { - if let Some(p) = pos { + if let Some(p) = pos.or_else(|| ctx.input(|i| i.pointer.latest_pos())) { d.pos = p; } ctx.request_repaint(); + // Held near the edge of the canvas, or past it, the view pans toward it (#2015); the + // connection's end stays under the pointer, and its start stays on its layer. + if down && !released { + super::autopan::pan(app, &ctx, d.pos); + } if released || !down { ctx.data_mut(|m| m.remove::(drag_id())); let params = target_at(app, &doc, page, d.source, d.pos).map(|t| match t { @@ -331,7 +339,7 @@ pub fn input(app: &mut FigApp, ui: &egui::Ui, resp: &egui::Response) -> bool { return false; } if let Some((source, from)) = over_handle { - ctx.data_mut(|m| m.insert_temp(drag_id(), Drag { source, from, pos })); + ctx.data_mut(|m| m.insert_temp(drag_id(), Drag { source, from: app.to_page(from), pos })); return true; } let hit = noodles(app, &ctx, &doc, page) @@ -373,6 +381,66 @@ mod tests { u.button(at, false); } + /// A connection dragged out of a layer and held at the canvas's edge pans the view toward it + /// (520 px/s 2 px inside), so a frame off screen scrolls under the pointer and the link can + /// reach it (#2015). The connection keeps leaving its layer. + #[test] + fn a_connection_dragged_to_the_edge_pans_until_a_frame_off_screen_is_under_it() { + use egui::Event; + let mut s = figcraft_engine::Session::new(); + let a = s.execute("frame.create", &json!({"x": -300, "y": -100, "width": 200, "height": 150})).unwrap(); + let a = crate::present_tests::id(&a); + // Beyond the right edge of a 1440 x 900 screen at 100%. + let b = s.execute("frame.create", &json!({"x": 1500, "y": -200, "width": 400, "height": 400})).unwrap(); + let b = crate::present_tests::id(&b); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let mut u = crate::layers_drag_tests::Ui::new(s); + u.app.ui.right_tab = RightTab::Prototype; + { + let v = &mut u.app.session.ds_mut().unwrap().view; + v.zoom = 1.0; + v.cx = 0.0; + v.cy = 0.0; + } + u.frame(vec![]); + u.frame(vec![]); + let rect = u.app.canvas.rect; + let doc = u.app.session.doc().unwrap().clone(); + let (_, at) = *handles(&u.app, &doc, &[a]).first().unwrap(); + let start = u.app.to_page(at); + u.button(at, true); + let out = pos2(rect.max.x - 40.0, at.y); + u.frame(vec![Event::PointerMoved(out)]); + u.frame(vec![]); + assert_eq!(u.app.session.ds().unwrap().view.cx, 0.0, "40 px in: no pan"); + let edge = pos2(rect.max.x - 2.0, at.y); + u.frame(vec![Event::PointerMoved(edge)]); + let mut frames = 1; + let under_pointer = |u: &crate::layers_drag_tests::Ui| { + let doc = u.app.session.doc().unwrap().clone(); + frame_at(&u.app, &doc, u.app.session.ds().unwrap().page, edge) + }; + assert_eq!(under_pointer(&u), None, "nothing there yet"); + while under_pointer(&u) != Some(b) && frames < 600 { + u.frame(vec![]); + frames += 1; + } + let cx = u.app.session.ds().unwrap().view.cx; + assert!((cx - 520.0 * f64::from(frames) / 60.0).abs() < 1.0, "{frames} frames panned {cx}"); + // It still leaves the layer where it started, now pushed off to the left on screen. + let drag: Drag = u.ctx.data(|d| d.get_temp(drag_id())).expect("the drag goes on"); + assert_eq!(drag.from, start); + assert!(u.app.to_screen(start.x, start.y).x < at.x - 600.0); + u.button(edge, false); + let doc = u.app.session.doc().unwrap().clone(); + let links = doc.node(a).map(|n| n.interactions.clone()).unwrap_or_default(); + assert_eq!(links.len(), 1, "the link was made"); + assert!( + matches!(links[0].actions.as_slice(), [figcraft_doc::proto::Action::Navigate { dest, .. }] if *dest == b), + "to the frame that scrolled in" + ); + } + #[test] fn curves_leave_the_facing_side() { let a = Rect::from_min_size(pos2(0.0, 0.0), vec2(50.0, 20.0)); diff --git a/crates/ui-egui/src/canvas_autopan_tests.rs b/crates/ui-egui/src/canvas_autopan_tests.rs new file mode 100644 index 000000000..0670f05e4 --- /dev/null +++ b/crates/ui-egui/src/canvas_autopan_tests.rs @@ -0,0 +1,301 @@ +//! Canvas auto-pan (#2015), driven through egui headless at 60 frames per second: a drag that +//! holds the pointer within about 15 px of the canvas's edge, or past it, pans the view toward +//! it at `40 x (15 - d)` screen px per second (d: px inside the edge, at most 600), steadily while +//! the pointer stays still. It covers moving layers, the selection box and drawing a shape (the +//! prototype connection is in `proto_canvas`); resizing, rotating and every other drag leave the +//! view where it is. + +use egui::{Event, Pos2, pos2, vec2}; +use figcraft_doc::NodeId; +use figcraft_engine::Session; +use serde_json::json; + +use crate::layers_drag_tests::Ui; + +/// One frame's length, in seconds. +const DT: f64 = 1.0 / 60.0; + +fn id(v: serde_json::Value) -> NodeId { + figcraft_engine::params::id_of(&v["id"]).unwrap() +} + +/// An empty file at 100%, centred on the page's origin, with the canvas laid out. +fn setup() -> Ui { + let mut u = Ui::new(Session::new()); + { + let v = &mut u.app.session.ds_mut().unwrap().view; + v.zoom = 1.0; + v.cx = 0.0; + v.cy = 0.0; + } + u.frame(vec![]); + u.frame(vec![]); + u +} + +fn run(u: &mut Ui, cmd: &str, params: serde_json::Value) -> serde_json::Value { + u.app.session.execute(cmd, ¶ms).unwrap() +} + +/// The view's centre, in page units. +fn centre(u: &Ui) -> (f64, f64) { + let v = &u.app.session.ds().unwrap().view; + (v.cx, v.cy) +} + +fn bounds_x0(u: &Ui, n: NodeId) -> f64 { + u.app.session.doc().unwrap().world_bounds(n).unwrap().x0 +} + +/// Move the pointer to `to` (button held) and hold it there for `frames` frames. +fn hold(u: &mut Ui, to: Pos2, frames: usize) { + u.frame(vec![Event::PointerMoved(to)]); + for _ in 1..frames { + u.frame(vec![]); + } +} + +fn release(u: &mut Ui, at: Pos2) { + u.button(at, false); +} + +/// A 100 x 50 rectangle in the middle of the view, nothing selected; its screen centre. +fn centred_rect(u: &mut Ui) -> (NodeId, Pos2) { + let r = id(run(u, "shape.rectangle", json!({"x": -50, "y": -25, "width": 100, "height": 50}))); + run(u, "select.none", json!({})); + u.frame(vec![]); + (r, u.app.canvas.rect.center()) +} + +/// Press on `p`, drag a little (past the slop) and settle. +fn pick_up(u: &mut Ui, p: Pos2) -> Pos2 { + u.button(p, true); + let moved = p + vec2(12.0, 0.0); + u.frame(vec![Event::PointerMoved(moved)]); + u.frame(vec![]); + moved +} + +#[test] +fn a_layer_held_2_px_inside_the_right_edge_pans_the_view_at_520_px_per_second_and_stays_under_the_pointer() { + let mut u = setup(); + let (r, p) = centred_rect(&mut u); + let from = pick_up(&mut u, p); + // Out of the zone first (40 px in): no pan, however long. + let rect = u.app.canvas.rect; + let out = pos2(rect.max.x - 40.0, from.y); + hold(&mut u, out, 20); + assert_eq!(centre(&u), (0.0, 0.0), "40 px inside: no pan"); + let at = pos2(rect.max.x - 2.0, from.y); + let n = 30; + let (cx0, x0) = (centre(&u).0, bounds_x0(&u, r)); + let grab = x0 - u.app.to_page(out).x; + hold(&mut u, at, n); + let (cx1, x1) = (centre(&u).0, bounds_x0(&u, r)); + let pan = cx1 - cx0; + let want = 520.0 * n as f64 * DT; + assert!((pan - want).abs() < 0.5, "panned {pan} px for {n} frames, wanted {want}"); + assert_eq!(centre(&u).1, 0.0); + // The layer went with the pointer: the pointer's move into the zone plus the pan. + let went = x1 - x0; + assert!((went - (38.0 + pan)).abs() < 1.5, "the layer moved {went}, the pointer 38 and the view {pan}"); + let now = x1 - u.app.to_page(at).x; + assert!((now - grab).abs() < 1.5, "the layer stays under the pointer: {grab} then {now}"); + // Constant speed: the same again for the same time. + hold(&mut u, at, n); + assert!((centre(&u).0 - cx1 - want).abs() < 0.5, "no acceleration"); + // Back out of the zone it stops; so it does on release. + hold(&mut u, out, 10); + let stopped = centre(&u); + hold(&mut u, out, 10); + assert_eq!(centre(&u), stopped, "out of the zone"); + hold(&mut u, at, 3); + release(&mut u, at); + let done = centre(&u); + for _ in 0..10 { + u.frame(vec![]); + } + assert_eq!(centre(&u), done, "released"); + assert!(!u.app.session.tool.busy()); +} + +#[test] +fn the_speed_depends_on_the_distance_and_a_corner_pans_both_ways() { + let mut u = setup(); + let (_, p) = centred_rect(&mut u); + let from = pick_up(&mut u, p); + let rect = u.app.canvas.rect; + // 12 px in: 120 px/s; 8 px: 280; past the edge: 600 (the pointer stays on the canvas). + for (d, speed) in [(12.0, 120.0), (8.0, 280.0), (0.0, 600.0)] { + hold(&mut u, pos2(rect.max.x - 40.0, from.y), 2); + let before = centre(&u).0; + hold(&mut u, pos2(rect.max.x - d, from.y), 60); + let pan = centre(&u).0 - before; + assert!((pan - speed).abs() < 3.0, "{d} px in: panned {pan} px in a second, wanted {speed}"); + } + // The bottom-left corner: down by its distance from the bottom, left by its from the left. + hold(&mut u, rect.center(), 2); + let (cx, cy) = centre(&u); + hold(&mut u, pos2(rect.min.x + 8.0, rect.max.y - 2.0), 30); + let (dx, dy) = (centre(&u).0 - cx, centre(&u).1 - cy); + assert!((dx + 280.0 / 2.0).abs() < 2.0, "left at 280 px/s for half a second: {dx}"); + assert!((dy - 520.0 / 2.0).abs() < 2.0, "down at 520 px/s for half a second: {dy}"); +} + +#[test] +fn a_selection_box_held_at_the_bottom_edge_pans_and_grows_over_what_scrolls_in() { + let mut u = setup(); + let below = f64::from(u.app.canvas.rect.height()) / 2.0 + 120.0; + let far = id(run(&mut u, "shape.rectangle", json!({"x": -40, "y": below, "width": 80, "height": 40}))); + run(&mut u, "select.none", json!({})); + u.frame(vec![]); + let rect = u.app.canvas.rect; + let press = rect.center() + vec2(-200.0, -100.0); + u.button(press, true); + let at = pos2(press.x + 250.0, rect.max.y - 2.0); + u.frame(vec![Event::PointerMoved(at)]); + assert!(u.app.session.selection().is_empty(), "not in the box yet"); + let box0 = u.app.session.tool.overlay.marquee.unwrap(); + let cy0 = centre(&u).1; + let n = 45; + for _ in 1..n { + u.frame(vec![]); + } + let pan = centre(&u).1 - cy0; + let want = 520.0 * (n - 1) as f64 * DT; + assert!((pan - want).abs() < 1.0, "panned {pan}, wanted {want}"); + let box1 = u.app.session.tool.overlay.marquee.unwrap(); + assert!((box1[3] - box0[3] - pan).abs() < 1.0, "the box's bottom followed the pointer: {box0:?} then {box1:?}"); + assert_eq!(u.app.session.selection(), vec![far], "the box reached the layer that scrolled in"); + release(&mut u, at); +} + +#[test] +fn a_press_that_has_not_become_a_drag_does_not_pan() { + let mut u = setup(); + let rect = u.app.canvas.rect; + // A click on the empty canvas right by the edge is not a drag. + let at = pos2(rect.max.x - 2.0, rect.center().y); + u.button(at, true); + for _ in 0..30 { + u.frame(vec![]); + } + assert_eq!(centre(&u), (0.0, 0.0)); + release(&mut u, at); +} + +#[test] +fn a_shape_drawn_at_the_edge_pans_and_grows() { + let mut u = setup(); + run(&mut u, "tool.set", json!({"tool": "rectangle"})); + let rect = u.app.canvas.rect; + let press = rect.center(); + u.button(press, true); + u.frame(vec![Event::PointerMoved(press + vec2(30.0, 30.0))]); + let at = pos2(press.x + 30.0, rect.max.y - 2.0); + u.frame(vec![Event::PointerMoved(at)]); + let cy0 = centre(&u).1; + for _ in 0..30 { + u.frame(vec![]); + } + let pan = centre(&u).1 - cy0; + assert!((pan - 520.0 * 30.0 * DT).abs() < 1.0, "panned {pan}"); + release(&mut u, at); + let r = u.app.session.selection()[0]; + let h = u.app.session.doc().unwrap().world_bounds(r).unwrap().height(); + let before = f64::from(at.y - press.y); + assert!(h > before + pan - 2.0, "the rectangle grew with the pan: {h} for a drag of {before} and a pan of {pan}"); +} + +#[test] +fn a_resize_held_at_the_edge_does_not_pan() { + let mut u = setup(); + let r = id(run(&mut u, "shape.rectangle", json!({"x": 100, "y": -25, "width": 100, "height": 50}))); + run(&mut u, "select.set", json!({"ids": [r]})); + u.frame(vec![]); + let rect = u.app.canvas.rect; + let corner = u.app.to_screen(200.0, 25.0); + u.button(corner, true); + let at = pos2(rect.max.x - 2.0, corner.y); + u.frame(vec![Event::PointerMoved(at)]); + for _ in 0..30 { + u.frame(vec![]); + } + let b = u.app.session.doc().unwrap().world_bounds(r).unwrap(); + assert!(b.width() > 100.0, "it resized, so the press was on the handle: {}", b.width()); + assert_eq!(centre(&u), (0.0, 0.0), "a resize does not pan"); + release(&mut u, at); +} + +#[test] +fn a_hand_drag_does_not_pan_on_its_own_at_the_edge() { + let mut u = setup(); + run(&mut u, "tool.set", json!({"tool": "hand"})); + let rect = u.app.canvas.rect; + let at = pos2(rect.max.x - 2.0, rect.center().y); + u.button(rect.center(), true); + hold(&mut u, at, 20); + // The hand moves the view with the pointer, by the drag, and nothing more. + let c = centre(&u); + for _ in 0..20 { + u.frame(vec![]); + } + assert_eq!(centre(&u), c); + release(&mut u, at); +} + +#[test] +fn a_long_frame_pans_for_a_tenth_of_a_second_at_most() { + let mut u = setup(); + let (_, p) = centred_rect(&mut u); + let from = pick_up(&mut u, p); + let at = pos2(u.app.canvas.rect.max.x - 2.0, from.y); + hold(&mut u, at, 3); + let before = centre(&u).0; + // One frame half a second after the last: it counts as 0.1 s, 52 px at 520 px/s. + let now = u.ctx.input(|i| i.time); + u.advance_clock(now + 0.5); + u.frame(vec![]); + let pan = centre(&u).0 - before; + assert!((pan - 52.0).abs() < 0.5, "a 0.5 s frame panned {pan} px, wanted 52"); + release(&mut u, at); +} + +#[test] +fn past_the_edge_pans_at_the_top_speed_and_the_layer_stays_under_the_pointer() { + let mut u = setup(); + let (r, p) = centred_rect(&mut u); + let from = pick_up(&mut u, p); + let rect = u.app.canvas.rect; + // 30 px past the right edge, over the panel beside the canvas. + let at = pos2(rect.max.x + 30.0, from.y); + hold(&mut u, at, 2); + let (cx0, grab) = (centre(&u).0, bounds_x0(&u, r) - u.app.to_page(at).x); + hold(&mut u, at, 30); + let pan = centre(&u).0 - cx0; + assert!((pan - 600.0 * 30.0 * DT).abs() < 0.5, "panned {pan} px past the edge, wanted {}", 600.0 * 30.0 * DT); + let now = bounds_x0(&u, r) - u.app.to_page(at).x; + assert!((now - grab).abs() < 1.5, "the layer stays under the pointer: {grab} then {now}"); + release(&mut u, at); +} + +#[test] +fn at_200_percent_the_pan_is_the_same_on_screen_and_the_layer_stays_under_the_pointer() { + let mut u = setup(); + u.app.session.ds_mut().unwrap().view.zoom = 2.0; + u.frame(vec![]); + let (r, p) = centred_rect(&mut u); + let from = pick_up(&mut u, p); + let at = pos2(u.app.canvas.rect.max.x - 2.0, from.y); + hold(&mut u, at, 2); + let (cx0, grab) = (centre(&u).0, bounds_x0(&u, r) - u.app.to_page(at).x); + let n = 30; + hold(&mut u, at, n); + // 520 screen px per second is 260 page units at 200 %. + let pan = centre(&u).0 - cx0; + let want = 520.0 * n as f64 * DT / 2.0; + assert!((pan - want).abs() < 0.5, "panned {pan} page units, wanted {want}"); + let now = bounds_x0(&u, r) - u.app.to_page(at).x; + assert!((now - grab).abs() < 1.0, "the layer stays under the pointer: {grab} then {now}"); + release(&mut u, at); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index fecdc3882..f2bb24b5a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -58,6 +58,8 @@ mod bool_menu_icon_tests; #[cfg(test)] mod branch_ui_tests; #[cfg(test)] +mod canvas_autopan_tests; +#[cfg(test)] mod canvas_double_click_tests; #[cfg(test)] mod canvas_drag_tests; diff --git a/docs/prototyping-parity.md b/docs/prototyping-parity.md index b42457172..e56ab3d67 100644 --- a/docs/prototyping-parity.md +++ b/docs/prototyping-parity.md @@ -1,6 +1,6 @@ # Prototyping parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-10 · **Change:** patch (in the presenter's comment mode (C) a click on the presented frame starts a comment there and the mode stays on for the next one, Escape closes the draft and then the mode, measured in Figma's web app 2026-11-10 (#2209); presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); a connection dragged from a variant, or a layer in it, onto a sibling variant makes Change to, On click, Instant, with the sibling outlined (#2158); `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) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-19 · **Change:** patch (dragging a prototype connection near the canvas edge pans the view toward it, so a link can reach a frame off screen (#2015); in the presenter's comment mode (C) a click on the presented frame starts a comment there and the mode stays on for the next one, Escape closes the draft and then the mode, measured in Figma's web app 2026-11-10 (#2209); presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); a connection dragged from a variant, or a layer in it, onto a sibling variant makes Change to, On click, Instant, with the sibling outlined (#2158); `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, @@ -81,7 +81,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Feature | Status | Notes | |---|---|---| -| Connections drawn and dragged on the canvas; interaction editor | done | | +| Connections drawn and dragged on the canvas; interaction editor | done | dragging a connection out of a layer and holding the pointer within about 15 px of the canvas edge, or past it, pans the view toward it at `40 x (15 - d)` screen px/s (600 at the edge), so a link can reach a frame off screen (measured in Figma at 100%; #2015; `proto_canvas::tests`) | | Several actions per interaction; drag to reorder; conditional blocks with else-if/else | done | one undo step per edit | | Expressions (`count + 1`, `mode(Theme) == "Dark"`, `accent[Dark]`) | done | checked when entered; `proto.evaluate` computes one where a layer's interaction would run (MCP and agents) | | Flows, starting points, descriptions | done | | @@ -108,6 +108,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Date | Change | Summary | |---|---|---| +| 2026-11-07 | patch | M8, #2015: dragging a prototype connection near the canvas edge pans the view, as measured in Figma: while a drag holds the pointer within about 15 px of the edge (or past it) the view pans toward it at 40 px/s for each px closer, up to 600 px/s at the edge, steadily while the pointer stays still; moving layers, the selection box, drawing a shape and dragging a prototype connection (a link can now reach a frame off screen). Resizing, rotating and other drags don't pan. Tests: `view_autopan_tests`, `canvas_autopan_tests`, `proto_canvas::tests`. | | 2026-11-14 | patch | M5, #2352: a chain of variant changes on After delay plays to the end (A to B to C to D); before, the step a variant had fired stayed marked as fired when the instance changed variant, so the chain stopped after one step, and now each step's delay counts from when its variant appears (`crates/ui-egui/src/present/afterdelay_chain_tests.rs`). Numbers unchanged | | 2026-11-09 | patch | M7, #2158: a connection dragged from a variant (or a layer in it) onto a sibling variant of its set did nothing, because the drop looked only for top-level frames and a variant's top-level frame is its set. It now creates Change to the sibling (On click, Instant, as measured in Figma's web app) and outlines the sibling while dragging; the set's background and the variant itself still add nothing, and a frame outside the set still gets Navigate to | | 2026-11-10 | patch | M7, #2209: the presenter's comment mode showed the frame's pins but nothing started a comment. Measured in Figma's web app: with the mode on (C or the bar's comment button) a click on the presented frame drops a pin at the click and opens an "Add a comment" composer beside it; Enter posts, the pin stays at the same frame-relative spot and the mode stays on; a click on the background does nothing; Escape closes a composer, and with none open turns the mode off; the comment shows on the frame in the editor. Now the same: the click starts the draft at the point mapped back through the presenter's placement, the editor's composer is shared, the post carries the frame's page, the player ignores the pointer while the mode is on (no click interactions or hotspots fire), and Escape closes the draft, then the mode. Tests: `comments_tests::a_click_in_the_presenters_comment_mode_adds_a_comment_on_the_frame` and four more. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 6a9d101fd..dab128bf9 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (M8: a Shift-click range in the Layers panel across parents keeps a frame and not its covered children, measured in Figma's web app on 2026-11-12; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); 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 capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (dragging near the canvas edge pans the view toward it, as measured in Figma: 40 px/s for each px within about 15 px of the edge, 600 px/s at it, for moving layers, the selection box, drawing and prototype connections (#2015); M8: a Shift-click range in the Layers panel across parents keeps a frame and not its covered children, measured in Figma's web app on 2026-11-12; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); 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 capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -114,6 +114,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Item | Status | Notes | |---|---|---| | Pan/zoom: wheel, pinch, Space-drag, Shift+0/1/2, Cmd+0, `+`/`-` | done | Shift-wheel pans sideways, pinch and the zoom tool keep the point under the pointer; Preferences ▸ Scroll wheel zoom makes a mouse wheel zoom about the pointer and Cmd/Ctrl+wheel scroll (a wheel told from a trackpad by the device macOS reports, elsewhere by line versus pixel steps; #1390); the arrows pan the view with nothing selected by 64 px, 320 px (five steps) with Shift (`view.pan`; measured in Figma's web app at 100% zoom: one Right press 62–64 px in two trials, Shift+Right about 320 px, reading offsets from screenshots, about ±3 px); Preferences ▸ Invert zoom direction (Figma's Preferences menu has it, checked 2026-11-09; #2145) reverses wheel zoom: Cmd/Ctrl+wheel, and a plain mouse wheel with Scroll wheel zoom on, zoom out where they would zoom in, by the same factor, while a trackpad pinch and panning are unchanged (only the setting's existence was measured, so the pinch is left alone); zoom steps, limits (2%–25,600%) and frame order pinned where the documentation is silent (`view_behaviour_tests`); Zoom to selection (Shift+2) fits the selection into the canvas above the floating bottom toolbar with a 40 pt margin on all four sides, centred in that area, at a continuous zoom (measured in Figma's web app, 2026-11-09; `zoom_to_selection_leaves_forty_points_and_clears_the_toolbar`, `zoom_to_selection_on_a_wide_layer_is_limited_by_the_width`, `zoom_to_selection_without_a_toolbar_inset_uses_the_whole_height`); Zoom to fit (Shift+1) keeps its 64 pt margin, margin not measured yet (`zoom_to_fit_is_unchanged`) | +| Auto-pan when a drag holds the pointer near the canvas edge | done | measured in Figma (web, 100% zoom, held drags; #2015): while a drag holds the pointer within about 15 px of the canvas viewport's edge, or past it, the view pans toward that edge by itself at `40 x (15 - d)` screen px per second (d: px inside the edge, negative outside; 0 at 15 px or more, 120 at 12 px, about 280 at 8 px, 520 at 2 px, 600 at the edge and beyond), steadily while the pointer stays still, no acceleration; two edges (a corner) pan both axes, each by its own distance. Covers moving layers (once past the drag threshold), the selection box (once it has grown past it), drawing a shape and dragging a prototype connection out of a layer, so a link can reach a frame off screen; the layer, box, shape or connection follows the document point under the pointer. Not for resizing, rotating, the hand or Space panning, text selection or vector edits (not measured). Speed taken as screen px per second at every zoom (other zooms not measured). The rule is `ViewState::autopan_velocity`, applied each frame by the canvas (`view_autopan_tests`, `canvas_autopan_tests`, `proto_canvas`) | | Rulers and guides (drag out, move, remove; rotated frames; frame guides) | done | guides belong to the page or a top-level frame (a frame moved into another keeps its guides but they stop applying); a click selects one for Delete, the arrows or the context menu's Remove guide; Alt-drag drops a copy; Alt while dragging measures to the layers in the frame it crosses; ruler numbering checked by eye only | | Frame labels (rotated, right-to-left), size badge | done | | | Outline mode | done | Outlines, outlines for the selection, mask outlines, frame outlines; shapes are clicked on their outlines, reaching layers behind; View ▸ Outlines ▸ Include hidden layers (`view.outlinesHiddenLayers`) outlines hidden layers too and Include object bounds (`view.outlinesObjectBounds`) draws the box of every layer whose outline isn't its box (groups, text, ellipses, vectors); what either draws can be clicked there (a hidden layer on its outline, a group on its box) and nothing else can; both are view settings like the other outline flags (per file, off in a new one, checked in the menu); the lines are light on a dark page (`outline_options_tests`). The main menu now shows a check mark beside every View toggle that is on | @@ -210,6 +211,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-19 | patch | M8, #2015: dragging near the canvas edge pans the view, as measured in Figma: while a drag holds the pointer within about 15 px of the edge (or past it) the view pans toward it at 40 px/s for each px closer, up to 600 px/s at the edge, steadily while the pointer stays still; moving layers, the selection box, drawing a shape and dragging a prototype connection (a link can now reach a frame off screen). Resizing, rotating and other drags don't pan. Tests: `view_autopan_tests`, `canvas_autopan_tests`, `proto_canvas::tests`. | | 2026-11-19 | patch | M8: a Shift-click range in the Layers panel keeps a frame and not its covered children: a range across parents selects a frame whose row is inside it, and drops the rows under that frame, as measured in Figma's web app on 2026-11-12 (Rect 4 in one frame, Shift-click Rect 2 in another: Rect 4 and the second frame, 2 selected); a range among siblings is unchanged; Cmd with Shift reduces the combined set the same way, not measured | | 2026-11-19 | patch | M5, #2360: with a frame selected, a drag that starts on one of its children moves the frame and a click selects the child (a press on a layer inside a selected one drags the selection), as in Figma; Cmd/Ctrl, Shift and layers outside the frame are unchanged. | | 2026-11-18 | patch | M5, #2372: the arrow keys move a layer along the canvas axes inside a rotated parent (the step was applied along the parent's axes, so Down moved a child of a frame rotated 90 degrees sideways); auto layout children are unchanged | From 6b625a0d465992be204e7fda314450e2d9a3c10e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 19 Nov 2026 01:28:57 +0700 Subject: [PATCH 044/114] M6: .fig export writes ruler guides (#2336) (#2337) The change from #2337 by @TrevorBrown-dev, as one commit. --- crates/format/src/fig.rs | 2 + crates/format/src/fig/export.rs | 23 +++- crates/format/src/fig/export/common.rs | 24 +++- crates/format/src/fig/export/layer.rs | 8 +- crates/format/src/fig/guides_tests.rs | 162 +++++++++++++++++++++++++ docs/file-format-parity.md | 8 +- 6 files changed, 212 insertions(+), 15 deletions(-) create mode 100644 crates/format/src/fig/guides_tests.rs diff --git a/crates/format/src/fig.rs b/crates/format/src/fig.rs index 033d4f22d..db799ca70 100644 --- a/crates/format/src/fig.rs +++ b/crates/format/src/fig.rs @@ -25,6 +25,8 @@ mod export; #[cfg(test)] mod export_tests; #[cfg(test)] +mod guides_tests; +#[cfg(test)] mod interop_tests; #[cfg(test)] mod layer_cap_tests; diff --git a/crates/format/src/fig/export.rs b/crates/format/src/fig/export.rs index c0de279c1..d2f548abd 100644 --- a/crates/format/src/fig/export.rs +++ b/crates/format/src/fig/export.rs @@ -154,6 +154,7 @@ message VectorData uint vectorNetworkBlob=1, Vector normalizedSize=2, NodeChange message TextPathStart float tValue=1, bool forward=2 message ArcData float startingAngle=1, float endingAngle=2, float innerRadius=3 message OptionalVector Vector value=1 +message Guide Axis axis=1, float offset=2, GUID guid=3 message LayoutGrid LayoutGridType type=1, Axis axis=2, bool visible=3, int numSections=4, float offset=5, float sectionSize=6, float gutterSize=7, Color color=8, LayoutGridPattern pattern=9, VariableData numSectionsVar=10, VariableData offsetVar=11, VariableData sectionSizeVar=12, VariableData gutterSizeVar=13 struct ExportConstraint ExportConstraintType type, float value message ExportSettings string suffix=1, ImageType imageType=2, ExportConstraint constraint=3 @@ -191,7 +192,7 @@ message GridTrackSizingFunction GridTrackSizingType type=1, float value=2 message GridTrackSize GridTrackSizingFunction minSizing=1, GridTrackSizingFunction maxSizing=2 message GUIDGridTrackSizeMapEntry GUID id=1, GridTrackSize trackSize=2 message GUIDGridTrackSizeMap GUIDGridTrackSizeMapEntry[] entries=1 -message NodeChange GUID guid=1, NodePhase phase=2, ParentIndex parentIndex=3, NodeType type=4, string name=5, bool visible=6, bool locked=7, float opacity=8, BlendMode blendMode=9, Vector size=11, Matrix transform=12, bool mask=16, MaskType maskType=317, float backgroundOpacity=19, bool backgroundEnabled=15, bool internalOnly=142, string description=318, StyleType styleType=163, string sortPosition=320, StyleId styleIdForFill=332, StyleId styleIdForStrokeFill=333, StyleId styleIdForText=334, StyleId styleIdForEffect=335, StyleId styleIdForGrid=336, VariableDataMap variableConsumptionMap=307, VariableModeBySetMap variableModeBySetMap=316, VariableSetMode[] variableSetModes=312, VariableSetID variableSetID=313, VariableResolvedDataType variableResolvedType=314, VariableDataValues variableDataValues=315, VariableScope[] variableScopes=353, DocumentColorProfile documentColorProfile=349, Paint[] fillPaints=38, Paint[] strokePaints=39, float strokeWeight=26, StrokeAlign strokeAlign=29, StrokeJoin strokeJoin=31, StrokeCap strokeCap=30, float[] dashPattern=13, float miterLimit=25, bool borderStrokeWeightsIndependent=299, float borderTopWeight=295, float borderRightWeight=298, float borderBottomWeight=296, float borderLeftWeight=297, Effect[] effects=43, float cornerRadius=20, float cornerSmoothing=160, bool rectangleCornerRadiiIndependent=149, float rectangleTopLeftCornerRadius=145, float rectangleTopRightCornerRadius=146, float rectangleBottomRightCornerRadius=148, float rectangleBottomLeftCornerRadius=147, ConstraintType horizontalConstraint=28, ConstraintType verticalConstraint=37, bool frameMaskDisabled=115, bool resizeToFit=117, bool isStateGroup=225, StateGroupPropertyValueOrder[] stateGroupPropertyValueOrders=238, bool sectionContentsHidden=283, Color backgroundColor=50, StackMode stackMode=105, float stackSpacing=107, float stackCounterSpacing=324, StackWrap stackWrap=323, StackCounterAlignContent stackCounterAlignContent=343, float stackHorizontalPadding=209, float stackVerticalPadding=210, float stackPaddingRight=233, float stackPaddingBottom=234, StackJustify stackPrimaryAlignItems=230, StackAlign stackCounterAlignItems=231, StackSize stackPrimarySizing=229, StackSize stackCounterSizing=221, bool bordersTakeSpace=294, bool stackReverseZIndex=271, float gridColumnGap=438, float gridRowGap=437, GUIDPositionMap gridColumns=436, GUIDPositionMap gridRows=435, GUIDGridTrackSizeMap gridColumnsSizing=474, GUIDGridTrackSizeMap gridRowsSizing=475, float stackChildPrimaryGrow=232, StackCounterAlign stackChildAlignSelf=236, StackPositioning stackPositioning=269, OptionalVector minSize=325, OptionalVector maxSize=326, GUID gridColumnAnchor=440, GUID gridRowAnchor=439, uint gridColumnSpan=442, uint gridRowSpan=441, LayoutGrid[] layoutGrids=47, ExportSettings[] exportSettings=45, TextData textData=42, FontName fontName=41, float fontSize=21, Number lineHeight=40, Number letterSpacing=165, TextCase textCase=34, TextDecoration textDecoration=35, TextAlignHorizontal textAlignHorizontal=32, TextAlignVertical textAlignVertical=33, TextAutoResize textAutoResize=46, TextTruncation textTruncation=280, int maxLines=351, float paragraphSpacing=23, float paragraphIndent=22, float listSpacing=264, LeadingTrim leadingTrim=322, bool hangingPunctuation=337, bool hangingList=339, Hyperlink hyperlink=223, bool autoRename=14, bool fontVariantCommonLigatures=127, bool fontVariantContextualLigatures=128, string fontVersion=202, uint textUserLayoutVersion=203, uint textExplicitLayoutVersion=396, uint textBidiVersion=279, float textTracking=27, bool textDecorationSkipInk=412, EmojiImageSet emojiImageSet=391, uint styleID=49, Path[] fillGeometry=51, Path[] strokeGeometry=52, VectorData vectorData=48, TextPathStart textPathStart=432, VectorMirror handleMirroring=44, uint count=10, float starInnerScale=24, ArcData arcData=195, BooleanOperation booleanOperation=36, string symbolDescription=144, VariableWidthPoint[] variableWidthPoints=447, PluginData[] pluginData=204, SymbolData symbolData=113, NodeChange[] derivedSymbolData=125, GUID overriddenSymbolID=143, ComponentPropDef[] componentPropDefs=266, ComponentPropRef[] componentPropRefs=267, ComponentPropAssignment[] componentPropAssignments=268, VariantPropSpec[] variantPropSpecs=483, VariableDataMap parameterConsumptionMap=445, GUIDPath guidPath=111, PrototypeInteraction[] prototypeInteractions=226, PrototypeStartingPoint prototypeStartingPoint=249, ScrollDirection scrollDirection=159, ScrollBehavior scrollBehavior=186, OverlayPositionType overlayPositionType=198, OverlayBackgroundInteraction overlayBackgroundInteraction=200, OverlayBackgroundAppearance overlayBackgroundAppearance=201, Color prototypeBackgroundColor=141 +message NodeChange GUID guid=1, NodePhase phase=2, ParentIndex parentIndex=3, NodeType type=4, string name=5, bool visible=6, bool locked=7, float opacity=8, BlendMode blendMode=9, Vector size=11, Matrix transform=12, bool mask=16, MaskType maskType=317, float backgroundOpacity=19, bool backgroundEnabled=15, bool internalOnly=142, string description=318, StyleType styleType=163, string sortPosition=320, StyleId styleIdForFill=332, StyleId styleIdForStrokeFill=333, StyleId styleIdForText=334, StyleId styleIdForEffect=335, StyleId styleIdForGrid=336, VariableDataMap variableConsumptionMap=307, VariableModeBySetMap variableModeBySetMap=316, VariableSetMode[] variableSetModes=312, VariableSetID variableSetID=313, VariableResolvedDataType variableResolvedType=314, VariableDataValues variableDataValues=315, VariableScope[] variableScopes=353, DocumentColorProfile documentColorProfile=349, Paint[] fillPaints=38, Paint[] strokePaints=39, float strokeWeight=26, StrokeAlign strokeAlign=29, StrokeJoin strokeJoin=31, StrokeCap strokeCap=30, float[] dashPattern=13, float miterLimit=25, bool borderStrokeWeightsIndependent=299, float borderTopWeight=295, float borderRightWeight=298, float borderBottomWeight=296, float borderLeftWeight=297, Effect[] effects=43, float cornerRadius=20, float cornerSmoothing=160, bool rectangleCornerRadiiIndependent=149, float rectangleTopLeftCornerRadius=145, float rectangleTopRightCornerRadius=146, float rectangleBottomRightCornerRadius=148, float rectangleBottomLeftCornerRadius=147, ConstraintType horizontalConstraint=28, ConstraintType verticalConstraint=37, bool frameMaskDisabled=115, bool resizeToFit=117, bool isStateGroup=225, StateGroupPropertyValueOrder[] stateGroupPropertyValueOrders=238, bool sectionContentsHidden=283, Color backgroundColor=50, StackMode stackMode=105, float stackSpacing=107, float stackCounterSpacing=324, StackWrap stackWrap=323, StackCounterAlignContent stackCounterAlignContent=343, float stackHorizontalPadding=209, float stackVerticalPadding=210, float stackPaddingRight=233, float stackPaddingBottom=234, StackJustify stackPrimaryAlignItems=230, StackAlign stackCounterAlignItems=231, StackSize stackPrimarySizing=229, StackSize stackCounterSizing=221, bool bordersTakeSpace=294, bool stackReverseZIndex=271, float gridColumnGap=438, float gridRowGap=437, GUIDPositionMap gridColumns=436, GUIDPositionMap gridRows=435, GUIDGridTrackSizeMap gridColumnsSizing=474, GUIDGridTrackSizeMap gridRowsSizing=475, float stackChildPrimaryGrow=232, StackCounterAlign stackChildAlignSelf=236, StackPositioning stackPositioning=269, OptionalVector minSize=325, OptionalVector maxSize=326, GUID gridColumnAnchor=440, GUID gridRowAnchor=439, uint gridColumnSpan=442, uint gridRowSpan=441, LayoutGrid[] layoutGrids=47, ExportSettings[] exportSettings=45, TextData textData=42, FontName fontName=41, float fontSize=21, Number lineHeight=40, Number letterSpacing=165, TextCase textCase=34, TextDecoration textDecoration=35, TextAlignHorizontal textAlignHorizontal=32, TextAlignVertical textAlignVertical=33, TextAutoResize textAutoResize=46, TextTruncation textTruncation=280, int maxLines=351, float paragraphSpacing=23, float paragraphIndent=22, float listSpacing=264, LeadingTrim leadingTrim=322, bool hangingPunctuation=337, bool hangingList=339, Hyperlink hyperlink=223, bool autoRename=14, bool fontVariantCommonLigatures=127, bool fontVariantContextualLigatures=128, string fontVersion=202, uint textUserLayoutVersion=203, uint textExplicitLayoutVersion=396, uint textBidiVersion=279, float textTracking=27, bool textDecorationSkipInk=412, EmojiImageSet emojiImageSet=391, uint styleID=49, Path[] fillGeometry=51, Path[] strokeGeometry=52, VectorData vectorData=48, TextPathStart textPathStart=432, VectorMirror handleMirroring=44, uint count=10, float starInnerScale=24, ArcData arcData=195, BooleanOperation booleanOperation=36, string symbolDescription=144, VariableWidthPoint[] variableWidthPoints=447, PluginData[] pluginData=204, SymbolData symbolData=113, NodeChange[] derivedSymbolData=125, GUID overriddenSymbolID=143, ComponentPropDef[] componentPropDefs=266, ComponentPropRef[] componentPropRefs=267, ComponentPropAssignment[] componentPropAssignments=268, VariantPropSpec[] variantPropSpecs=483, VariableDataMap parameterConsumptionMap=445, GUIDPath guidPath=111, PrototypeInteraction[] prototypeInteractions=226, PrototypeStartingPoint prototypeStartingPoint=249, ScrollDirection scrollDirection=159, ScrollBehavior scrollBehavior=186, OverlayPositionType overlayPositionType=198, OverlayBackgroundInteraction overlayBackgroundInteraction=200, OverlayBackgroundAppearance overlayBackgroundAppearance=201, Color prototypeBackgroundColor=141, Guide[] guides=138 struct Blob byte[] bytes message Message MessageType type=1, uint sessionID=2, NodeChange[] nodeChanges=4, Blob[] blobs=6 "; @@ -418,6 +419,8 @@ struct Exporter<'d> { /// Grid tracks of written grid frames: (columns, rows) local ids (session [`AUX`]). tracks: BTreeMap, Vec)>, aux: u32, + /// Session of the last guide's GUID: guides count from the session after [`AUX`], one session each, local id 1. + guide_session: u32, overlays: BTreeMap, trigger_size: [f64; 2], /// Flow starting points: layer → (order, name). @@ -458,6 +461,7 @@ impl<'d> Exporter<'d> { child_defs: BTreeMap::new(), tracks: BTreeMap::new(), aux: 0, + guide_session: AUX, overlays: BTreeMap::new(), trigger_size: [0.0, 0.0], starts: BTreeMap::new(), @@ -475,6 +479,23 @@ impl<'d> Exporter<'d> { } } + /// A node's ruler `guides` field: Y is a horizontal guide and X a vertical one, the offset the ruler's reading (a + /// page's in page coordinates, a frame's in the frame's own). + fn guides(&mut self, guides: &[figcraft_doc::Guide], f: &mut Fields) { + // A guide whose offset isn't finite shows nowhere in the document: it is left out, not written at 0. + let list: Vec> = guides + .iter() + .filter(|g| g.offset.is_finite()) + .map(|g| { + self.guide_session = self.guide_session.saturating_add(1); + o(vec![("axis", e(if g.vertical { "X" } else { "Y" })), ("offset", fl(g.offset)), ("guid", guid(self.guide_session, 1))]) + }) + .collect(); + if !list.is_empty() { + f.push(("guides", arr(list))); + } + } + fn next_aux(&mut self) -> u32 { self.aux += 1; self.aux diff --git a/crates/format/src/fig/export/common.rs b/crates/format/src/fig/export/common.rs index a28951cf8..3ca682682 100644 --- a/crates/format/src/fig/export/common.rs +++ b/crates/format/src/fig/export/common.rs @@ -111,11 +111,22 @@ pub(super) fn scaled(a: &Kv<'static>, b: &Kv<'static>, k: f64, slack: f64) -> bo } } +/// A `guides` list without its guids. Every guide written has a guid of its own, so two layers' guides are the same +/// when their axes and offsets are. +fn bare_guides(v: &Kv<'static>) -> Vec> { + let bare = |g: &Kv<'static>| match g { + Kv::Object(f) => o(f.iter().filter(|(k, _)| *k != "guid").cloned().collect()), + other => other.clone(), + }; + v.list().iter().map(bare).collect() +} + /// The fields of `mine` that differ from `theirs` (a layer and the main's layer it mirrors), and /// the ones only `theirs` has at their empty values. pub(super) fn changed(mine: Fields, theirs: &Fields) -> Fields { + let same = |k: &str, a: &Kv<'static>, b: &Kv<'static>| a == b || (k == "guides" && bare_guides(a) == bare_guides(b)); let cleared: Fields = theirs.iter().filter(|(k, _)| !mine.iter().any(|(mk, _)| mk == k)).filter_map(|(k, _)| Some((*k, unset(k)?))).collect(); - let mut out: Fields = mine.into_iter().filter(|(k, v)| !theirs.iter().any(|(tk, tv)| tk == k && tv == v)).collect(); + let mut out: Fields = mine.into_iter().filter(|(k, v)| !theirs.iter().any(|(tk, tv)| tk == k && same(k, tv, v))).collect(); out.extend(cleared); out } @@ -181,9 +192,14 @@ fn unset(key: &str) -> Option> { } "variableConsumptionMap" | "variableModeBySetMap" | "gridColumnsSizing" | "gridRowsSizing" => o(vec![("entries", arr(Vec::new()))]), "mask" | "rectangleCornerRadiiIndependent" | "borderStrokeWeightsIndependent" => b(false), - "effects" | "dashPattern" | "layoutGrids" | "exportSettings" | "prototypeInteractions" | "fillGeometry" | "variableWidthPoints" => { - arr(Vec::new()) - } + "effects" + | "dashPattern" + | "layoutGrids" + | "exportSettings" + | "prototypeInteractions" + | "fillGeometry" + | "variableWidthPoints" + | "guides" => arr(Vec::new()), "cornerSmoothing" | "stackChildPrimaryGrow" => fl(0.0), "stackMode" => e("NONE"), "stackChildAlignSelf" | "stackPositioning" => e("AUTO"), diff --git a/crates/format/src/fig/export/layer.rs b/crates/format/src/fig/export/layer.rs index 0ab593f1a..3b718cfc2 100644 --- a/crates/format/src/fig/export/layer.rs +++ b/crates/format/src/fig/export/layer.rs @@ -23,9 +23,7 @@ impl<'d> Exporter<'d> { f.extend([("type", e("CANVAS")), ("name", s(&n.name))]); f.extend(root_fields()); f.extend([("backgroundColor", color(*background)), ("backgroundOpacity", fl(background.a.into())), ("backgroundEnabled", b(true))]); - if !n.guides.is_empty() { - self.warn("ruler guides were left out"); - } + self.guides(&n.guides, &mut f); let defaults = figcraft_doc::proto::PrototypeSettings::default(); // Every page writes its colour, so Figma shows the same one (a page without the field shows Figma's own default). // The colour is written opaque: the record measured has alpha 1, and the import reads the colour as opaque and @@ -318,9 +316,7 @@ impl<'d> Exporter<'d> { f.push(("variableConsumptionMap", o(vec![("entries", arr(bound.entries))]))); } self.modes(n, f); - if !n.guides.is_empty() { - self.warn("ruler guides were left out"); - } + self.guides(&n.guides, f); if !n.annotations.is_empty() || !n.dev_resources.is_empty() || !n.code_links.is_empty() diff --git a/crates/format/src/fig/guides_tests.rs b/crates/format/src/fig/guides_tests.rs new file mode 100644 index 000000000..bf4a6a8e8 --- /dev/null +++ b/crates/format/src/fig/guides_tests.rs @@ -0,0 +1,162 @@ +//! Ruler guides in `.fig` exports: a page's and a frame's `guides`, as a synthetic file saved from +//! Figma's web app wrote them. + +use std::collections::BTreeMap; + +use figcraft_doc::{Document, Guide, NodeId, NodeKind}; + +use super::kiwi::Kv; +use super::{Archive, decode_canvas, export}; + +/// A document with a page guide at `page` and a frame guide at `frame` (both vertical and +/// horizontal), and the frame's id. +fn doc_with(page: &[Guide], frame: &[Guide]) -> (Document, NodeId) { + let mut doc = Document::new("t"); + let p = doc.first_page().unwrap(); + let f = doc.create(p, NodeKind::Frame, "Frame 1", 1000.0, 500.0, 400.0, 300.0).unwrap(); + doc.node_mut(p).unwrap().guides = page.to_vec(); + doc.node_mut(f).unwrap().guides = frame.to_vec(); + (doc, f) +} + +fn vertical(offset: f64) -> Guide { + Guide { vertical: true, offset } +} + +fn horizontal(offset: f64) -> Guide { + Guide { vertical: false, offset } +} + +/// The `guides` of the CANVAS record and of the FRAME record, as (axis, offset, sessionID, localID). +type Written = Option>; + +fn written(doc: &Document) -> (Written, Written, Vec) { + let (bytes, warnings) = export(doc, None).unwrap(); + let archive = Archive::open(&bytes).unwrap(); + let (schema, message) = decode_canvas(&archive.canvas).unwrap(); + let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap(); + let nodes = msg.get("nodeChanges").unwrap().list(); + let of = |ty: &str| { + let n = nodes + .iter() + .find(|n| n.get("type").and_then(Kv::str) == Some(ty) && n.get("name").and_then(Kv::str) != Some("Internal Only Canvas")) + .unwrap(); + n.get("guides").map(|g| { + g.list() + .iter() + .map(|x| { + let id = x.get("guid").unwrap(); + ( + x.get("axis").and_then(Kv::str).unwrap().to_string(), + x.get("offset").and_then(Kv::f64).unwrap() as f32, + id.get("sessionID").and_then(Kv::f64).unwrap() as u64, + id.get("localID").and_then(Kv::f64).unwrap() as u64, + ) + }) + .collect() + }) + }; + (of("CANVAS"), of("FRAME"), warnings) +} + +/// A component with a vertical guide at 24 that holds a frame with a vertical guide at 7, and an instance of it as the +/// engine makes one: its root a copy of the main's, guides included, and its layer mirroring the main's. Returns the +/// instance. +fn component_and_instance() -> (Document, NodeId) { + let mut doc = Document::new("t"); + let p = doc.first_page().unwrap(); + let kind = NodeKind::Component { description: String::new(), props: BTreeMap::new(), prop_order: Vec::new() }; + let main = doc.create(p, kind, "Card", 0.0, 0.0, 200.0, 100.0).unwrap(); + let inner = doc.create(main, NodeKind::Frame, "Inner", 20.0, 30.0, 100.0, 50.0).unwrap(); + doc.node_mut(main).unwrap().guides = vec![vertical(24.0)]; + doc.node_mut(inner).unwrap().guides = vec![vertical(7.0)]; + let inst = doc.alloc_id(); + let mut root = doc.node(main).unwrap().clone(); + (root.id, root.kind, root.parent, root.source) = (inst, NodeKind::Instance { component: main, props: BTreeMap::new() }, None, Some(main)); + root.children.clear(); + doc.insert(root, p, None).unwrap(); + let mut layer = doc.node(inner).unwrap().clone(); + (layer.id, layer.parent, layer.source) = (doc.alloc_id(), None, Some(inner)); + doc.insert(layer, inst, None).unwrap(); + (doc, inst) +} + +/// The `guides` of every instance override row in the file, as (axis, offset). +fn overridden(doc: &Document) -> Vec> { + let (bytes, _) = export(doc, None).unwrap(); + let archive = Archive::open(&bytes).unwrap(); + let (schema, message) = decode_canvas(&archive.canvas).unwrap(); + let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap(); + let nodes = msg.get("nodeChanges").unwrap().list(); + let rows = nodes.iter().flat_map(|n| n.get("symbolData").and_then(|d| d.get("symbolOverrides")).map(Kv::list).unwrap_or_default()); + rows.filter_map(|row| row.get("guides")) + .map(|g| { + g.list() + .iter() + .map(|x| (x.get("axis").and_then(Kv::str).unwrap().to_string(), x.get("offset").and_then(Kv::f64).unwrap() as f32)) + .collect() + }) + .collect() +} + +#[test] +fn a_page_guide_at_120_and_a_frame_guide_at_40_are_written_as_figma_writes_them() { + let (doc, _) = doc_with(&[horizontal(120.0), vertical(120.0)], &[horizontal(40.0), vertical(40.0)]); + let (page, frame, warnings) = written(&doc); + // Axis Y is a horizontal guide and X a vertical one; the offsets are the ruler readings (a frame's in its own + // coordinates); localID is 1 and sessionID counts the file's guides from 3. + assert_eq!(page, Some(vec![("Y".into(), 120.0, 3, 1), ("X".into(), 120.0, 4, 1)])); + assert_eq!(frame, Some(vec![("Y".into(), 40.0, 5, 1), ("X".into(), 40.0, 6, 1)])); + assert!(warnings.iter().all(|w| !w.contains("ruler guides")), "{warnings:?}"); +} + +#[test] +fn a_frame_without_guides_and_a_page_without_guides_write_no_field() { + let (doc, _) = doc_with(&[], &[]); + let (page, frame, warnings) = written(&doc); + assert_eq!(page, None); + assert_eq!(frame, None); + assert!(warnings.iter().all(|w| !w.contains("ruler guides")), "{warnings:?}"); +} + +#[test] +fn a_frame_guide_is_not_shifted_by_the_frames_position() { + let (doc, _) = doc_with(&[], &[vertical(78.0)]); + let (_, frame, _) = written(&doc); + assert_eq!(frame, Some(vec![("X".into(), 78.0, 3, 1)])); +} + +#[test] +fn an_instance_overrides_guides_only_where_they_differ_from_its_mains() { + let (mut doc, inst) = component_and_instance(); + // Untouched: the instance's guides and its layer's are the main's. + assert_eq!(overridden(&doc), Vec::>::new()); + // Its own guide: one override, on the instance. + doc.node_mut(inst).unwrap().guides = vec![horizontal(60.0)]; + assert_eq!(overridden(&doc), vec![vec![("Y".to_string(), 60.0)]]); + // Its guides removed: an empty list, or it would show the main's. + doc.node_mut(inst).unwrap().guides.clear(); + assert_eq!(overridden(&doc), vec![Vec::new()]); +} + +#[test] +fn a_guide_whose_offset_is_not_finite_is_left_out() { + let (doc, _) = doc_with(&[vertical(f64::NAN), vertical(10.0), horizontal(f64::INFINITY)], &[horizontal(f64::NEG_INFINITY)]); + let (page, frame, _) = written(&doc); + assert_eq!(page, Some(vec![("X".into(), 10.0, 3, 1)])); + assert_eq!(frame, None); +} + +#[test] +fn the_schema_numbers_the_guides() { + let s = super::kiwi::Schema::parse(super::export::SCHEMA).unwrap(); + let def = |n: &str| s.defs.iter().find(|d| d.name == n).unwrap(); + let field = |d: &str, f: &str| def(d).fields.iter().find(|x| x.name == f).unwrap().value; + assert_eq!(field("NodeChange", "guides"), 138); + assert_eq!(field("Guide", "axis"), 1); + assert_eq!(field("Guide", "offset"), 2); + assert_eq!(field("Guide", "guid"), 3); + let axis = def("Axis"); + assert_eq!(axis.fields.iter().find(|x| x.name == "X").unwrap().value, 0); + assert_eq!(axis.fields.iter().find(|x| x.name == "Y").unwrap().value, 1); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index cee929d66..c5d777bcf 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (`.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; 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 Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (`.fig` export writes ruler guides (#2336); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; 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 Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of `/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's @@ -90,7 +90,7 @@ an inherited style link keep their own values and the link; stale copies on the still yield to the style. These cases have synthetic export/import regressions, including nested scales and empty-style clears; they have not been checked in other software. -- **Written:** pages (name, background, prototype background as an opaque colour, for every page); frames, groups, sections, rectangles (as rounded +- **Written:** pages (name, background, ruler guides, prototype background as an opaque colour, for every page); the ruler guides of frames, components and instances, in the layer's own coordinates; frames, groups, sections, rectangles (as rounded rectangles, with their four radii), ellipses (arcs), polygons, stars, lines, vectors (editable network blobs with per-point corner radius, handle mirroring, caps and joins, each filled area's own paints, plus the outline of their filled areas), text, boolean groups, slices; the fill outline of frames and shapes and the @@ -136,8 +136,7 @@ scales and empty-style clears; they have not been checked in other software. properties, arc fields, font weight: written as the values they give), text styles on part of a text (written as values), the paint frames of vector regions, variables' publishing, code syntax and inheritance settings, extended collections (written as collections of their own), comments, Developer Mode annotations, statuses, - resources, measurements and code links, plugin data, ruler - guides, a page's prototype device settings (device, rotation, colour, custom size, responsive), the opacity of a page's prototype background (written opaque), slot properties and slot content, brush + resources, measurements and code links, plugin data, a page's prototype device settings (device, rotation, colour, custom size, responsive), the opacity of a page's prototype background (written opaque), slot properties and slot content, brush strokes (written plain), strokes wider on one side of their path (written as filled outlines, or with the width on both sides when the shape has a fill too), pattern fills, WebP export settings (written as PNG), glass settings other than frost, springs other than Gentle (written as ease @@ -196,6 +195,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | M6, #2336: `.fig` export writes ruler guides: a page's and a frame's `guides` (each an `Axis` Y for a horizontal guide and X for a vertical one, the offset as the ruler reads it, a frame's in its own coordinates, and a guid of its own: local id 1 and a session id counted up from 3), as measured on a page and an unrotated frame in a synthetic file saved from Figma's web app. The "ruler guides were left out" warnings are gone. An instance writes a `guides` override only where its guides differ from its main's, and a guide whose offset isn't finite is left out. Our own import does not read guides yet, so this is checked by reading the written records only, not in other software. Numbers unchanged. | | 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. | | 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Pasted content from other apps, PNG. | | 2026-11-12 | minor | M6, #2302: the `.fig` export writes the paints of a vector's own regions: each region with paints of its own (an empty list means unfilled) names an entry of the network's style table (`styleOverrideTable[].fillPaints`), equal lists share one entry, and a region without paints writes style 0. The fill outline is still one path with style 0. A region's kept paint frame is still left out, with a narrower warning. The importer already read this; not checked in other software | From 0d70c332b13499d736954240c973aa470e365a9d Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 19 Nov 2026 02:00:46 +0700 Subject: [PATCH 045/114] M12: boards: code blocks (doc and engine): a board code block that hugs its lines, with a language (#2237) (#2282) The change from #2282 by @TrevorBrown-dev, as one commit. --- ROADMAP.md | 2 +- crates/doc/src/board.rs | 15 +- crates/doc/src/board_code.rs | 130 ++++++ crates/doc/src/board_code_tests.rs | 58 +++ crates/doc/src/lib.rs | 4 + crates/engine/src/board_code_tests.rs | 541 ++++++++++++++++++++++ crates/engine/src/board_tests.rs | 3 + crates/engine/src/boards/board.rs | 18 +- crates/engine/src/boards/board/code.rs | 260 +++++++++++ crates/engine/src/boards/board/derived.rs | 1 + crates/engine/src/boards/board/edit.rs | 2 +- crates/engine/src/boards/board/items.rs | 9 +- crates/engine/src/canvas/textedit.rs | 20 +- crates/engine/src/cmd/text.rs | 2 +- crates/engine/src/lib.rs | 2 + crates/ui-egui/src/canvas/board_bar.rs | 2 +- docs/boards-parity.md | 6 +- docs/gaps.md | 5 +- docs/mcp.md | 15 +- docs/roadmap.md | 3 +- 20 files changed, 1081 insertions(+), 17 deletions(-) create mode 100644 crates/doc/src/board_code.rs create mode 100644 crates/doc/src/board_code_tests.rs create mode 100644 crates/engine/src/board_code_tests.rs create mode 100644 crates/engine/src/boards/board/code.rs diff --git a/ROADMAP.md b/ROADMAP.md index 107a11f96..5924750e6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-18 · **Change:** minor (library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through diff --git a/crates/doc/src/board.rs b/crates/doc/src/board.rs index eb0594bab..999631aed 100644 --- a/crates/doc/src/board.rs +++ b/crates/doc/src/board.rs @@ -10,7 +10,7 @@ use figcraft_geom::kurbo::{Ellipse, RoundedRect}; use figcraft_geom::{BezPath, Point, Rect, Shape, Vec2}; use serde::{Deserialize, Serialize}; -use crate::NodeId; +use crate::{CodeLanguage, NodeId}; /// What a file is for: designing screens, or a board to think together on. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -65,6 +65,12 @@ pub enum BoardItem { /// A mind map's node: a frame hugging its text, with no outline. What it hangs from is the /// branch (a connector with `branch`) arriving at it. MindNode, + /// A code block: a dark panel holding one monospace text (its first text layer), as wide as + /// it was made and as tall as its lines. `language` picks the highlighting. + CodeBlock { + #[serde(default)] + language: CodeLanguage, + }, } impl BoardItem { @@ -79,12 +85,16 @@ impl BoardItem { | BoardItem::Stamp { .. } | BoardItem::Table | BoardItem::MindNode + | BoardItem::CodeBlock { .. } ) } /// Objects whose first text layer is their text (a double-click or Enter edits it). pub fn has_text(&self) -> bool { - matches!(self, BoardItem::Sticky { .. } | BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::MindNode) + matches!( + self, + BoardItem::Sticky { .. } | BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::MindNode | BoardItem::CodeBlock { .. } + ) } /// Who made it (stickies and stamps; empty when unknown). @@ -127,6 +137,7 @@ impl BoardItem { BoardItem::Ink => "ink", BoardItem::Table => "table", BoardItem::MindNode => "mindNode", + BoardItem::CodeBlock { .. } => "codeBlock", } } } diff --git a/crates/doc/src/board_code.rs b/crates/doc/src/board_code.rs new file mode 100644 index 000000000..b31487c25 --- /dev/null +++ b/crates/doc/src/board_code.rs @@ -0,0 +1,130 @@ +//! Code blocks (#2237): the languages a block is highlighted as, and the numbers of its look. +//! Pure data: the engine makes the block ([`crate::BoardItem::CodeBlock`]). + +use figcraft_color::Color; +use serde::{Deserialize, Serialize}; + +/// The language a code block is highlighted as. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum CodeLanguage { + Bash, + Cpp, + Css, + Go, + Graphql, + Html, + Javascript, + Json, + Kotlin, + PlainText, + Python, + Ruby, + Rust, + Sql, + Swift, + #[default] + Typescript, +} + +impl CodeLanguage { + /// In menu order: by name. + pub const ALL: [CodeLanguage; 16] = [ + CodeLanguage::Bash, + CodeLanguage::Cpp, + CodeLanguage::Css, + CodeLanguage::Go, + CodeLanguage::Graphql, + CodeLanguage::Html, + CodeLanguage::Javascript, + CodeLanguage::Json, + CodeLanguage::Kotlin, + CodeLanguage::PlainText, + CodeLanguage::Python, + CodeLanguage::Ruby, + CodeLanguage::Rust, + CodeLanguage::Sql, + CodeLanguage::Swift, + CodeLanguage::Typescript, + ]; + + /// The id used in commands and saved files ("cpp", "plainText", "typescript"). + pub fn id(self) -> &'static str { + match self { + CodeLanguage::Bash => "bash", + CodeLanguage::Cpp => "cpp", + CodeLanguage::Css => "css", + CodeLanguage::Go => "go", + CodeLanguage::Graphql => "graphql", + CodeLanguage::Html => "html", + CodeLanguage::Javascript => "javascript", + CodeLanguage::Json => "json", + CodeLanguage::Kotlin => "kotlin", + CodeLanguage::PlainText => "plainText", + CodeLanguage::Python => "python", + CodeLanguage::Ruby => "ruby", + CodeLanguage::Rust => "rust", + CodeLanguage::Sql => "sql", + CodeLanguage::Swift => "swift", + CodeLanguage::Typescript => "typescript", + } + } + + /// The name shown in the UI ("C++", "Plain text", "TypeScript"). + pub fn label(self) -> &'static str { + match self { + CodeLanguage::Bash => "Bash", + CodeLanguage::Cpp => "C++", + CodeLanguage::Css => "CSS", + CodeLanguage::Go => "Go", + CodeLanguage::Graphql => "GraphQL", + CodeLanguage::Html => "HTML", + CodeLanguage::Javascript => "JavaScript", + CodeLanguage::Json => "JSON", + CodeLanguage::Kotlin => "Kotlin", + CodeLanguage::PlainText => "Plain text", + CodeLanguage::Python => "Python", + CodeLanguage::Ruby => "Ruby", + CodeLanguage::Rust => "Rust", + CodeLanguage::Sql => "SQL", + CodeLanguage::Swift => "Swift", + CodeLanguage::Typescript => "TypeScript", + } + } + + /// By id or by name, in any case, trimmed ("cpp", "C++", "plain text"). + pub fn from_id(s: &str) -> Option { + let s = s.trim(); + CodeLanguage::ALL.into_iter().find(|l| l.id().eq_ignore_ascii_case(s) || l.label().eq_ignore_ascii_case(s)) + } +} + +/// The font code is set in (always this family; the machine finds the nearest when it is absent). +pub const CODE_FONT: &str = "Liberation Mono"; +pub const CODE_FONT_SIZE: f64 = 16.0; +/// A line of code: 150% of the size. +pub const CODE_LINE: f64 = 24.0; +/// Room around the code: top, right, bottom, left (the left holds the line numbers). +pub const CODE_PAD: [f64; 4] = [16.0, 16.0, 16.0, 64.0]; +pub const CODE_MIN_LINES: usize = 4; +/// A block's least height: four lines. +pub const CODE_MIN_H: f64 = 128.0; +pub const CODE_WIDTH: f64 = 576.0; +pub const CODE_MIN_W: f64 = 210.0; +pub const CODE_MAX_W: f64 = 100_000.0; +/// The room between a block and the next one made beside it. +pub const CODE_GAP: f64 = 128.0; +pub const CODE_RADIUS: f64 = 10.0; +/// What Tab types in a block. +pub const CODE_TAB: &str = " "; +/// The most characters `board.codeBlock` takes. +pub const CODE_MAX_CHARS: usize = 100_000; +/// The panel: the board's ink. +pub const CODE_PANEL: Color = Color::from_rgb8_const(0x1E, 0x1E, 0x1E); +/// Plain code: the board's gray. +pub const CODE_TEXT: Color = Color::from_rgb8_const(0xE3, 0xE1, 0xDD); + +/// A block's height holding `lines` visual lines (four at least): 32 + 24 a line. +pub fn code_height(lines: usize) -> f64 { + CODE_PAD[0] + CODE_PAD[2] + CODE_LINE * lines.clamp(CODE_MIN_LINES, 1_000_000) as f64 +} diff --git a/crates/doc/src/board_code_tests.rs b/crates/doc/src/board_code_tests.rs new file mode 100644 index 000000000..4f8ec0bb9 --- /dev/null +++ b/crates/doc/src/board_code_tests.rs @@ -0,0 +1,58 @@ +//! Code blocks (#2237): the languages, the saved item, the height rule and the colours. + +use serde_json::json; + +use crate::BoardItem; +use crate::board_code::{CODE_MIN_H, CODE_PAD, CODE_PANEL, CODE_TEXT, CodeLanguage, code_height}; + +#[test] +fn sixteen_languages_by_name_with_typescript_the_default() { + assert_eq!(CodeLanguage::ALL.len(), 16); + let ids: std::collections::BTreeSet<&str> = CodeLanguage::ALL.iter().map(|l| l.id()).collect(); + assert_eq!(ids.len(), 16, "ids are unique"); + let labels: Vec = CodeLanguage::ALL.iter().map(|l| l.label().to_lowercase()).collect(); + assert!(labels.windows(2).all(|w| w[0] < w[1]), "labels ascend: {labels:?}"); + for l in CodeLanguage::ALL { + assert_eq!(CodeLanguage::from_id(l.id()), Some(l)); + assert_eq!(CodeLanguage::from_id(l.label()), Some(l)); + assert_eq!(serde_json::to_value(l).unwrap(), json!(l.id())); + } + assert_eq!(CodeLanguage::from_id("CPP"), Some(CodeLanguage::Cpp)); + assert_eq!(CodeLanguage::from_id("c++"), Some(CodeLanguage::Cpp)); + assert_eq!(CodeLanguage::from_id(" plain text "), Some(CodeLanguage::PlainText)); + assert_eq!(CodeLanguage::from_id("markdown"), None); + assert_eq!(CodeLanguage::from_id(""), None); + assert_eq!(CodeLanguage::default(), CodeLanguage::Typescript); +} + +#[test] +fn a_code_block_item_saves_its_language() { + let item = BoardItem::CodeBlock { language: CodeLanguage::Rust }; + let v = json!({"type": "codeBlock", "language": "rust"}); + assert_eq!(serde_json::to_value(&item).unwrap(), v); + assert_eq!(serde_json::from_value::(v).unwrap(), item); + let plain: BoardItem = serde_json::from_value(json!({"type": "codeBlock"})).unwrap(); + assert_eq!(plain, BoardItem::CodeBlock { language: CodeLanguage::Typescript }); + assert!(serde_json::from_value::(json!({"type": "codeBlock", "language": "klingon"})).is_err()); + assert_eq!(item.kind_id(), "codeBlock"); + assert!(item.is_atom()); + assert!(item.has_text()); +} + +#[test] +fn the_height_is_32_and_24_a_line_from_four_lines_up() { + assert_eq!(code_height(0), 128.0); + assert_eq!(code_height(1), 128.0); + assert_eq!(code_height(4), 128.0); + assert_eq!(code_height(5), 152.0); + assert_eq!(code_height(9), 248.0); + assert!(code_height(usize::MAX).is_finite()); + assert_eq!(CODE_MIN_H, code_height(0)); + assert_eq!(CODE_PAD[0] + CODE_PAD[2], 32.0); + assert_eq!(CODE_PAD[1] + CODE_PAD[3], 80.0); +} + +#[test] +fn plain_code_reads_on_the_panel() { + assert!(CODE_TEXT.contrast(CODE_PANEL) >= 4.5, "{}", CODE_TEXT.contrast(CODE_PANEL)); +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index e0dd356e1..170da1a25 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -9,6 +9,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod board; +mod board_code; mod board_mindmap; mod board_route; pub mod colors; @@ -28,6 +29,7 @@ pub mod vector_faces; pub mod vector_regions; pub use board::*; +pub use board_code::*; pub use board_mindmap::{MIND_GAP_X, MIND_GAP_Y, MIND_MAX_DEPTH, MIND_MAX_NODES, MindBox, mind_layout}; pub use board_route::{END_GAP, MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points}; pub use colors::*; @@ -1321,6 +1323,8 @@ fn remap_action(a: &mut proto::Action, map: &BTreeMap) { #[cfg(test)] mod blur_tests; #[cfg(test)] +mod board_code_tests; +#[cfg(test)] mod board_mindmap_tests; #[cfg(test)] mod board_route_tests; diff --git a/crates/engine/src/board_code_tests.rs b/crates/engine/src/board_code_tests.rs new file mode 100644 index 000000000..97fc6bfdc --- /dev/null +++ b/crates/engine/src/board_code_tests.rs @@ -0,0 +1,541 @@ +//! Code blocks (#2237): `board.codeBlock` and `board.setLanguage`, the pass that keeps a block as +//! tall as its lines and its text plain code, and the text editor's three literal-typing lines. + +use figcraft_color::{Color, Paint}; +use figcraft_doc::{ + BoardItem, CODE_FONT, CODE_MAX_CHARS, CodeLanguage, EffectKind, FileKind, LayoutMode, LineHeight, ListStyle, NodeId, NodeKind, Sizing, + TextAlignH, TextAutoResize, TextCase, TextData, TextDecoration, +}; +use figcraft_geom::Rect; +use serde_json::{Value, json}; + +use crate::board::{is_code_text, text_of}; +use crate::board_tests::{board, id, node}; +use crate::collab_live_tests::Room; +use crate::tools::{PointerEvent, PointerKind}; +use crate::{EngineError, Session}; + +fn bx(s: &Session, id: NodeId) -> Rect { + s.doc().unwrap().world_bounds(id).unwrap() +} + +fn td(s: &Session, block: NodeId) -> TextData { + let t = text_of(s.doc().unwrap(), block).unwrap(); + match node(s, t).kind { + NodeKind::Text(td) => td, + other => panic!("not text: {other:?}"), + } +} + +/// `board.codeBlock` with `p`: the frame and its text. +fn block(s: &mut Session, p: Value) -> (NodeId, NodeId) { + let out = s.execute("board.codeBlock", &p).unwrap(); + (id(&out, "id"), id(&out, "text")) +} + +/// How many visual lines the text lays out in. +fn lines(s: &Session, text: NodeId) -> usize { + let n = node(s, text); + figcraft_text::layout_node(&n).map_or(0, |(l, _)| l.lines.len()) +} + +fn solid(hex: (u8, u8, u8)) -> Vec { + vec![Paint::solid(Color::from_rgb8_const(hex.0, hex.1, hex.2))] +} + +fn ten(n: usize) -> String { + vec!["x"; n].join("\n") +} + +fn drag(s: &mut Session, from: (f64, f64), to: (f64, f64)) { + s.pointer(&PointerEvent::at(PointerKind::Down, from.0, from.1, 1.0)).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::Move, (from.0 + to.0) / 2.0, (from.1 + to.1) / 2.0, 1.0)).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::Move, to.0, to.1, 1.0)).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::Up, to.0, to.1, 1.0)).unwrap(); +} + +fn undo(s: &mut Session) { + s.execute("edit.undo", &json!({})).unwrap(); +} + +#[test] +fn a_code_block_is_a_dark_panel_576_by_128_holding_one_monospace_text() { + let mut s = board(); + let before = s.doc().unwrap().ids().count(); + let depth = s.undo_depth().0; + let out = s.execute("board.codeBlock", &json!({"x": 100, "y": 200})).unwrap(); + assert_eq!(out["language"], json!("typescript")); + let (f, t) = (id(&out, "id"), id(&out, "text")); + let n = node(&s, f); + assert_eq!(n.board, Some(BoardItem::CodeBlock { language: CodeLanguage::Typescript })); + assert!(n.is_board_atom()); + let r = bx(&s, f); + assert_eq!((r.x0, r.y0, r.x1, r.y1), (100.0, 200.0, 676.0, 328.0)); + assert_eq!(n.fills, solid((0x1E, 0x1E, 0x1E))); + assert_eq!(n.corners.radii, [10.0; 4]); + assert_eq!(n.effects.iter().filter(|e| matches!(e.kind, EffectKind::DropShadow(_))).count(), 1); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.padding), (LayoutMode::Vertical, [16.0, 16.0, 16.0, 64.0])); + assert_eq!(n.child_layout.sizing_v, Sizing::Hug); + assert_eq!((n.child_layout.min_h, n.child_layout.min_w), (Some(128.0), Some(210.0))); + assert_eq!(n.children, vec![t]); + let tr = bx(&s, t); + assert_eq!((tr.x0, tr.y0, tr.width()), (164.0, 216.0, 496.0)); + let d = td(&s, f); + assert_eq!(d.characters, ""); + assert_eq!((d.style.font_family.as_str(), d.style.font_style.as_str(), d.style.font_size), (CODE_FONT, "Regular", 16.0)); + assert_eq!(d.style.line_height, LineHeight::Percent(150.0)); + assert_eq!((d.auto_resize, d.align_h), (TextAutoResize::Height, TextAlignH::Left)); + assert_eq!(node(&s, t).fills, solid((0xE3, 0xE1, 0xDD))); + assert_eq!((d.features.get("liga"), d.features.get("calt")), (Some(&false), Some(&false))); + assert!(d.runs.is_empty()); + assert_eq!(d.list, ListStyle::None); + assert_eq!(s.selection(), vec![f]); + assert_eq!(s.undo_depth().0, depth + 1); + undo(&mut s); + assert_eq!(s.doc().unwrap().ids().count(), before); +} + +#[test] +fn a_block_without_a_place_is_centred_and_edit_asks_for_typing() { + let mut s = board(); + // Centred on the view without a place. + let (vx, vy) = { + let v = &s.ds().unwrap().view; + (v.cx, v.cy) + }; + let (f, _) = block(&mut s, json!({})); + let r = bx(&s, f); + assert_eq!((r.x0, r.y0), (vx - 288.0, vy - 64.0)); + // Typing starts in it on request. + let (f, _) = block(&mut s, json!({"x": 0, "y": 500, "edit": true})); + assert!(s.ui_requests.iter().any(|q| q.kind == "board.editText" && q.data["id"] == json!(f))); +} + +#[test] +fn the_height_is_its_lines_24_each_and_never_under_four() { + let mut s = board(); + let heights = [("a", 128.0), ("a\nb\nc\nd", 128.0), ("a\nb\nc\nd\ne", 152.0)]; + for (text, h) in heights { + let (f, _) = block(&mut s, json!({"x": 100, "y": 200, "text": text})); + let r = bx(&s, f); + assert_eq!((r.x0, r.y0, r.height()), (100.0, 200.0, h), "{text:?}"); + } + let (f, t) = block(&mut s, json!({"x": 100, "y": 200, "text": ten(9)})); + assert_eq!(bx(&s, f).height(), 248.0); + assert_eq!(bx(&s, t).height(), 216.0); + s.execute("text.set", &json!({"id": t, "characters": "a\nb"})).unwrap(); + let r = bx(&s, f); + assert_eq!((r.x0, r.y0, r.height()), (100.0, 200.0, 128.0)); +} + +#[test] +fn long_lines_wrap_and_each_visual_line_adds_24() { + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": "ab ".repeat(400)})); + let n = lines(&s, t); + assert!(n >= 3, "{n}"); + assert_eq!(bx(&s, f).height(), 32.0 + 24.0 * n as f64); + assert_eq!(bx(&s, t).width(), 496.0); + if figcraft_text::has_family(CODE_FONT) { + let (f, _) = block(&mut s, json!({"x": 0, "y": 0, "width": 976, "text": "x".repeat(93)})); + assert_eq!(bx(&s, f).height(), 128.0); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "width": 976, "text": "x".repeat(94)})); + assert_eq!(lines(&s, t), 2); + assert_eq!(bx(&s, f).height(), 128.0); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "width": 976, "text": format!("{}\na\nb\nc", "x".repeat(94))})); + assert_eq!(lines(&s, t), 5); + assert_eq!(bx(&s, f).height(), 152.0); + } +} + +#[test] +fn only_the_width_is_the_users() { + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 100, "y": 200, "text": ten(9)})); + assert_eq!(bx(&s, f).height(), 248.0); + s.execute("node.set", &json!({"id": f, "props": {"height": 400}})).unwrap(); + assert_eq!(bx(&s, f).height(), 248.0); + assert_eq!(node(&s, f).child_layout.sizing_v, Sizing::Hug); + s.execute("transform.resize", &json!({"ids": [f], "width": 300, "height": 500})).unwrap(); + let r = bx(&s, f); + assert_eq!((r.width(), r.height(), bx(&s, t).width()), (300.0, 248.0, 220.0)); + s.execute("node.set", &json!({"id": f, "props": {"width": 100}})).unwrap(); + assert_eq!((bx(&s, f).width(), bx(&s, t).width()), (210.0, 130.0)); + + // A pointer drag of the bottom-right handle. + let mut s = board(); + let (f, _) = block(&mut s, json!({"x": 100, "y": 200})); + let depth = s.undo_depth().0; + drag(&mut s, (676.0, 328.0), (876.0, 628.0)); + let r = bx(&s, f); + assert_eq!((r.x0, r.y0, r.width(), r.height()), (100.0, 200.0, 776.0, 128.0)); + assert_eq!(s.undo_depth().0, depth + 1); + undo(&mut s); + let r = bx(&s, f); + assert_eq!((r.width(), r.height()), (576.0, 128.0)); + + // A narrower block wraps into more lines and grows. + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": "ab ".repeat(400)})); + let was = lines(&s, t); + s.execute("node.set", &json!({"id": f, "props": {"width": 300}})).unwrap(); + let now = lines(&s, t); + assert!(now > was, "{now} > {was}"); + assert_eq!(bx(&s, f).height(), 32.0 + 24.0 * now as f64); +} + +/// A block settled after `how` made it incoherent: still 5 lines tall, 576 wide, hugging, with +/// its layout, and a second pass changes nothing. +fn settled_after(how: impl Fn(&mut Session, NodeId)) { + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": ten(4)})); + how(&mut s, f); + s.execute("text.set", &json!({"id": t, "characters": ten(5)})).unwrap(); + let n = node(&s, f); + assert!(n.layout.is_some(), "the layout is restored"); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug)); + assert_eq!((bx(&s, f).width(), bx(&s, f).height()), (576.0, 152.0)); + assert_eq!(node(&s, t).child_layout.sizing_h, Sizing::Fill); + let doc = s.doc().unwrap().clone(); + let mut again = doc.clone(); + again.mark_dirty(doc.ids().collect::>()); + crate::normalize(&mut again, &doc); + assert_eq!(again, doc, "a second pass changes nothing"); +} + +#[test] +fn the_pass_keeps_a_blocks_layout_and_width_sizing() { + settled_after(|s, f| { + s.execute("layout.remove", &json!({"ids": [f]})).unwrap(); + }); + settled_after(|s, f| { + s.execute("node.set", &json!({"id": f, "props": {"layout": null}})).unwrap(); + }); + settled_after(|s, f| { + s.execute("node.set", &json!({"id": f, "props": {"sizingH": "hug"}})).unwrap(); + }); +} + +#[test] +fn a_block_in_a_section_without_a_place_is_centred_on_the_view_too() { + let mut s = board(); + let (vx, vy) = { + let v = &s.ds().unwrap().view; + (v.cx, v.cy) + }; + let sec = id(&s.execute("node.create", &json!({"type": "section", "x": 1000, "y": 500, "width": 4000, "height": 4000})).unwrap(), "id"); + let (f, _) = block(&mut s, json!({"parent": sec})); + assert_eq!(node(&s, f).parent, Some(sec)); + let r = bx(&s, f); + assert_eq!((r.x0, r.y0), (vx - 288.0, vy - 64.0), "on the page, where a block on the page would be"); +} + +#[test] +fn a_block_in_a_turned_frame_without_a_place_is_centred_on_the_view_and_a_given_place_is_the_frames() { + let mut s = board(); + let (vx, vy) = { + let v = &s.ds().unwrap().view; + (v.cx, v.cy) + }; + let fr = id(&s.execute("node.create", &json!({"type": "frame", "x": 300, "y": -200, "width": 3000, "height": 3000})).unwrap(), "id"); + s.execute("node.set", &json!({"id": fr, "props": {"rotation": 30}})).unwrap(); + // Left out: the block's middle (a four-line block) is on the view's centre, in the page. + let (f, _) = block(&mut s, json!({"parent": fr})); + let c = bx(&s, f).center(); + assert!((c.x - vx).abs() < 1e-6 && (c.y - vy).abs() < 1e-6, "{c:?} vs ({vx}, {vy})"); + // Given: `x`/`y` stay the frame's own coordinates. + let (g, _) = block(&mut s, json!({"parent": fr, "x": 10, "y": 20})); + let t = node(&s, g).transform.translation(); + assert_eq!((t.x, t.y), (10.0, 20.0)); +} + +#[test] +fn a_default_position_is_within_a_billion_too() { + let mut s = board(); + s.execute("view.set", &json!({"cx": 1e300})).unwrap(); + match s.execute("board.codeBlock", &json!({})) { + Err(EngineError::BadParams { .. }) => {} + Err(other) => panic!("not a named refusal: {other:?}"), + Ok(out) => panic!("placed at {out}"), + } +} + +#[test] +fn the_next_block_is_128_to_the_right_as_wide_and_in_the_same_language() { + let mut s = board(); + let (a, _) = block(&mut s, json!({"x": 0, "y": 0, "width": 976, "language": "rust", "text": "fn main() {}"})); + let connectors = |s: &Session| s.doc().unwrap().nodes().filter(|n| matches!(n.board, Some(BoardItem::Connector(_)))).count(); + let depth = s.undo_depth().0; + let out = s.execute("board.nextSticky", &json!({"id": a})).unwrap(); + let b = id(&out, "id"); + let r = bx(&s, b); + assert_eq!((r.x0, r.y0, r.width(), r.height()), (1104.0, 0.0, 976.0, 128.0)); + assert_eq!(node(&s, b).board, Some(BoardItem::CodeBlock { language: CodeLanguage::Rust })); + assert_eq!(td(&s, b).characters, ""); + assert_eq!(connectors(&s), 0); + assert_eq!(s.selection(), vec![b]); + assert_eq!(s.undo_depth().0, depth + 1); + undo(&mut s); + assert!(s.doc().unwrap().node(b).is_none()); + // While typing in the source, with no id, and asking for the next one to be typed in. + let t = text_of(s.doc().unwrap(), a).unwrap(); + s.execute("text.edit.begin", &json!({"id": t})).unwrap(); + let out = s.execute("board.nextSticky", &json!({"edit": true})).unwrap(); + let c = id(&out, "id"); + assert_eq!(bx(&s, c).x0, 1104.0); + assert!(s.ds().unwrap().text_edit.is_none(), "the edit has ended"); + assert!(s.ui_requests.iter().any(|q| q.kind == "board.editText" && q.data["id"] == json!(c))); + let out = s.execute("board.nextSticky", &json!({"id": a, "side": "below"})).unwrap(); + let r = bx(&s, id(&out, "id")); + assert_eq!((r.x0, r.y0), (0.0, 256.0)); + assert!(s.execute("board.nextSticky", &json!({"id": a, "side": "up"})).is_err()); +} + +#[test] +fn a_block_is_in_one_of_sixteen_languages() { + let mut s = board(); + let (f, _) = block(&mut s, json!({"x": 0, "y": 0})); + let lang = |s: &Session| node(s, f).board; + s.execute("board.setLanguage", &json!({"id": f, "language": "python"})).unwrap(); + assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: CodeLanguage::Python })); + for name in ["C++", "CPP"] { + s.execute("board.setLanguage", &json!({"id": f, "language": name})).unwrap(); + assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: CodeLanguage::Cpp })); + } + for l in CodeLanguage::ALL { + s.execute("board.setLanguage", &json!({"id": f, "language": l.id()})).unwrap(); + assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: l })); + } + s.execute("board.setLanguage", &json!({"id": f, "language": "go"})).unwrap(); + let e = s.execute("board.setLanguage", &json!({"id": f, "language": "klingon"})).unwrap_err().to_string(); + assert!(e.contains("typescript") && e.contains("plainText"), "{e}"); + let sticky = id(&s.execute("board.sticky", &json!({"x": 900, "y": 0})).unwrap(), "id"); + assert!(s.execute("board.setLanguage", &json!({"id": sticky, "language": "go"})).is_err()); + s.execute("select.none", &json!({})).unwrap(); + assert!(matches!(s.execute("board.setLanguage", &json!({"language": "go"})), Err(EngineError::Disabled(..)))); + // While typing in it, the text is the selection and the edit goes on. + let t = text_of(s.doc().unwrap(), f).unwrap(); + s.execute("text.edit.begin", &json!({"id": t})).unwrap(); + s.execute("board.setLanguage", &json!({"language": "ruby"})).unwrap(); + assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: CodeLanguage::Ruby })); + assert!(s.ds().unwrap().text_edit.is_some()); + s.execute("text.edit.key", &json!({"key": "Escape"})).unwrap(); + undo(&mut s); + assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: CodeLanguage::Go })); + // The creating command refuses what it cannot make. + assert!(s.execute("board.codeBlock", &json!({"language": "nope"})).is_err()); + assert!(s.execute("board.codeBlock", &json!({"width": 5})).is_err()); + assert!(s.execute("board.codeBlock", &json!({"text": "x".repeat(CODE_MAX_CHARS + 1)})).is_err()); +} + +fn insert(s: &mut Session, text: &str) { + s.execute("text.edit.insert", &json!({"text": text})).unwrap(); +} + +fn key(s: &mut Session, key: &str, shift: bool) { + s.execute("text.edit.key", &json!({"key": key, "shift": shift})).unwrap(); +} + +fn characters(s: &Session, t: NodeId) -> String { + match node(s, t).kind { + NodeKind::Text(td) => td.characters, + other => panic!("not text: {other:?}"), + } +} + +#[test] +fn typing_in_a_block_is_literal() { + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0})); + assert!(is_code_text(s.doc().unwrap(), t)); + s.execute("text.edit.begin", &json!({"id": t})).unwrap(); + insert(&mut s, "-"); + insert(&mut s, " "); + assert_eq!(characters(&s, t), "- "); + assert!(td(&s, f).paragraphs.iter().all(|p| p.list == ListStyle::None) && td(&s, f).list == ListStyle::None); + insert(&mut s, "\n1."); + insert(&mut s, " "); + assert_eq!(characters(&s, t), "- \n1. "); + assert!(td(&s, f).paragraphs.iter().all(|p| p.list == ListStyle::None)); + // Tab types two spaces. + s.execute("text.set", &json!({"id": t, "characters": ""})).unwrap(); + s.execute("text.edit.begin", &json!({"id": t, "caret": 0})).unwrap(); + key(&mut s, "Tab", false); + assert_eq!(characters(&s, t), " "); + key(&mut s, "Tab", true); + assert_eq!(characters(&s, t), " ", "Shift+Tab does nothing"); + // Enter keeps the line's indent, and nothing more after a brace. + insert(&mut s, "foo"); + key(&mut s, "Enter", false); + assert_eq!(characters(&s, t), " foo\n "); + s.execute("text.set", &json!({"id": t, "characters": "foo"})).unwrap(); + s.execute("text.edit.begin", &json!({"id": t, "caret": 3})).unwrap(); + key(&mut s, "Enter", false); + assert_eq!(characters(&s, t), "foo\n"); + s.execute("text.set", &json!({"id": t, "characters": "{"})).unwrap(); + s.execute("text.edit.begin", &json!({"id": t, "caret": 1})).unwrap(); + key(&mut s, "Enter", false); + assert_eq!(characters(&s, t), "{\n"); + // Nothing is made smart. + s.execute("text.set", &json!({"id": t, "characters": ""})).unwrap(); + s.execute("text.edit.begin", &json!({"id": t, "caret": 0})).unwrap(); + let raw = "\"a\" -- 'b' ... -> != fi"; + insert(&mut s, raw); + let got = characters(&s, t); + assert_eq!(got, raw); + assert!(!got.chars().any(|c| matches!(c, '\u{201C}' | '\u{2019}' | '\u{2014}' | '\u{2026}'))); + // In a sticky the same keys still make a list. + let note = id(&s.execute("board.sticky", &json!({"x": 900, "y": 0})).unwrap(), "text"); + s.execute("text.edit.begin", &json!({"id": note})).unwrap(); + insert(&mut s, "-"); + insert(&mut s, " "); + match node(&s, note).kind { + NodeKind::Text(d) => assert!(d.list == ListStyle::Bulleted || d.paragraphs.iter().any(|p| p.list == ListStyle::Bulleted)), + other => panic!("not text: {other:?}"), + } +} + +#[test] +fn lists_links_and_styled_ranges_do_not_stick() { + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": "one\ntwo"})); + let plain = |s: &Session| { + let d = td(s, f); + assert_eq!(d.list, ListStyle::None); + assert!(d.paragraphs.iter().all(|p| p.list == ListStyle::None)); + assert_eq!(d.style.link, None); + assert_eq!((d.style.decoration, d.style.case), (TextDecoration::None, TextCase::Original)); + assert!(d.runs.is_empty()); + assert_eq!(d.characters, "one\ntwo"); + assert_eq!(d.auto_resize, TextAutoResize::Height); + }; + for (cmd, p) in [ + ("text.bulletList", json!({"ids": [t]})), + ("text.link", json!({"url": "https://example.com", "ids": [t]})), + ("text.underline", json!({"ids": [t]})), + ("text.caseUpper", json!({"ids": [t]})), + ] { + // Done or refused by name, and the block is plain either way. + match s.execute(cmd, &p) { + Ok(_) | Err(EngineError::BadParams { .. } | EngineError::Disabled(..)) => {} + Err(other) => panic!("{cmd}: {other:?}"), + } + plain(&s); + } + s.execute("text.edit.begin", &json!({"id": t, "caret": 0})).unwrap(); + for _ in 0..3 { + key(&mut s, "ArrowRight", true); + } + s.execute("text.bold", &json!({})).unwrap(); + s.execute("text.edit.key", &json!({"key": "Escape"})).unwrap(); + plain(&s); + assert_eq!(td(&s, f).style.font_style, "Regular"); + s.execute("node.set", &json!({"id": t, "props": {"textAutoResize": "widthAndHeight"}})).unwrap(); + plain(&s); + // A sticky's note keeps its link (the guard). + let note = id(&s.execute("board.sticky", &json!({"x": 900, "y": 0, "text": "hi"})).unwrap(), "text"); + s.execute("text.link", &json!({"url": "https://example.com", "ids": [note]})).unwrap(); + match node(&s, note).kind { + NodeKind::Text(d) => assert_eq!(d.style.link.as_deref(), Some("https://example.com")), + other => panic!("not text: {other:?}"), + } +} + +#[test] +fn saved_files_live_sessions_and_a_second_pass() { + let mut s = board(); + let (f, _) = block(&mut s, json!({"x": 100, "y": 200, "width": 400, "language": "rust", "text": "a\nb"})); + let doc = s.doc().unwrap(); + let (back, _) = figcraft_format::from_json(&figcraft_format::to_json(doc).unwrap().to_string()).unwrap(); + let n = back.node(f).unwrap(); + assert_eq!(n.board, Some(BoardItem::CodeBlock { language: CodeLanguage::Rust })); + assert_eq!((n.width, n.height), (400.0, 128.0)); + + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0})); + let mut room = Room::new(s.doc().unwrap().clone(), 2, 7); + room.s(0).execute("text.set", &json!({"id": t, "characters": ten(6)})).unwrap(); + room.s(1).execute("board.setLanguage", &json!({"id": f, "language": "go"})).unwrap(); + room.settle(); + room.check(); + let server = room.server.document(); + let n = server.node(f).unwrap(); + assert_eq!(n.height, 176.0); + assert_eq!(n.board, Some(BoardItem::CodeBlock { language: CodeLanguage::Go })); + + // A second pass over a settled document changes nothing. + let doc = s.doc().unwrap().clone(); + let mut again = doc.clone(); + again.mark_dirty(doc.ids().collect::>()); + crate::normalize(&mut again, &doc); + assert_eq!(again, doc); + + // Not on design files. + let mut d = Session::new(); + assert_eq!(d.doc().unwrap().kind, FileKind::Design); + assert!(matches!(d.execute("board.codeBlock", &json!({})), Err(EngineError::Disabled(..)))); + assert!(matches!(d.execute("board.setLanguage", &json!({"language": "go"})), Err(EngineError::Disabled(..)))); +} + +#[test] +fn code_blocks_survive_junk_commands() { + let junk = [ + json!({}), + json!(null), + json!({"language": 7, "id": "x", "ids": [1], "side": 3, "text": [1]}), + json!({"language": "nope", "id": 99_999, "side": "up", "width": 1e308, "x": "NaN"}), + ]; + let ids: Vec<&str> = crate::cmd::all_commands() + .iter() + .map(|c| c.id) + .filter(|i| { + i.starts_with("text.") && *i != "text.rescanFonts" || i.starts_with("layout.") || matches!(*i, "board.nextSticky" | "board.setLanguage") + }) + .collect(); + assert!(ids.len() > 20, "{ids:?}"); + for editing in [false, true] { + for cmd in &ids { + for j in &junk { + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": "a\nb"})); + if editing { + s.execute("text.edit.begin", &json!({"id": t})).unwrap(); + } else { + s.set_selection(vec![f]); + } + if let Err(EngineError::Internal { cmd, msg }) = s.execute(cmd, j) { + panic!("{cmd} panicked on {j} (editing {editing}): {msg}"); + } + } + } + } +} + +#[test] +fn a_structured_text_is_refused_and_no_block_is_made() { + for text in [json!({"a": 1}), json!([1]), json!(7), json!(true)] { + let mut s = board(); + let before = s.doc().unwrap().ids().count(); + let err = s.execute("board.codeBlock", &json!({"x": 0, "y": 0, "text": text})); + assert!(matches!(err, Err(EngineError::BadParams { .. })), "{text}: {err:?}"); + assert_eq!(s.doc().unwrap().ids().count(), before, "{text}"); + } +} + +#[test] +fn the_pass_restores_padding_and_the_minimums() { + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": ten(6)})); + assert_eq!(bx(&s, f).height(), 176.0); + s.execute("node.set", &json!({"id": f, "props": {"padding": 0}})).unwrap(); + s.execute("text.set", &json!({"id": t, "characters": ten(6)})).unwrap(); + assert_eq!(node(&s, f).layout.unwrap().padding, [16.0, 16.0, 16.0, 64.0]); + assert_eq!(bx(&s, f).height(), 176.0); + + let (f, t) = block(&mut s, json!({"x": 0, "y": 500})); + s.execute("node.set", &json!({"id": f, "props": {"minHeight": null}})).unwrap(); + s.execute("text.set", &json!({"id": t, "characters": "a"})).unwrap(); + assert_eq!(node(&s, f).child_layout.min_h, Some(128.0)); + assert_eq!(bx(&s, f).height(), 128.0); +} diff --git a/crates/engine/src/board_tests.rs b/crates/engine/src/board_tests.rs index dfcb28d32..83b353f96 100644 --- a/crates/engine/src/board_tests.rs +++ b/crates/engine/src/board_tests.rs @@ -465,6 +465,7 @@ fn board_commands_survive_junk() { json!({"end": "from", "target": {"x": 1e308, "y": -1e308}, "side": "inside", "style": "curved"}), json!({"id": 99_999, "end": 7, "target": [1], "style": "wavy"}), json!({"id": 99_999, "relation": 7, "children": "x", "text": [1], "x": "NaN", "y": 1e308}), + json!({"id": 99_999, "language": 7, "text": [1], "width": "wide", "x": "NaN", "y": 1e308, "side": 3}), ]; let ids: Vec<&str> = crate::cmd::all_commands() .iter() @@ -482,6 +483,7 @@ fn board_commands_survive_junk() { let a = s.execute("board.sticky", &json!({"x": 0, "y": 0})).unwrap()["id"].clone(); let b = s.execute("board.shape", &json!({"x": 300, "y": 0})).unwrap()["id"].clone(); let _ = s.execute("board.connector", &json!({"from": a, "to": b, "label": "x"})); + let _ = s.execute("board.codeBlock", &json!({"x": 0, "y": 300, "text": "a\nb"})); if let Err(EngineError::Internal { cmd, msg }) = s.execute(cmd, j) { panic!("{cmd} panicked on {j}: {msg}"); } @@ -497,6 +499,7 @@ fn board_commands_survive_junk() { let a = s.execute("board.sticky", &json!({"x": 0, "y": 0})).unwrap()["id"].clone(); let b = s.execute("board.stamp", &json!({"x": 300, "y": 0})).unwrap()["id"].clone(); let _ = s.execute("board.connector", &json!({"from": a, "to": b})); + let _ = s.execute("board.codeBlock", &json!({"x": 0, "y": 300, "text": "a\nb"})); if let Err(EngineError::Internal { cmd, msg }) = s.execute(spec.id, j) { panic!("{cmd} panicked on {j}: {msg}"); } diff --git a/crates/engine/src/boards/board.rs b/crates/engine/src/boards/board.rs index ddee2d823..a320ee6f5 100644 --- a/crates/engine/src/boards/board.rs +++ b/crates/engine/src/boards/board.rs @@ -21,6 +21,7 @@ use crate::params::{boolean, color_of, get, id, id_of, num, num_or, opt_id, req_ use crate::tools::{Gesture, PointerEvent, ToolId}; use crate::{EngineError, Result, Session, bad, spec, textedit}; +mod code; mod connectors; mod derived; mod edit; @@ -29,6 +30,7 @@ mod mindmap; mod reshape; mod tools; +pub use code::is_code_text; pub(crate) use connectors::end_handle_at; pub use connectors::{END_HANDLE_PX, selected_connector_ends}; use connectors::{connector_cmd, reattach}; @@ -144,7 +146,7 @@ pub fn specs() -> Vec { spec!( "board.nextSticky", "Next sticky note", - "{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?} a sticky of the same colour beside a sticky; after a shape, the next shape joined to it by a connector, as board.addConnected", + "{id? (a sticky, shape or code block; default the selected or edited one), side?: right|below|left|above (default right), edit? (start typing in it; default false)} → {id, text, connector?} a sticky of the same colour beside a sticky; after a shape, the next shape joined to it by a connector, as board.addConnected; after a code block, the next code block beside it (128 away), as wide and in the same language, not joined", true, next_sticky ), @@ -197,6 +199,20 @@ pub fn specs() -> Vec { true, mindmap::mind_map_add ), + spec!( + "board.codeBlock", + "Code block", + "{x?, y? (its top-left in the parent; default a four-line block centred in the view), language? (bash|cpp|css|go|graphql|html|javascript|json|kotlin|plainText|python|ruby|rust|sql|swift|typescript; default typescript), text?, width? (210 to 100000; default 576), parent?, edit? (start typing in it; default false)} → {id, text, language} a dark panel holding monospace text: as wide as it is made, as tall as its lines (four at least)", + true, + code::code_block_cmd + ), + spec!( + "board.setLanguage", + "Code language", + "{id? | ids? (code blocks; default the selected ones, or the one being typed in), language} → {ids}", + true, + code::set_language + ), spec!("board.label", "Connector label", "{id (a connector; default the selection), text (empty removes it)} → {id, label}", true, label_cmd), spec!( "board.stamp", diff --git a/crates/engine/src/boards/board/code.rs b/crates/engine/src/boards/board/code.rs new file mode 100644 index 000000000..226f51bd4 --- /dev/null +++ b/crates/engine/src/boards/board/code.rs @@ -0,0 +1,260 @@ +//! Code blocks (#2237): a frame hugging one monospace text ([`BoardItem::CodeBlock`]), as wide as +//! it was made and as tall as its lines. The commands only make the block; [`settle_code`] keeps +//! it that way in the normalize pass (the height is the lines', the text is plain code), so every +//! entry point (a drag, `node.set`, a styled paste, a live session's edit) ends the same. + +use std::collections::BTreeSet; + +use figcraft_color::Paint; +use figcraft_doc::{ + AutoLayout, BoardItem, CODE_FONT, CODE_FONT_SIZE, CODE_GAP, CODE_MAX_CHARS, CODE_MAX_W, CODE_MIN_H, CODE_MIN_W, CODE_PAD, CODE_PANEL, + CODE_RADIUS, CODE_TEXT, CODE_WIDTH, CodeLanguage, Document, LayoutMode, LineHeight, ListStyle, NodeId, NodeKind, ParaList, Sizing, TextAlignH, + TextAutoResize, TextCase, TextData, TextDecoration, +}; +use serde_json::{Value, json}; + +use super::items::{add, add_text, owner_of_text, soft_shadow, text_of}; +use super::{Result, Session, bad, boolean, get, num, parent_of, req_string, req_targets, require, string, textedit}; + +/// How far from the page's middle a block may be put. +const CODE_MAX_COORD: f64 = 1.0e9; + +/// Whether `text` is the text of a code block: what the text editor asks before it converts what +/// is typed (a list from `- `, and any smart punctuation or link to come). +pub fn is_code_text(doc: &Document, text: NodeId) -> bool { + owner_of_text(doc, text).and_then(|o| doc.node(o)).is_some_and(|n| matches!(n.board, Some(BoardItem::CodeBlock { .. }))) +} + +/// The auto layout every code block has: its text stacked inside the padding. +fn block_layout() -> AutoLayout { + AutoLayout { mode: LayoutMode::Vertical, gap: 0.0, padding: CODE_PAD, ..AutoLayout::default() } +} + +/// A code block's frame and its text: `width` wide at `at` in `parent`, holding `text`. +fn make_code_block(doc: &mut Document, parent: NodeId, at: (f64, f64), width: f64, language: CodeLanguage, text: &str) -> Result<(NodeId, NodeId)> { + let frame = add(doc, parent, NodeKind::Frame, "Code block", at, (width, CODE_MIN_H), |n| { + n.fills = vec![Paint::solid(CODE_PANEL)]; + n.corners.radii = [CODE_RADIUS; 4]; + n.effects = vec![soft_shadow()]; + n.clip = false; + n.layout = Some(block_layout()); + n.child_layout.sizing_v = Sizing::Hug; + n.child_layout.min_h = Some(CODE_MIN_H); + n.child_layout.min_w = Some(CODE_MIN_W); + n.board = Some(BoardItem::CodeBlock { language }); + })?; + let inner = width - CODE_PAD[1] - CODE_PAD[3]; + let label = add_text(doc, frame, text, CODE_FONT_SIZE, CODE_TEXT, TextAlignH::Left, inner)?; + if let Some(NodeKind::Text(td)) = doc.node_mut(label).map(|n| &mut n.kind) { + td.style.font_family = CODE_FONT.into(); + td.style.line_height = LineHeight::Percent(150.0); + td.features.insert("liga".into(), false); + td.features.insert("calt".into(), false); + } + Ok((frame, label)) +} + +/// A language from its id or name, or an error listing the ids. +fn language_of(cmd: &str, v: &str) -> Result { + CodeLanguage::from_id(v).ok_or_else(|| { + let known: Vec<&str> = CodeLanguage::ALL.iter().map(|l| l.id()).collect(); + bad(cmd, format!("unknown language `{v}` ({})", known.join("|"))) + }) +} + +/// A coordinate from the params: given, it is a finite number within a billion of the origin. +fn coord(cmd: &str, p: &Value, key: &str, default: f64) -> Result { + let v = if get(p, key).is_none_or(Value::is_null) { Some(default) } else { num(p, key) }; + v.filter(|v| v.is_finite() && v.abs() <= CODE_MAX_COORD).ok_or_else(|| bad(cmd, format!("`{key}` is a position within a billion of the origin"))) +} + +pub(super) fn code_block_cmd(s: &mut Session, p: &Value) -> Result { + let cmd = "board.codeBlock"; + require(s, cmd)?; + let parent = parent_of(cmd, s, p)?; + let width = if get(p, "width").is_none_or(Value::is_null) { + CODE_WIDTH + } else { + num(p, "width") + .filter(|w| w.is_finite() && (CODE_MIN_W..=CODE_MAX_W).contains(w)) + .ok_or_else(|| bad(cmd, format!("`width` is a size from {CODE_MIN_W} to {CODE_MAX_W}")))? + }; + // The view's centre is on the page, and `x`/`y` are in the parent: a block in a section or + // frame takes the centre in that parent's coordinates (a parent that can't be inverted gives a + // non-finite centre, which `coord` refuses). + let (vx, vy) = { + let ds = s.ds()?; + let c = ds.doc.world_transform(parent).inverse() * figcraft_geom::Point::new(ds.view.cx, ds.view.cy); + (c.x, c.y) + }; + let x = coord(cmd, p, "x", vx - width / 2.0)?; + let y = coord(cmd, p, "y", vy - CODE_MIN_H / 2.0)?; + let language = match string(p, "language") { + Some(v) => language_of(cmd, &v)?, + None if get(p, "language").is_none_or(Value::is_null) => CodeLanguage::default(), + None => return Err(bad(cmd, "`language` is a language id")), + }; + let text = match get(p, "text") { + None | Some(Value::Null) => String::new(), + Some(Value::String(t)) => t.clone(), + Some(_) => return Err(bad(cmd, "`text` is a string")), + }; + if text.chars().count() > CODE_MAX_CHARS { + return Err(bad(cmd, format!("`text` is at most {CODE_MAX_CHARS} characters"))); + } + let (frame, label) = make_code_block(s.doc_mut()?, parent, (x, y), width, language, &text)?; + s.set_selection(vec![frame]); + if boolean(p, "edit") == Some(true) { + s.request_ui("board.editText", json!({"id": frame})); + } + Ok(json!({"id": frame, "text": label, "language": language.id()})) +} + +pub(super) fn set_language(s: &mut Session, p: &Value) -> Result { + let cmd = "board.setLanguage"; + require(s, cmd)?; + let language = language_of(cmd, &req_string(cmd, p, "language")?)?; + let targets = req_targets(cmd, s, p)?; + let doc = s.doc()?; + let blocks: BTreeSet = targets + .into_iter() + .map(|i| owner_of_text(doc, i).unwrap_or(i)) + .filter(|i| doc.node(*i).is_some_and(|n| matches!(n.board, Some(BoardItem::CodeBlock { .. })))) + .collect(); + if blocks.is_empty() { + return Err(bad(cmd, "select a code block")); + } + let doc = s.doc_mut()?; + for &b in &blocks { + if doc.node(b).is_some_and(|n| n.board != Some(BoardItem::CodeBlock { language })) { + doc.get_mut(b)?.board = Some(BoardItem::CodeBlock { language }); + } + } + Ok(json!({"ids": blocks.into_iter().collect::>()})) +} + +/// `board.nextSticky` on code block `from`: the next one beside it, as wide and in the same +/// language, with no connector. +pub(super) fn next_block(s: &mut Session, from: NodeId, language: CodeLanguage, p: &Value) -> Result { + let cmd = "board.nextSticky"; + let editing = s.ds()?.text_edit.is_some(); + let doc = s.doc()?; + let n = doc.get(from)?; + let parent = n.parent.ok_or_else(|| bad(cmd, "that code block has no parent"))?; + let at = n.transform.translation(); + let (w, h) = (n.width, n.height); + let (x, y) = match string(p, "side").as_deref().unwrap_or("right") { + "right" => (at.x + w + CODE_GAP, at.y), + "left" => (at.x - CODE_GAP - w, at.y), + "below" => (at.x, at.y + h + CODE_GAP), + "above" => (at.x, at.y - CODE_GAP - CODE_MIN_H), + other => return Err(bad(cmd, format!("`side` is right, below, left or above, not `{other}`"))), + }; + if !(x.is_finite() && y.is_finite() && w.is_finite()) { + return Err(bad(cmd, "the next block can't be placed there")); + } + let width = w.clamp(CODE_MIN_W, CODE_MAX_W); + if editing { + textedit::end(s)?; + } + let (frame, label) = make_code_block(s.doc_mut()?, parent, (x, y), width, language, "")?; + s.set_selection(vec![frame]); + if boolean(p, "edit") == Some(true) { + s.request_ui("board.editText", json!({"id": frame})); + } + Ok(json!({"id": frame, "text": label, "language": language.id()})) +} + +/// Whether `td` is already plain code: no list, indent, spacing, link, decoration, case change or +/// hand-made run, and a height that follows its lines. +fn is_plain(td: &TextData) -> bool { + td.auto_resize == TextAutoResize::Height + && td.list == ListStyle::None + && td.paragraphs == plain_paragraphs(&td.paragraphs) + && td.paragraph_indent == 0.0 + && td.paragraph_spacing == 0.0 + && td.list_spacing == 0.0 + && td.style.link.is_none() + && td.style.decoration == TextDecoration::None + && td.style.decoration_look.is_none() + && td.style.case == TextCase::Original + && td.runs.is_empty() +} + +/// `paragraphs` with no list, level or counting offset (the direction stays); empty when that +/// leaves every paragraph at its default. +fn plain_paragraphs(paragraphs: &[ParaList]) -> Vec { + let v: Vec = paragraphs.iter().map(|p| ParaList { direction: p.direction, ..ParaList::default() }).collect(); + if v.iter().all(|p| *p == ParaList::default()) { Vec::new() } else { v } +} + +fn make_plain(td: &mut TextData) { + td.auto_resize = TextAutoResize::Height; + td.list = ListStyle::None; + td.paragraphs = plain_paragraphs(&td.paragraphs); + td.paragraph_indent = 0.0; + td.paragraph_spacing = 0.0; + td.list_spacing = 0.0; + td.style.link = None; + td.style.decoration = TextDecoration::None; + td.style.decoration_look = None; + td.style.case = TextCase::Original; + td.runs.clear(); +} + +/// In the normalize pass, before text is measured and layout runs: every code block an edit +/// touched (or whose text it touched) is as tall as its lines again and holds plain code. Nothing +/// is written for a block already in that form, so a second pass changes nothing. +pub(crate) fn settle_code(doc: &mut Document, touched: &BTreeSet) { + let is_block = |doc: &Document, id: NodeId| doc.node(id).is_some_and(|n| matches!(n.board, Some(BoardItem::CodeBlock { .. }))); + let mut blocks = BTreeSet::new(); + for &id in touched { + if is_block(doc, id) { + blocks.insert(id); + } else if let Some(p) = doc.node(id).and_then(|n| n.parent).filter(|p| is_block(doc, *p)) { + blocks.insert(p); + } + } + for b in blocks { + // The frame's form is complete first: its layout and minimums (or it cannot hug) and a width that + // is not Hug (or its text cannot fill), else normalize puts them back every pass. + if let Some(n) = doc.node_mut(b) { + if n.layout.as_ref() != Some(&block_layout()) { + n.layout = Some(block_layout()); + } + if n.child_layout.min_h != Some(CODE_MIN_H) { + n.child_layout.min_h = Some(CODE_MIN_H); + } + if n.child_layout.min_w != Some(CODE_MIN_W) { + n.child_layout.min_w = Some(CODE_MIN_W); + } + if n.child_layout.sizing_h == Sizing::Hug { + n.child_layout.sizing_h = Sizing::Fixed; + } + } + // A fixed height is not kept: the layout pass sizes the block to its lines again. + if doc.node(b).is_some_and(|n| n.child_layout.sizing_v != Sizing::Hug) + && let Some(n) = doc.node_mut(b) + { + n.child_layout.sizing_v = Sizing::Hug; + } + let Some(t) = text_of(doc, b) else { continue }; + let Some(node) = doc.node(t) else { continue }; + let off = match &node.kind { + NodeKind::Text(td) => !is_plain(td), + _ => continue, + }; + let fill_off = node.child_layout.sizing_h != Sizing::Fill; + if !(off || fill_off) { + continue; + } + if let Some(n) = doc.node_mut(t) { + if fill_off { + n.child_layout.sizing_h = Sizing::Fill; + } + if off && let NodeKind::Text(td) = &mut n.kind { + make_plain(td); + } + } + } +} diff --git a/crates/engine/src/boards/board/derived.rs b/crates/engine/src/boards/board/derived.rs index a6461fb85..e62d41973 100644 --- a/crates/engine/src/boards/board/derived.rs +++ b/crates/engine/src/boards/board/derived.rs @@ -15,6 +15,7 @@ pub(crate) fn settle_text(doc: &mut Document, before: &Document, touched: &BTree return; } crate::board_table::settle_resize(doc, before, touched); + super::code::settle_code(doc, touched); for &id in touched { let Some(n) = doc.node(id) else { continue }; if let Some(BoardItem::Shape { shape }) = n.board diff --git a/crates/engine/src/boards/board/edit.rs b/crates/engine/src/boards/board/edit.rs index 61a3c5659..6df2fa397 100644 --- a/crates/engine/src/boards/board/edit.rs +++ b/crates/engine/src/boards/board/edit.rs @@ -84,7 +84,7 @@ pub(super) fn set_color(s: &mut Session, p: &Value) -> Result { n.strokes = vec![Paint::solid(line_shade(color))]; } BoardItem::Connector(_) | BoardItem::Ink => doc.get_mut(id)?.strokes = vec![Paint::solid(line_shade(color))], - BoardItem::Label { .. } | BoardItem::Stamp { .. } | BoardItem::Table | BoardItem::MindNode => continue, + BoardItem::Label { .. } | BoardItem::Stamp { .. } | BoardItem::Table | BoardItem::MindNode | BoardItem::CodeBlock { .. } => continue, } changed.push(id); } diff --git a/crates/engine/src/boards/board/items.rs b/crates/engine/src/boards/board/items.rs index 431a27cf9..481f0ebed 100644 --- a/crates/engine/src/boards/board/items.rs +++ b/crates/engine/src/boards/board/items.rs @@ -26,7 +26,7 @@ pub(super) fn add( } /// A soft shadow under stickies and stamps. -fn soft_shadow() -> Effect { +pub(super) fn soft_shadow() -> Effect { Effect { kind: EffectKind::DropShadow(Shadow { color: Color::new(0.0, 0.0, 0.0, 0.16), offset: (0.0, 2.0), radius: 6.0, ..Shadow::default() }), visible: true, @@ -142,14 +142,17 @@ pub(super) fn next_sticky(s: &mut Session, p: &Value) -> Result { let from = id(p, "id") .or_else(|| editing.and_then(|t| owner_of_text(doc, t))) .or_else(|| s.selection().first().copied().map(|i| owner_of_text(doc, i).unwrap_or(i))) - .ok_or_else(|| EngineError::Disabled(cmd.into(), "select a sticky or a shape first".into()))?; + .ok_or_else(|| EngineError::Disabled(cmd.into(), "select a sticky, a shape or a code block first".into()))?; let n = doc.get(from)?; + if let Some(BoardItem::CodeBlock { language }) = n.board { + return super::code::next_block(s, from, language, p); + } if matches!(n.board, Some(BoardItem::Shape { .. })) { // A shape gets the next one joined to it, as the "+" beside it makes (#1597). return add_connected(s, p); } if !matches!(n.board, Some(BoardItem::Sticky { .. })) { - return Err(bad(cmd, "that isn't a sticky or a shape")); + return Err(bad(cmd, "that isn't a sticky, a shape or a code block")); } let color = n.fills.iter().find_map(Paint::solid_color).unwrap_or(s.tool.board.sticky); let parent = n.parent.ok_or_else(|| bad(cmd, "that sticky has no parent"))?; diff --git a/crates/engine/src/canvas/textedit.rs b/crates/engine/src/canvas/textedit.rs index 51a1640f7..6c8c15071 100644 --- a/crates/engine/src/canvas/textedit.rs +++ b/crates/engine/src/canvas/textedit.rs @@ -87,6 +87,12 @@ fn text_of(s: &Session, id: NodeId) -> Result { } } +/// Whether the text being edited is a code block's. +fn in_code(s: &Session) -> bool { + let Some(te) = s.ds().ok().and_then(|d| d.text_edit.as_ref()) else { return false }; + s.doc().is_ok_and(|d| crate::board::is_code_text(d, te.id)) +} + /// Start editing text node `id` with the caret at `caret` (None = select all). pub fn begin(s: &mut Session, id: NodeId, caret: Option, created: bool) -> Result<()> { let t = text_of(s, id)?; @@ -282,13 +288,15 @@ fn insert_model(s: &mut Session, text: &str, ime_commit: bool) -> Result. " or "1) " typed at the start of a plain paragraph starts a list // (the creation characters of Create bulleted and numbered lists). As measured in Figma // (2026-11-11), a typed "5. " starts the numbered list at 5 (there is no start-number // field). "0. " and a bracket after a number other than 1 are not measured: plain text. - if text == " " && a == b && t.para_list(t.para_of(a)).list == ListStyle::None { + if !code && text == " " && a == b && t.para_list(t.para_of(a)).list == ListStyle::None { let chars: Vec = t.characters.chars().collect(); let start = line_start(&chars, a); let typed: String = chars.get(start..a).unwrap_or(&[]).iter().collect(); @@ -463,6 +471,16 @@ pub fn key(s: &mut Session, key: &str, shift: bool, word: bool, line: bool) -> R if matches!(key, "Tab" | "Backspace" | "Delete" | "Enter") && !word && !line && list_key(s, key, shift)? { return Ok(()); } + // In a code block Tab types two spaces and Enter keeps the line's indent. + if matches!(key, "Tab" | "Enter") && !word && !line && in_code(s) { + if key == "Tab" { + return if shift { Ok(()) } else { insert(s, figcraft_doc::CODE_TAB) }; + } + let (a, _) = range(&te); + let start = line_start(&chars, a); + let indent: String = chars.get(start..a).unwrap_or(&[]).iter().take(256).take_while(|c| matches!(c, ' ' | '\t')).collect(); + return insert(s, &format!("\n{indent}")); + } match key { "Escape" => return end(s), "Enter" => return insert(s, "\n"), diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index c865924c5..177155a8a 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -642,7 +642,7 @@ pub fn specs() -> Vec { spec!( "text.edit.key", "Text key", - "{key: Backspace|Delete|Left|Right|Up|Down|Home|End|Enter|Tab|Escape|SelectAll, shift?, alt?, cmd?} in a list, Tab nests the item and Shift+Tab, Enter on an empty item or Backspace at its start move it out", + "{key: Backspace|Delete|Left|Right|Up|Down|Home|End|Enter|Tab|Escape|SelectAll, shift?, alt?, cmd?} in a list, Tab nests the item and Shift+Tab, Enter on an empty item or Backspace at its start move it out; in a code block, Tab types two spaces and Enter keeps the line's indent", true, |s, p| { let k = req_string("text.edit.key", p, "key")?; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6fe5633ad..a66290647 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -208,6 +208,8 @@ mod batch_undo_snapshot_tests; #[cfg(test)] mod binding_lists_tests; #[cfg(test)] +mod board_code_tests; +#[cfg(test)] mod board_connected_tests; #[cfg(test)] mod board_connector_tests; diff --git a/crates/ui-egui/src/canvas/board_bar.rs b/crates/ui-egui/src/canvas/board_bar.rs index fa3d5e4e5..95e6db394 100644 --- a/crates/ui-egui/src/canvas/board_bar.rs +++ b/crates/ui-egui/src/canvas/board_bar.rs @@ -153,7 +153,7 @@ fn has(app: &FigApp) -> Option { } Some(BoardItem::Label { .. } | BoardItem::MindNode) => h.text = true, Some(BoardItem::Table) => h.table = true, - Some(BoardItem::Stamp { .. }) | None => {} + Some(BoardItem::Stamp { .. } | BoardItem::CodeBlock { .. }) | None => {} } } h.only_lines = h.connector.is_some() && !others; diff --git a/docs/boards-parity.md b/docs/boards-parity.md index 567b9b61e..83a632057 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -1,6 +1,6 @@ # Boards parity -> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-12 · **Change:** minor (a `.jam` file's shapes with text come in as native board shapes for the 23 kinds FigCraft draws, the other 7 as frames (#1808); a sticky has a text-size menu in the contextual bar, Small 16, Medium 24, Large 40, Extra large 64 and Huge 96, with Small the default (an earlier reading of 18 did not reproduce); `board.setStyle {fontSize}` sizes stickies and the sticky tool remembers the last size for new ones; the note grows taller at Huge and shrinks back, as measured in FigJam's web app, 2026-11-12; resizing a board table by height changes its rows, not blank space below them: a bottom or top edge grows the last row, a corner shares the change over every row, and a table keeps at least 40 per cell, measured in FigJam's web app, 2026-11-09 (#2172); a `.jam` file's stickies come in as native board stickies, with their colour, text and author kept and the size as saved (#1808); a sticky's text stays 18 and the note grows taller instead of the text shrinking, as measured in FigJam's web app (#2157); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); 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) +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-12 · **Change:** minor (code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); a `.jam` file's shapes with text come in as native board shapes for the 23 kinds FigCraft draws, the other 7 as frames (#1808); a sticky has a text-size menu in the contextual bar, Small 16, Medium 24, Large 40, Extra large 64 and Huge 96, with Small the default (an earlier reading of 18 did not reproduce); `board.setStyle {fontSize}` sizes stickies and the sticky tool remembers the last size for new ones; the note grows taller at Huge and shrinks back, as measured in FigJam's web app, 2026-11-12; resizing a board table by height changes its rows, not blank space below them: a bottom or top edge grows the last row, a corner shares the change over every row, and a table keeps at least 40 per cell, measured in FigJam's web app, 2026-11-09 (#2172); a `.jam` file's stickies come in as native board stickies, with their colour, text and author kept and the size as saved (#1808); a sticky's text stays 18 and the note grows taller instead of the text shrinking, as measured in FigJam's web app (#2157); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); 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 @@ -58,7 +58,8 @@ all end with the same geometry. | Templates (retrospective, brainstorm, flow chart…) | partial | five built-in templates drawn up for FigCraft (retrospective, brainstorm, weekly planner, flow chart, kanban board), placed from the toolbar's templates picker (each with a picture of itself) or `board.template {name, x?, y?}` as ordinary sections, stickies, shapes, connectors and text in one undo step; `board.templates` lists them. No community templates, no saving your own | | Tables | partial | `board.table {rows, columns, cells?, x?, y?}` (at most 50 × 20): an auto layout frame of rows of cells with text, a tinted header row and lines between rows and columns; a cell's row grows with its text; resizing a table by its bottom edge or its height grows the last row and a corner drag shares the change equally over every row and column (a side drag changes no row), the table keeps hugging its rows and a cell keeps at least 40 each way (measured in FigJam's web app, 2026-11-09: its floor is about 52, FigCraft's is 40, and its right edge grows only the last column); a double-click types in the cell under the pointer; add or remove a row or column from the bar over the selection or `board.tableEdit {id, action, index?}`; cells copied from a spreadsheet (tab-separated text, quoted cells kept whole) paste as a table, up to 50 × 20 with a note when there was more; undoable and synced in live sessions. No per-column widths yet (a width change splits equally), no column resizing by dragging, no cell colours, no Tab between cells; comma-separated text pastes as text | | Mind maps | partial | from commands only so far (#2226): `board.mindMap {x?, y?, text?, children?}` places a first node (bold, no box) with three children on its right, joined by curved branches; `board.mindMapAdd {id?, relation?: child\|sibling}` adds a node. Nodes are text that grows wider as it is typed and taller with line breaks; a node's children stand in one column 88 units right of the widest node of its own column, 48 apart, centred on it, and the map lays itself out again in the normalize pass after every edit, undo and live-session change; moving the first node moves the map; a deleted node's children stay where they are without their branch. Branches are board connectors (`branch`: stroke 4, #757575, round caps), so their style, end points, weight and colour change like any connector's. No toolbar entry, shortcuts, "+" handles, dragging a node onto another, left side or `.jam` import yet | -| Washi tape, code blocks, image cropping on boards | missing | images can be placed as in design files | +| Code blocks | partial | from commands only so far (#2237): `board.codeBlock {x?, y?, language?, text?, width?}` places a dark panel holding monospace text (Liberation Mono 16 on a 24 line where it is embedded or installed), 576 wide; its height is its lines (32 + 24 a line, wrapped lines counted, never under four lines) and only its width can be changed (210 at least); `board.setLanguage {id?, language}` keeps one of 16 languages (TypeScript by default); `board.nextSticky` on a block makes the next one 128 to its right, as wide and in the same language. In a block Tab types two spaces, Enter keeps the line's indent, and lists, links and styled ranges don't apply. No toolbar entry, language menu, highlighting colours, line numbers or `.jam` import yet | +| Washi tape, image cropping on boards | missing | images can be placed as in design files | | 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 | @@ -68,6 +69,7 @@ all end with the same geometry. | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | M12, #2237 (step 1 of 4): code blocks in the document and engine. A code block is a board object of its own (`BoardItem::CodeBlock { language }`): a hugging frame holding one monospace text, 576 wide, 32 + 24 a visual line tall and never under four lines; only its width is kept from a resize. `board.codeBlock` places one, `board.setLanguage` picks one of 16 languages, and `board.nextSticky` makes the next block beside it. The normalize pass keeps a block's text plain code (`board::settle_code`) and the text editor types literally in it (two spaces for Tab, the line's indent after Enter, no list from `- `). The colours are FigCraft's own (the board's ink and tints); the sizes are from a FigJam measurement. Tests: `board_code_tests` in doc (four) and engine (thirteen). Numbers unchanged (no toolbar entry yet). | | 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Shapes with text, Connectors, Create the next shape already connected. | | 2026-11-12 | minor | M12: a sticky's text-size menu. Measured in FigJam's web app, 2026-11-12: the menu lists Small 16, Medium 24, Large 40, Extra large 64 and Huge 96 (typing 40 shows Large), a fresh sticky is Small = 16 (read twice from the size field; the 18 of 2026-11-09 did not reproduce), the note stays square to Extra large and grows taller at Huge with the same width and shrinks back at Large, choosing a size with two stickies selected sets both, and the sticky tool remembers the last size. `STICKY_TEXT_SIZE` is 16, `STICKY_SIZES` holds the table, `board.setStyle {fontSize}` sizes stickies and sets the tool's size, `board.sticky` takes `fontSize`, and the contextual bar shows a size menu when only stickies carry text (shapes keep S/M/L/XL, unmeasured). Stacks are still missing. Tests: `a_new_sticky_is_small_16`, `the_sticky_sizes_are_figjams`, `set_style_font_size_sizes_every_selected_sticky`, `the_sticky_tool_remembers_the_last_size`, `a_huge_sticky_grows_taller_and_shrinks_back`, `a_selected_sticky_has_a_size_menu_instead_of_the_size_cells` | | 2026-11-09 | minor | M12, #2172: a board table's height change goes into its rows. Measured in FigJam's web app, 2026-11-09 (a table has no lock-proportions control and never scales proportionally): a bottom-edge drag grows only the last row, a corner drag shares the change equally over every row and column, text keeps its size, and a table stops shrinking at about 52 per cell with a row never shorter than its wrapped text. FigCraft already split a width change equally (every cell fills); the bug was height: a bottom or corner resize turned the table from hugging to fixed height, so the rows stayed at 40 with blank space below them (or were clipped when shrunk) and typing no longer grew the table. `board_table::settle_resize`, called first in the normalize pass, finds a table left at a fixed height, puts the change into the rows' minimum height (the last row, or every row when both axes changed), raises a width that is too narrow to `columns x 40`, and returns the table to hugging, so every route (drag, `node.set`, `transform.resize`, MCP, live-session peers) gives the same result, in one undo step. FigCraft's floor is 40 (FigJam's is about 52) and there are no per-column widths yet: a side drag of the right edge still splits equally where FigJam grows only the last column. Numbers unchanged. Tests: `board_tables_tests` (the bottom, corner and side drags, the floor, typing after a resize and undo, live sessions, junk). | diff --git a/docs/gaps.md b/docs/gaps.md index bb3ede386..d13953a32 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where FigCraft falls short of Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (gap 10: library analytics count insertions and detachments of styles and variables; gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: 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; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; 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; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (gap 24: code blocks, first step (`board.codeBlock`, `board.setLanguage`, #2237); gap 10: library analytics count insertions and detachments of styles and variables; gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: 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; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; 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; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The @@ -606,7 +606,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe connector's ends drag onto another object or empty canvas (`board.reattach`); curved connectors; elbows that go around the objects they join. - **Missing:** timer music, board widgets, saving your own templates, table column resizing and - cell colours, the mind maps' toolbar entry, shortcuts, drag to re-parent and import, washi tape, code blocks, audio and huddles, quick-create handles, + cell colours, the mind maps' toolbar entry, shortcuts, drag to re-parent and import, washi tape, the code blocks' toolbar entry, language menu, highlighting and import, audio and huddles, quick-create handles, the stamp wheel, emotes and stickers, `.jam` files ([`boards-parity.md`](boards-parity.md)). - **User impact:** boards cover a brainstorm, a retrospective, a flow sketch and a timed, voted @@ -617,6 +617,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | Gap 24: code blocks, first step (`board.codeBlock`, `board.setLanguage`; a block is as tall as its lines and keeps its text plain code, #2237); the toolbar entry, language menu, highlighting, line numbers and `.jam` import are missing. | | 2026-11-18 | minor | Gap 10: library analytics count insertions and detachments of styles and variables; modes stay on the missing list. | | 2026-11-18 | minor | Gap 6: the plugin directory works in the browser build, so that item leaves the missing list; what's installed there lasts as long as the page. Team libraries on a server work there too. | | 2026-11-17 | minor | Gap 7: a pan past the canvas image shows a coarse image of the area around the view (desktop), not the bare page colour; `canvas.uncovered` in `ui.inspect`. Numbers unchanged. Tests: `surround_tests`, `background::tests::the_image_around_the_view_fills_what_the_render_leaves_and_the_page_colour_the_rest` | diff --git a/docs/mcp.md b/docs/mcp.md index 8940fa184..2d6580fd7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -499,7 +499,7 @@ Returns `{fitted: [{id, fontSize, lines, fits, orphan}]}`. Use case: a carousel A board is a file of its own kind for thinking together: `file.newBoard {name?}` opens one (its page is light; `inspect_document` says `kind: "board"`). Board objects are ordinary layers with a -`board` entry `get_node` shows (`{type: sticky|shape|connector|label|stamp|ink|mindNode, …}`; a connector may say +`board` entry `get_node` shows (`{type: sticky|shape|connector|label|stamp|ink|mindNode|codeBlock, …}`; a connector may say `branch: true`), so the usual commands move, resize, recolour, copy, delete and undo them. On a design file the board commands refuse; on a board `proto.*`, `dev.*`, `view.prototype` and `view.devMode` refuse. Each of these is @@ -513,6 +513,8 @@ one undo step and returns the ids it made: same colour beside the selected (or edited) one; with `edit: true` the app goes on typing in it (`Shift+Cmd/Ctrl+Enter` in the app does both). On a shape it does what `board.addConnected` does: the next shape, joined to it by a connector (`{id, text, connector}`). + On a code block it makes the next code block 128 units beside it (`side`, default right), as wide and + in the same language, not joined (`{id, text, language}`). - `board.addConnected {id?, side?: right|below|left|above, edit?}` → `{id, text, connector}`: the next sticky or shape of the same kind, size and colour on that side of the selected (or edited) one, 80 units away, joined to it by a connector the way the Connector tool makes one; one undo @@ -533,6 +535,17 @@ one undo step and returns the ids it made: of the map that the given (or selected, or edited) one belongs to: a child below its other children, or a sibling right after it (the first node has none); the map lays itself out again. One undo step. With `edit: true` the app goes on typing in it. +- `board.codeBlock {x?, y?, language?, text?, width?, parent?, edit?}` → `{id, text, language}`: a code + block (`codeBlock` with its `language`): a dark panel holding monospace text (Liberation Mono 16 on a + 24 line where it is embedded or installed). `language` is `bash cpp css go graphql html javascript json + kotlin plainText python ruby rust sql swift typescript` (default `typescript`); `width` is 210 to 100000 + (default 576); `x`/`y` are its top-left corner, by default the view's centre less half the width and less 64 (half the + smallest height, 128), so a block of more lines reaches further down. Its height is its lines: 32 + 24 a visual line, + never under four lines, so only its width can be changed (a set or dragged height is not kept). In its + text Tab types two spaces, Enter keeps the line's indent, and lists, links and styled ranges do not stick. + One undo step. +- `board.setLanguage {id?, ids?, language}` → `{ids}`: the language of the given (or selected, or edited) + code blocks, by id or name (`cpp` or `C++`). - `board.shape {shape, x, y, width?, height?, text?, color?, parent?}` → `{id, text}`: a shape with centred, wrapping text: `rectangle roundedRectangle ellipse diamond triangle triangleDown parallelogramRight parallelogramLeft trapezoid pentagon hexagon octagon star plus arrowLeft arrowRight chevron speechBubble database document predefinedProcess manualInput internalStorage`. - `board.connector {from, to, fromSide?, toSide?, fromAt?, toAt?, style?: straight|elbow|curved, startCap?, endCap?, label?}` diff --git a/docs/roadmap.md b/docs/roadmap.md index b797063a6..27d7af485 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # FigCraft roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (library analytics count insertions and detachments of styles and variables; the browser build uses team libraries and plugin directories on a server; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; 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); 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; 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); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); 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); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); 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; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); 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; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); library analytics count insertions and detachments of styles and variables; the browser build uses team libraries and plugin directories on a server; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; 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); 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; 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); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); 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); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); 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; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); 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; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) Forward-looking plan. Where FigCraft stands today: [`ROADMAP.md`](../ROADMAP.md) and [`target-app-parity.md`](target-app-parity.md); the full ranked list: [`gaps.md`](gaps.md). Hours @@ -76,6 +76,7 @@ blockers. | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | M12, #2237 (step 1 of 4): code blocks in the document and engine. `board.codeBlock` places a dark panel of monospace text as tall as its lines, `board.setLanguage` picks one of 16 languages, and `board.nextSticky` makes the next block beside it; the toolbar entry, language menu, highlighting, line numbers and `.jam` import are missing. Numbers unchanged. | | 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-10 | minor | Zoomed-out images: the canvas's copies of an image shown smaller than its pixels now also come at 256, 512, 1024 and 2048 px, the smallest that holds what the screen shows, and images of 4096 px or less get them too (they were drawn from the image itself at any size). On a page of 237 photos, about 4.6 GB decoded against the 512 MB cache, every zoomed-out render decoded them again: 3.4 s a frame at 1% before, 0.9 s the first time and 4 ms after; peak memory 3.9 → 2.3 GB. Exports, and images shown at their own size or larger, still draw from the image itself. | From a4099033f74cf9d6696ba9bae486793cf2c0c35e Mon Sep 17 00:00:00 2001 From: B-uchi Date: Wed, 18 Nov 2026 07:46:14 +0100 Subject: [PATCH 046/114] M8: inspect `fields` accepts dashCap, which node.get already writes node.get and document.inspect write `dashCap` on a layer with a dash cap, but it was missing from NODE_KEYS, so `fields: ["dashCap"]` was refused as an unknown key (and the MCP tools' `fields` schema left it out). A test now walks the keys a varied layer tree writes and checks each is one `fields` accepts. --- crates/engine/src/automation/inspect.rs | 1 + crates/engine/src/inspect_fields_tests.rs | 39 +++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/crates/engine/src/automation/inspect.rs b/crates/engine/src/automation/inspect.rs index a3c0b94e5..359c58bb4 100644 --- a/crates/engine/src/automation/inspect.rs +++ b/crates/engine/src/automation/inspect.rs @@ -27,6 +27,7 @@ pub const NODE_KEYS: &[&str] = &[ "constraints", "cornerRadius", "cornerSmoothing", + "dashCap", "dashes", "description", "devChanged", diff --git a/crates/engine/src/inspect_fields_tests.rs b/crates/engine/src/inspect_fields_tests.rs index 592ca8b94..c121092ef 100644 --- a/crates/engine/src/inspect_fields_tests.rs +++ b/crates/engine/src/inspect_fields_tests.rs @@ -561,3 +561,42 @@ fn modes_property_bindings_and_exposed_instances_are_read() { s.execute("component.exposeInstance", &json!({"id": nested.clone()})).unwrap(); assert_eq!(s.execute("node.get", &json!({"id": nested})).unwrap()["exposedInstance"], true); } + +/// Every key a layer's JSON can have is one `fields` accepts: a key missing from `NODE_KEYS` can be +/// read in full output but is refused when asked for by name (`dashCap` was). +#[test] +fn every_key_node_get_writes_can_be_asked_for() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let frame = s + .execute("node.create", &json!({"type": "frame", "width": 200, "height": 100, "props": {"layout": {"mode": "horizontal"}, "gap": 4}})) + .unwrap()["id"] + .clone(); + let line = s + .execute( + "node.create", + &json!({"type": "line", "parent": frame, "width": 80, "props": { + "strokes": ["#000000"], "strokeWeight": 2, "dashes": [4, 2], "dashCap": "round", "strokeJoin": "round", + "opacity": 0.5, "visible": false, "locked": true}}), + ) + .unwrap()["id"] + .clone(); + s.execute("node.create", &json!({"type": "text", "parent": frame, "text": "Hi", "props": {"textDecoration": "underline"}})).unwrap(); + s.execute("annotation.add", &json!({"id": line, "label": "Note"})).unwrap(); + let mut keys = std::collections::BTreeSet::new(); + fn walk(v: &Value, keys: &mut std::collections::BTreeSet) { + if let Some(o) = v.as_object() { + keys.extend(o.keys().cloned()); + for c in o.get("children").and_then(Value::as_array).into_iter().flatten() { + walk(c, keys); + } + } + } + walk(&node_json(s.doc().unwrap(), crate::params::id_of(&frame).unwrap(), 4), &mut keys); + assert!(keys.contains("dashCap"), "the test sets a dash cap: {keys:?}"); + for key in keys { + assert!(crate::inspect::NODE_KEYS.contains(&key.as_str()), "`{key}` is written but `fields` refuses it"); + let one = InspectOptions::parse(&json!({"fields": [key]})); + assert!(one.is_ok(), "{key}: {one:?}"); + } +} From 79a1ea4a4293edbdc08750de812fff7852904106 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 02:36:08 +0700 Subject: [PATCH 047/114] M8: keep the canvas input under the complexity limit with edge panning (#2104) The pan past the canvas edge moves into a helper of its own. --- crates/ui-egui/src/canvas/input.rs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 1360697d8..6ecdb948c 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -226,13 +226,7 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo send(app, PointerKind::Up, at, &mods); } } - // A drag held past the edge pans toward it, the layer or box going with the pointer. - if super::autopan::wanted(app, &ctx) - && let Some(at) = ctx.input(|i| i.pointer.latest_pos()) - && super::autopan::pan(app, &ctx, at) - { - send(app, PointerKind::Move, at, &mods); - } + pan_past_edge(app, &ctx, &mods); // Leaving the canvas: nothing is hovered there any more. if !app.canvas.dragging && std::mem::take(&mut app.canvas.hovering) { left(app); @@ -410,6 +404,16 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo } /// Pointer event `kind` at screen point `pos`, to the tools. +/// A drag held past the edge pans toward it, the layer or box going with the pointer. +fn pan_past_edge(app: &mut FigApp, ctx: &egui::Context, mods: &egui::Modifiers) { + if super::autopan::wanted(app, ctx) + && let Some(at) = ctx.input(|i| i.pointer.latest_pos()) + && super::autopan::pan(app, ctx, at) + { + send(app, PointerKind::Move, at, mods); + } +} + fn send(app: &mut FigApp, kind: PointerKind, pos: Pos2, m: &egui::Modifiers) { let ev = pointer_event(app, kind, pos, m); // A hover where nothing changed since the last one finds what that one found (the state is From 2d4309c9aa61facdea6c698e0010fee43a2e5558 Mon Sep 17 00:00:00 2001 From: B-uchi Date: Wed, 18 Nov 2026 08:20:59 +0100 Subject: [PATCH 048/114] M8: design context for AI agents inspect.designContext and the MCP tool design_context read the selection (or ids, or a scope) in one call. Each layer keeps apart the values the designer set (explicit), those layout or the file worked out (derived) and those with no direct CSS equivalent (unsupported, with the reason). The variables (every mode's stored and resolved value), styles, components, fonts and assets the tree uses are joined once, and `missing` says what the design doesn't specify. A connected instance gives its code snippet instead of its layers. Large trees are capped and say so, and the MCP tool asks for fewer layers until the result fits the client. --- ROADMAP.md | 1 + crates/engine/src/cmd.rs | 1 + crates/engine/src/design_context_tests.rs | 288 ++++++++++++++ crates/engine/src/dev.rs | 1 + crates/engine/src/dev/design_context.rs | 434 ++++++++++++++++++++++ crates/engine/src/lib.rs | 3 + crates/mcp/src/tools.rs | 38 ++ crates/mcp/tests/it/inspect_fields.rs | 18 + docs/mcp.md | 36 ++ 9 files changed, 820 insertions(+) create mode 100644 crates/engine/src/design_context_tests.rs create mode 100644 crates/engine/src/dev/design_context.rs diff --git a/ROADMAP.md b/ROADMAP.md index 107a11f96..95e1a67ef 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -366,6 +366,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | M8: design context for AI agents. `inspect.designContext` and the MCP tool `design_context` read the selection (or `ids`, or a `scope`) in one call: a tree where each layer keeps apart `explicit` values, `derived` ones layout worked out and `unsupported` ones with no direct CSS equivalent, joined with the variables (every mode's stored and resolved value), styles, components, fonts and assets it uses, and what the design leaves `missing`. A connected instance gives its code instead of its layers, and a result that wouldn't fit the client asks for fewer layers. Numbers unchanged | | 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. | diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 0e90dc198..b90204504 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -100,6 +100,7 @@ fn registry() -> &'static Registry { list.extend(crate::shapebuilder::specs()); list.extend(crate::codegen::specs()); list.extend(crate::devinspect::specs()); + list.extend(crate::design_context::specs()); list.extend(crate::component_codegen::specs()); list.extend(crate::playground::specs()); list.extend(crate::code_connect::specs()); diff --git a/crates/engine/src/design_context_tests.rs b/crates/engine/src/design_context_tests.rs new file mode 100644 index 000000000..3aa0ab09b --- /dev/null +++ b/crates/engine/src/design_context_tests.rs @@ -0,0 +1,288 @@ +//! `inspect.designContext` against documents built with real commands. + +use serde_json::{Value, json}; + +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s +} + +fn id(v: &Value) -> u64 { + v["id"].as_u64().unwrap() +} + +fn node(s: &mut Session, params: Value) -> u64 { + id(&s.execute("node.create", ¶ms).unwrap()) +} + +fn context(s: &mut Session, params: Value) -> Value { + s.execute("inspect.designContext", ¶ms).unwrap() +} + +/// A hugging auto layout card holding a fixed title and a filling line. +fn card(s: &mut Session) -> (u64, u64, u64) { + let f = node(s, json!({"type": "frame", "name": "Card", "x": 40, "y": 30, "width": 300, "height": 200, "props": {"fill": "#FFFFFF"}})); + s.execute("node.set", &json!({"ids": [f], "props": {"layout": {"mode": "vertical"}, "gap": 12, "padding": [16, 16, 16, 16], "sizingV": "hug"}})) + .unwrap(); + let title = node(s, json!({"type": "text", "parent": f, "name": "Title", "text": "Pro plan", "props": {"fontSize": 24}})); + let line = node(s, json!({"type": "rectangle", "parent": f, "name": "Rule", "width": 100, "height": 2, "props": {"sizingH": "fill"}})); + (f, title, line) +} + +fn only(v: &Value) -> &Value { + let nodes = v["nodes"].as_array().unwrap(); + assert_eq!(nodes.len(), 1, "{v}"); + &nodes[0] +} + +#[test] +fn the_selection_is_what_is_read() { + let mut s = session(); + let (f, title, _) = card(&mut s); + let other = node(&mut s, json!({"type": "rectangle", "name": "Elsewhere", "width": 10, "height": 10})); + s.execute("select.set", &json!({"ids": [f]})).unwrap(); + let v = context(&mut s, json!({})); + assert_eq!(v["target"]["source"], "selection"); + assert_eq!(only(&v)["id"], f); + assert_eq!(only(&v)["children"][0]["id"], title); + assert_eq!(v["target"]["layers"], 3); + assert!(!v.to_string().contains("Elsewhere"), "the rest of the page stays out"); + let _ = other; +} + +#[test] +fn several_selected_layers_each_come_back() { + let mut s = session(); + let a = node(&mut s, json!({"type": "rectangle", "width": 10, "height": 10})); + let b = node(&mut s, json!({"type": "ellipse", "width": 10, "height": 10})); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + assert_eq!(context(&mut s, json!({}))["nodes"].as_array().unwrap().len(), 2); +} + +#[test] +fn ids_and_scopes_choose_the_target() { + let mut s = session(); + let (f, _, _) = card(&mut s); + let other = node(&mut s, json!({"type": "rectangle", "width": 10, "height": 10})); + s.execute("select.set", &json!({"ids": [other]})).unwrap(); + assert_eq!(context(&mut s, json!({"ids": [f]}))["target"]["source"], "ids"); + assert_eq!(context(&mut s, json!({"scope": "page"}))["nodes"].as_array().unwrap().len(), 2); + s.execute("page.add", &json!({"name": "Second"})).unwrap(); + assert_eq!(context(&mut s, json!({"scope": "document"}))["target"]["source"], "document"); + assert!(s.execute("inspect.designContext", &json!({"ids": [999_999]})).is_err()); + assert!(s.execute("inspect.designContext", &json!({"scope": "everything"})).is_err()); +} + +#[test] +fn nothing_selected_reads_the_page() { + let mut s = session(); + card(&mut s); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(context(&mut s, json!({}))["target"]["source"], "page"); +} + +#[test] +fn what_layout_decides_is_derived_and_what_the_designer_set_is_explicit() { + let mut s = session(); + let (f, _, _) = card(&mut s); + let v = context(&mut s, json!({"ids": [f]})); + let frame = only(&v); + assert_eq!(frame["explicit"]["width"], 300.0, "a fixed width is the designer's"); + assert_eq!(frame["explicit"]["x"], 40.0); + assert!(frame["explicit"].get("height").is_none(), "a hug height isn't"); + assert!(frame["derived"]["height"].is_number()); + assert!(frame["derived"]["absoluteBounds"].is_object()); + assert_eq!(frame["explicit"]["layout"]["gap"], 12.0); + let (title, rule) = (&frame["children"][0], &frame["children"][1]); + assert!(title["derived"].get("x").is_some(), "its place comes from the flow: {title}"); + assert!(title["explicit"].get("x").is_none()); + assert!(title["derived"].get("width").is_some(), "auto-width text: {title}"); + assert!(rule["derived"].get("width").is_some(), "fill: {rule}"); + assert_eq!(rule["explicit"]["height"], 2.0); +} + +#[test] +fn the_values_are_the_documents() { + let mut s = session(); + let (f, title, _) = card(&mut s); + let v = context(&mut s, json!({"ids": [f]})); + let got = &only(&v)["children"][0]["explicit"]; + let inspected = s.execute("node.get", &json!({"id": title})).unwrap(); + for key in ["characters", "fontFamily", "fontSize", "lineHeight", "letterSpacing", "textAlign", "fontStyle"] { + assert_eq!(got[key], inspected[key], "{key}"); + } + assert_eq!(got["characters"], "Pro plan"); +} + +#[test] +fn tokens_are_joined_with_every_modes_value() { + let mut s = session(); + let c = s.execute("variable.createCollection", &json!({"name": "Theme", "modes": ["Light", "Dark"]})).unwrap(); + let collection = c["id"].clone(); + let var = s + .execute( + "variable.create", + &json!({"collection": collection, "name": "surface", "type": "color", "values": {"Light": "#FFFFFF", "Dark": "#101010"}}), + ) + .unwrap(); + let var_id = var["id"].as_str().unwrap().to_string(); + s.execute("variable.update", &json!({"variable": var_id, "codeSyntax": {"WEB": "var(--surface)"}})).unwrap(); + let r = node(&mut s, json!({"type": "rectangle", "width": 10, "height": 10, "props": {"fill": {"$var": var_id}}})); + let v = context(&mut s, json!({"ids": [r]})); + let bound = only(&v)["tokens"].as_object().unwrap().values().next().unwrap().clone(); + assert_eq!((bound["variable"].as_str(), bound["name"].as_str()), (Some(var_id.as_str()), Some("surface"))); + let entry = &v["variables"][var_id.as_str()]; + assert_eq!((entry["name"].as_str(), entry["collection"].as_str()), (Some("surface"), Some("Theme"))); + assert_eq!(entry["codeSyntax"]["WEB"], "var(--surface)"); + assert_eq!(entry["modes"][0]["mode"], "Light"); + assert_eq!(entry["modes"][1]["resolved"], "#101010"); +} + +#[test] +fn a_shared_style_is_named_and_defined_once() { + let mut s = session(); + let r = node(&mut s, json!({"type": "rectangle", "width": 10, "height": 10, "props": {"fill": "#FF0000"}})); + let st = s.execute("style.create", &json!({"type": "paint", "name": "Brand/Red", "from": r})).unwrap(); + s.execute("style.apply", &json!({"style": st["id"], "ids": [r]})).unwrap(); + let v = context(&mut s, json!({"ids": [r]})); + assert_eq!(only(&v)["tokens"]["style.fill"]["name"], "Brand/Red"); + assert_eq!(v["styles"].as_object().unwrap().len(), 1); + assert_eq!(v["styles"][st["id"].as_str().unwrap()]["name"], "Brand/Red"); +} + +#[test] +fn a_connected_instance_gives_its_code_not_its_layers() { + let mut s = session(); + let b = node(&mut s, json!({"type": "frame", "name": "Button", "width": 80, "height": 32})); + node(&mut s, json!({"type": "text", "parent": b, "text": "Buy"})); + let main = id(&s.execute("component.create", &json!({"ids": [b]})).unwrap()); + let instance = id(&s.execute("instance.create", &json!({"component": main})).unwrap()); + s.execute("codeConnect.set", &json!({"id": main, "language": "react", "importPath": "@/ui/button", "name": "Button", "template": "