From 2bab7078bdaabbeccd7328d18e6edd5675542fc2 Mon Sep 17 00:00:00 2001 From: Abhinav Date: Sat, 31 Oct 2026 17:18:42 +0530 Subject: [PATCH 01/48] fix(board): map left and right connector controls to matching ends (#1744) --- contributors/people.toml | 3 +++ crates/ui-egui/src/board_line_tests.rs | 4 ++-- crates/ui-egui/src/canvas/board_bar.rs | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/contributors/people.toml b/contributors/people.toml index db1f5ce59..043a56407 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -98,3 +98,6 @@ sync_github_name = true [people.dylanmtaylor] sync_github_name = true + +[people.IamAbhinav01] +sync_github_name = true diff --git a/crates/ui-egui/src/board_line_tests.rs b/crates/ui-egui/src/board_line_tests.rs index 536cfcf15..7225d7105 100644 --- a/crates/ui-egui/src/board_line_tests.rs +++ b/crates/ui-egui/src/board_line_tests.rs @@ -51,8 +51,8 @@ fn pick(u: &mut Ui, x: f32, item: &str) { // The bar's parts from its left edge: 8 board colours from 8 (24 apart) and the colour wheel // (to 224), Straight, Elbow and Curved from 232 (30 apart), the start point (62 wide) from 328, the // end point from 392 and the line style from 462. -const START: f32 = 328.0 + 31.0; -const END: f32 = 392.0 + 31.0; +const END: f32 = 328.0 + 31.0; +const START: f32 = 392.0 + 31.0; const STYLE: f32 = 462.0 + 20.0; const WHEEL: f32 = 200.0 + 10.0; diff --git a/crates/ui-egui/src/canvas/board_bar.rs b/crates/ui-egui/src/canvas/board_bar.rs index 3d5baf43e..15c7d5a59 100644 --- a/crates/ui-egui/src/canvas/board_bar.rs +++ b/crates/ui-egui/src/canvas/board_bar.rs @@ -362,7 +362,7 @@ fn line_part(app: &mut FigApp, ui: &mut Ui, line: &Line, at: Pos2, t: &Tokens) { x += CELL + 2.0; } x = divider(ui, t, x - 2.0, at.y); - for (start, cap) in [(true, line.start), (false, line.end)] { + for (start, cap) in [(false, line.end), (true, line.start)] { cap_menu(app, ui, t, pos2(x, at.y), start, cap); x += CAP_W + 2.0; } From 59d5c3624470e787847a32c5fb74d4c61aaf2e86 Mon Sep 17 00:00:00 2001 From: Abhinav Date: Sat, 31 Oct 2026 19:18:02 +0530 Subject: [PATCH 02/48] chore: remove people.toml from PR scope --- contributors/people.toml | 3 --- 1 file changed, 3 deletions(-) diff --git a/contributors/people.toml b/contributors/people.toml index 043a56407..db1f5ce59 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -98,6 +98,3 @@ sync_github_name = true [people.dylanmtaylor] sync_github_name = true - -[people.IamAbhinav01] -sync_github_name = true From 0ac4e22dda1d4c96532c6f8524ce179c3239667e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 8 Nov 2026 23:28:04 -0500 Subject: [PATCH 03/48] M2: Add auto layout picks Figma's sizing, gap and padding defaults (Shift+A) layout.add now follows what Figma's web app does with synthetic rectangles: height hugs; width is fixed in a vertical flow and with an Auto gap (Space between, for two layers in a horizontal flow whose gap is at least the narrower one, and for a converted frame equal left and right offsets), and hugs otherwise; a converted frame's padding is its left and top offsets mirrored; one wrapped layer gets padding 10 and gap 10 and keeps its place. docs/auto-layout-parity.md updated. Existing tests whose setup or expected values encoded the old defaults were adjusted. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove and briefed; Fable 5.1 scoped the measurements; Sonnet 5.5 measured and wrote at medium --- crates/engine/src/al_behaviour_tests.rs | 177 +++++++++++++++++++ crates/engine/src/al_nesting_tests.rs | 2 + crates/engine/src/auto_layout_move_tests.rs | 2 +- crates/engine/src/cmd/structure.rs | 98 ++++++++-- crates/engine/src/convert_container_tests.rs | 8 +- crates/engine/src/dev/codegen.rs | 5 +- docs/auto-layout-parity.md | 7 +- 7 files changed, 278 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/al_behaviour_tests.rs b/crates/engine/src/al_behaviour_tests.rs index 514a39fdc..e0a1bd078 100644 --- a/crates/engine/src/al_behaviour_tests.rs +++ b/crates/engine/src/al_behaviour_tests.rs @@ -336,3 +336,180 @@ fn auto_layout_keys_beside_no_auto_layout_are_refused() { set(&mut s, f, json!({"layout": null, "name": "Plain"})); assert!(s.doc().unwrap().node(f).unwrap().layout.is_none()); } + +// ---- Add auto layout (Shift+A) defaults, measured in Figma's web app with synthetic rectangles ---- + +fn rect_at(s: &mut Session, parent: Option, x: f64, y: f64, w: f64, h: f64) -> NodeId { + let mut p = json!({"x": x, "y": y, "width": w, "height": h}); + if let (Some(parent), Some(o)) = (parent, p.as_object_mut()) { + o.insert("parent".into(), json!(parent)); + } + id(s.execute("shape.rectangle", &p).unwrap()) +} + +fn add_layout(s: &mut Session, ids: &[NodeId]) -> NodeId { + let r = s.execute("layout.add", &json!({"ids": ids})).unwrap(); + id_of(&r["ids"][0]).unwrap() +} + +fn canvas(s: &Session, node: NodeId) -> (f64, f64) { + let c = s.doc().unwrap().world_transform(node).as_coeffs(); + (c[4], c[5]) +} + +#[test] +fn shift_a_on_two_rects_far_apart_spaces_them_between_at_a_fixed_width() { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let b = rect_at(&mut s, None, 100.0, 0.0, 40.0, 40.0); + let f = add_layout(&mut s, &[a, b]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.main_align, l.padding), (LayoutMode::Horizontal, MainAlign::SpaceBetween, [0.0; 4])); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug)); + assert_eq!((n.width, n.height), (140.0, 40.0)); + assert_eq!((canvas(&s, a).0, canvas(&s, b).0), (0.0, 100.0)); +} + +#[test] +fn shift_a_gap_auto_needs_a_gap_at_least_the_narrower_child() { + // (first size, second x, second width, second height, Auto?) + for (w, x2, w2, h2, auto) in [ + (40.0, 72.0, 40.0, 40.0, false), + (40.0, 80.0, 40.0, 40.0, true), + (20.0, 52.0, 20.0, 20.0, true), + (100.0, 160.0, 100.0, 100.0, false), + (40.0, 100.0, 80.0, 60.0, true), + ] { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, w, w); + let b = rect_at(&mut s, None, x2, 0.0, w2, h2); + let f = add_layout(&mut s, &[a, b]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!(l.gap, x2 - w, "{w} {x2}"); + if auto { + assert_eq!((l.main_align, n.child_layout.sizing_h, n.width), (MainAlign::SpaceBetween, Sizing::Fixed, x2 + w2), "{w} {x2}"); + } else { + assert_ne!(l.main_align, MainAlign::SpaceBetween, "{w} {x2}"); + assert_eq!(n.child_layout.sizing_h, Sizing::Hug, "{w} {x2}"); + } + } +} + +#[test] +fn shift_a_on_three_rects_in_a_row_uses_the_mean_gap_and_hugs() { + for (xs, gap, width) in [([0.0, 100.0, 200.0], 60.0, 240.0), ([0.0, 100.0, 180.0], 50.0, 220.0)] { + let mut s = Session::new(); + let ids: Vec = xs.iter().map(|x| rect_at(&mut s, None, *x, 0.0, 40.0, 40.0)).collect(); + let f = add_layout(&mut s, &ids); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!(l.gap, gap); + assert_ne!(l.main_align, MainAlign::SpaceBetween); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v, n.width), (Sizing::Hug, Sizing::Hug, width)); + } +} + +#[test] +fn shift_a_on_stacked_rects_fixes_the_width_and_hugs_the_height() { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let b = rect_at(&mut s, None, 0.0, 100.0, 80.0, 60.0); + let f = add_layout(&mut s, &[a, b]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.gap), (LayoutMode::Vertical, 60.0)); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug)); + assert_eq!((n.width, n.height), (80.0, 160.0)); + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let b = rect_at(&mut s, None, 0.0, 240.0, 40.0, 40.0); + let f = add_layout(&mut s, &[a, b]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.gap), (LayoutMode::Vertical, 200.0)); + assert_ne!(l.main_align, MainAlign::SpaceBetween); + assert_eq!((n.child_layout.sizing_h, n.width), (Sizing::Fixed, 40.0)); +} + +#[test] +fn shift_a_on_one_rect_pads_ten_and_keeps_it_in_place() { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let f = add_layout(&mut s, &[a]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.gap, l.padding), (LayoutMode::Horizontal, 10.0, [10.0; 4])); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug)); + assert_eq!((n.width, n.height), (60.0, 60.0)); + assert_eq!(canvas(&s, f), (-10.0, -10.0)); + assert_eq!(canvas(&s, a), (0.0, 0.0)); + assert_eq!(size(&s, a), (40.0, 40.0)); +} + +fn filled_frame(s: &mut Session) -> NodeId { + id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 200, "props": {"fill": "#ff0000"}})).unwrap()) +} + +#[test] +fn shift_a_on_a_frame_mirrors_its_left_and_top_offsets() { + let mut s = Session::new(); + let f = filled_frame(&mut s); + rect_at(&mut s, Some(f), 20.0, 30.0, 40.0, 40.0); + rect_at(&mut s, Some(f), 120.0, 30.0, 40.0, 40.0); + let fills = s.doc().unwrap().node(f).unwrap().fills.len(); + let clip = s.doc().unwrap().node(f).unwrap().clip; + add_layout(&mut s, &[f]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.gap, l.padding), (LayoutMode::Horizontal, 60.0, [30.0, 20.0, 30.0, 20.0])); + assert_ne!(l.main_align, MainAlign::SpaceBetween); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug)); + assert_eq!((n.width, n.height), (180.0, 100.0)); + assert_eq!((n.fills.len(), n.clip), (fills, clip)); +} + +#[test] +fn shift_a_on_a_frame_with_centred_content_spaces_it_between() { + let mut s = Session::new(); + let f = filled_frame(&mut s); + rect_at(&mut s, Some(f), 49.0, 49.0, 40.0, 40.0); + rect_at(&mut s, Some(f), 211.0, 49.0, 40.0, 40.0); + add_layout(&mut s, &[f]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.main_align, l.padding), (MainAlign::SpaceBetween, [49.0; 4])); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug)); + assert_eq!((n.width, n.height), (300.0, 138.0)); +} + +#[test] +fn shift_a_on_a_frame_with_stacked_content_fixes_the_content_width() { + let mut s = Session::new(); + let f = filled_frame(&mut s); + rect_at(&mut s, Some(f), 20.0, 20.0, 40.0, 40.0); + rect_at(&mut s, Some(f), 20.0, 100.0, 40.0, 40.0); + add_layout(&mut s, &[f]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.gap, l.padding), (LayoutMode::Vertical, 40.0, [20.0; 4])); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug)); + assert_eq!((n.width, n.height), (80.0, 160.0)); +} + +#[test] +fn shift_a_on_a_group_follows_the_wrap_rule() { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let b = rect_at(&mut s, None, 100.0, 0.0, 40.0, 40.0); + let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap()); + let f = add_layout(&mut s, &[g]); + assert_eq!(f, g); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!(l.main_align, MainAlign::SpaceBetween); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug)); + assert_eq!((n.width, n.height), (140.0, 40.0)); + assert!(n.fills.is_empty() && !n.clip); +} diff --git a/crates/engine/src/al_nesting_tests.rs b/crates/engine/src/al_nesting_tests.rs index f3ab62a06..cf7733927 100644 --- a/crates/engine/src/al_nesting_tests.rs +++ b/crates/engine/src/al_nesting_tests.rs @@ -170,6 +170,8 @@ fn the_dragged_frame_never_receives_itself_and_plain_frames_in_a_flow_are_items( let list = frame(&mut s, None, 500.0, 0.0, 200.0, 400.0); let cards: Vec = (0..3).map(|i| frame(&mut s, Some(list), 0.0, i as f64 * 70.0, 150.0, 60.0)).collect(); s.execute("layout.add", &json!({"ids": [list], "direction": "vertical"})).unwrap(); + // The list now hugs its cards; padding gives it room around them to drop into. + s.execute("node.set", &json!({"id": list, "props": {"padding": 20, "sizingH": "hug"}})).unwrap(); s.execute("select.none", &json!({})).unwrap(); let card0 = bounds(&s, cards[0]); let grab = Point::new(bounds(&s, cards[2]).x0 + 3.0, bounds(&s, cards[2]).y0 + 3.0); diff --git a/crates/engine/src/auto_layout_move_tests.rs b/crates/engine/src/auto_layout_move_tests.rs index 49256dc64..9cc02d92a 100644 --- a/crates/engine/src/auto_layout_move_tests.rs +++ b/crates/engine/src/auto_layout_move_tests.rs @@ -47,7 +47,7 @@ fn a_frame_moved_inside_auto_layout_still_moves_its_siblings() { // A stack and a rectangle side by side in an outer auto layout frame: the outer layout still // follows when the stack grows. let (mut s, inner, [first, _]) = stack(); - let other = id_of(&s.execute("shape.rectangle", &json!({"x": 300, "y": 0, "width": 100, "height": 40})).unwrap()["id"]).unwrap(); + let other = id_of(&s.execute("shape.rectangle", &json!({"x": 150, "y": 0, "width": 100, "height": 40})).unwrap()["id"]).unwrap(); s.execute("select.set", &json!({"ids": [inner.0, other.0]})).unwrap(); s.execute("layout.add", &json!({})).unwrap(); let outer = s.doc().unwrap().node(inner).and_then(|n| n.parent).unwrap(); diff --git a/crates/engine/src/cmd/structure.rs b/crates/engine/src/cmd/structure.rs index 3339faa38..bb6973766 100644 --- a/crates/engine/src/cmd/structure.rs +++ b/crates/engine/src/cmd/structure.rs @@ -2,8 +2,8 @@ use figcraft_color::{Color, Paint}; use figcraft_doc::{ - AutoLayout, BoolOp, Corners, Document, LayoutMode, Node, NodeId, NodeKind, Region, RegionPaintSpace, Segment, Sizing, StrokeAlign, StrokeJoin, - StrokeProps, VectorNetwork, WindingRule, proto, + AutoLayout, BoolOp, Corners, Document, LayoutMode, MainAlign, Node, NodeId, NodeKind, Region, RegionPaintSpace, Segment, Sizing, StrokeAlign, + StrokeJoin, StrokeProps, VectorNetwork, WindingRule, proto, }; use figcraft_geom::{Affine, BezPath, Rect, Shape}; use serde_json::{Value, json}; @@ -680,6 +680,78 @@ fn sort_layout_children(doc: &Document, kids: &mut [NodeId], vertical: bool) { } } +/// What "Add auto layout" settled on for one frame, beyond the layout itself. +struct AddPlan { + layout: AutoLayout, + /// Width stays fixed (Figma fixes it in a vertical flow and with an Auto gap); otherwise it hugs. + fixed_width: bool, + /// A converted frame in a vertical flow shrinks to its content plus padding. + set_width: Option, + /// A wrap of one layer: the frame grows by this much around the layer and stays put on the canvas. + grow: f64, +} + +/// The layout "Add auto layout" gives a frame (measured in Figma's web app with synthetic +/// rectangles, 2026-11-09): height hugs; the width is fixed in a vertical flow and with an Auto +/// gap (main align Space between: two children, a gap at least the narrower child, and for a +/// converted frame equal left and right offsets), and hugs otherwise; a converted frame takes its +/// left and top offsets as padding, a wrap of several layers has none, a wrap of one layer pads 10. +fn add_layout(doc: &Document, frame: NodeId, new_wrap: bool, group: bool, dir: Option<&str>) -> AddPlan { + let wrapped = new_wrap || group; + let flow = figcraft_layout::flow_children(doc, frame); + let mut al = infer_layout(doc, frame); + let mut plan = AddPlan { layout: AutoLayout::default(), fixed_width: false, set_width: None, grow: 0.0 }; + if let Some(d) = dir { + al.mode = match d.to_ascii_lowercase().as_str() { + "vertical" | "column" => LayoutMode::Vertical, + "grid" => LayoutMode::Grid, + _ => LayoutMode::Horizontal, + }; + } + let Some(f) = doc.node(frame) else { + plan.layout = al; + return plan; + }; + if flow.is_empty() || (!new_wrap && flow.len() == 1) { + plan.layout = al; + return plan; + } + if new_wrap && flow.len() == 1 { + al.padding = [10.0; 4]; + al.gap = 10.0; + plan.grow = 10.0; + plan.layout = al; + return plan; + } + let mut boxes: Vec = + flow.iter().filter_map(|c| doc.node(*c)).map(|c| figcraft_geom::transform_rect_bbox(c.transform, c.local_rect())).collect(); + let vertical = al.mode == LayoutMode::Vertical; + boxes.sort_by(|a, b| if vertical { a.y0.total_cmp(&b.y0) } else { a.x0.total_cmp(&b.x0) }); + let gaps: Vec = + boxes.windows(2).filter_map(|w| Some(if vertical { w.get(1)?.y0 - w.first()?.y1 } else { w.get(1)?.x0 - w.first()?.x1 })).collect(); + al.gap = if gaps.is_empty() { 10.0 } else { (gaps.iter().sum::() / gaps.len() as f64).max(0.0).round() }; + let all = boxes.iter().copied().reduce(|a, b| a.union(b)).unwrap_or_default(); + let (left, top) = (all.x0.max(0.0).round(), all.y0.max(0.0).round()); + al.padding = if wrapped { [0.0; 4] } else { [top, left, top, left] }; + let content_w = all.x1 - all.x0; + if vertical { + plan.fixed_width = true; + if !wrapped { + plan.set_width = Some(content_w + 2.0 * left); + } + } else if al.mode == LayoutMode::Horizontal && boxes.len() == 2 { + let narrower = boxes.iter().map(Rect::width).fold(f64::MAX, f64::min); + let gap = gaps.first().copied().unwrap_or(0.0); + let centred = wrapped || ((all.x0) - (f.width - all.x1)).abs() <= 0.5; + if gap > 0.0 && gap >= narrower && centred { + al.main_align = MainAlign::SpaceBetween; + plan.fixed_width = true; + } + } + plan.layout = al; + plan +} + /// Add inferred auto layout to existing frames or one group converted in place; wrap other /// selections. Preserve mask boundaries and a converted group's Fill sizing in its parent. fn layout_add(s: &mut Session, p: &Value) -> Result { @@ -707,29 +779,33 @@ fn layout_add(s: &mut Session, p: &Value) -> Result { }; let doc = s.doc_mut()?; for f in &targets { - let mut al = infer_layout(doc, *f); - if let Some(d) = &dir { - al.mode = match d.to_ascii_lowercase().as_str() { - "vertical" | "column" => LayoutMode::Vertical, - "grid" => LayoutMode::Grid, - _ => LayoutMode::Horizontal, - }; - } + let plan = add_layout(doc, *f, !in_place, single_group, dir.as_deref()); + let al = plan.layout; let mut kids = doc.get(*f)?.children.clone(); sort_layout_children(doc, &mut kids, al.mode == LayoutMode::Vertical); let empty = doc.node(*f).is_some_and(|n| n.children.iter().filter_map(|c| doc.node(*c)).all(|c| !c.visible || c.child_layout.absolute)); let n = doc.get_mut(*f)?; n.children = kids; n.layout = Some(al); + if single_group { + n.fills.clear(); + n.clip = false; + } + if plan.grow > 0.0 { + n.transform = Affine::translate((-plan.grow, -plan.grow)) * n.transform; + } if !in_place || !empty { // A frame wrapped around the selection hugs it; an existing frame with no flow // children keeps its size instead of collapsing to its padding. if !single_group || n.child_layout.sizing_h != Sizing::Fill { - n.child_layout.sizing_h = Sizing::Hug; + n.child_layout.sizing_h = if plan.fixed_width { Sizing::Fixed } else { Sizing::Hug }; } if !single_group || n.child_layout.sizing_v != Sizing::Fill { n.child_layout.sizing_v = Sizing::Hug; } + if let Some(w) = plan.set_width { + n.width = w; + } } } s.set_selection(targets.clone()); diff --git a/crates/engine/src/convert_container_tests.rs b/crates/engine/src/convert_container_tests.rs index db1282932..2bb4180d7 100644 --- a/crates/engine/src/convert_container_tests.rs +++ b/crates/engine/src/convert_container_tests.rs @@ -33,7 +33,7 @@ fn kind(s: &Session, n: NodeId) -> NodeKind { fn adding_auto_layout_converts_a_single_group_and_arranges_its_children_directly() { let mut s = Session::new(); let page = s.page().unwrap(); - let (a, b) = (rect(&mut s, page, 10.0, 20.0), rect(&mut s, page, 90.0, 20.0)); + let (a, b) = (rect(&mut s, page, 10.0, 20.0), rect(&mut s, page, 80.0, 20.0)); let group = id(ex(&mut s, "object.group", json!({"ids": [a, b], "name": "Actions"}))); let siblings = s.doc().unwrap().node(page).unwrap().children.clone(); let before = [page_box(&s, group), page_box(&s, a), page_box(&s, b)]; @@ -52,7 +52,7 @@ fn adding_auto_layout_converts_a_single_group_and_arranges_its_children_directly // The second child now follows changes to the first through auto layout. ex(&mut s, "node.set", json!({"id": a, "props": {"width": 60}})); - assert_eq!(page_box(&s, b), [110.0, 20.0, 150.0, 40.0]); + assert_eq!(page_box(&s, b), [100.0, 20.0, 140.0, 40.0]); s.undo().unwrap(); s.undo().unwrap(); let restored = s.doc().unwrap().node(group).unwrap(); @@ -151,7 +151,7 @@ fn hidden_children_do_not_influence_inferred_direction_or_padding() { ex(&mut s, "layout.add", json!({"ids": [frame]})); let layout = s.doc().unwrap().node(frame).unwrap().layout.as_ref().unwrap(); assert_eq!(layout.mode, figcraft_doc::LayoutMode::Horizontal); - assert_eq!(layout.padding, [20.0, 170.0, 160.0, 10.0]); + assert_eq!(layout.padding, [20.0, 10.0, 20.0, 10.0]); assert_eq!(layout.gap, 40.0); assert_eq!([page_box(&s, a), page_box(&s, b)], before); } @@ -169,7 +169,7 @@ fn converting_a_group_preserves_fill_on_each_axis_in_its_parent() { let before = [page_box(&s, group), page_box(&s, sibling)]; ex(&mut s, "layout.add", json!({"ids": [group]})); let cl = &s.doc().unwrap().node(group).unwrap().child_layout; - assert_eq!(cl.sizing_h, if h == "fill" { Sizing::Fill } else { Sizing::Hug }); + assert_eq!(cl.sizing_h, if h == "fill" { Sizing::Fill } else { Sizing::Fixed }); assert_eq!(cl.sizing_v, if v == "fill" { Sizing::Fill } else { Sizing::Hug }); assert_eq!([page_box(&s, group), page_box(&s, sibling)], before); s.undo().unwrap(); diff --git a/crates/engine/src/dev/codegen.rs b/crates/engine/src/dev/codegen.rs index 202f7ef0f..80c3a19f7 100644 --- a/crates/engine/src/dev/codegen.rs +++ b/crates/engine/src/dev/codegen.rs @@ -544,7 +544,7 @@ mod tests { ".backgroundColor('#FFFFFF')", ".borderRadius(12)", ".width(", - ".height(100)", + &format!(".height({})", num(doc.node(f).map(|n| n.height).unwrap_or_default())), ".clip(true)", ] { assert!(ark.contains(want), "ArkUI has {want:?}:\n{ark}"); @@ -627,7 +627,8 @@ mod tests { let dart = code_for(doc, f, CodeLang::Flutter); // The card hugs its content, so its width is the layout's, not the 200 it was created with. let w = doc.node(f).map(|n| n.width).unwrap_or_default(); - assert!(dart.starts_with(&format!("Container(\n width: {},\n height: 100,\n", num(w))), "{dart}"); + let h = doc.node(f).map(|n| n.height).unwrap_or_default(); + assert!(dart.starts_with(&format!("Container(\n width: {},\n height: {},\n", num(w), num(h))), "{dart}"); assert!(dart.contains("borderRadius: BorderRadius.circular(12)"), "{dart}"); assert!(dart.contains("child: Row(\n"), "{dart}"); assert!(dart.contains(" Text(\n \"Say \\\"hi\\\" \\$5\\nnow\",\n"), "escaped: {dart}"); diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index f60cd4350..2c45dad42 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -1,6 +1,6 @@ # Auto layout and constraints parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-03 · **Change:** patch (a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-09 · **Change:** patch (Add auto layout picks the sizing, gap and padding Figma does, measured with synthetic rectangles: height hugs, width fixed in a vertical flow or with an Auto gap, Space between for two far-apart layers, padding from the converted frame's left and top offsets, 10 around a single wrapped layer; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) Auto layout is the most used layout feature in Figma and the one where small differences (a hugging frame one pixel off, text wrapping at another width) break real files. **Breadth ~98%, @@ -15,7 +15,7 @@ With one group selected, Add auto layout converts that group into a frame in pla id, name, parent and direct children. The Layout sidebar’s +, context menu, Shift+A and API calls all dispatch `layout.add`, so they share the conversion and a single undo step restores the group. The layout settings are inferred from visible, non-absolute children, matching the layout engine’s -flow. Hidden and absolute children therefore do not distort direction, gap or padding. A converted +flow, with the sizing, gap and padding defaults measured in Figma (see the Add auto layout row below); a converted group follows the rule for a wrap of several layers and ends with no fill and clip off. Hidden and absolute children therefore do not distort direction, gap or padding. A converted group keeps Fill sizing on either axis in its auto layout parent. Sorting by position preserves mask boundaries and the paint order within masked runs. The sidebar offers Add only when every selected container has no auto layout, including mixed selections. @@ -93,7 +93,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Constraints: left, right, left and right, centre, scale; top/bottom likewise | done | | | Layout grids: columns, rows, grid; stretch/left/centre/right; variables bound | done | | | Suggest auto layout | done | The target works out which layers belong together and adds as many auto layout frames as the design needs, in one step, keeping the placement. `layout.suggest` used to run `layout.add` and made one row of everything (#1823). Now it splits a frame's layers, by their boxes in the frame, along the vertical axis first: sorted by top edge, a layer joins the current row while it starts above the row's bottom (or together with it), and a gap, even a zero one, between the row and the next layer starts a new row. With two or more rows the frame becomes a Vertical auto layout whose items are the rows; otherwise the same split by columns gives a Horizontal one; if the layers overlap along both axes the frame gets no auto layout and the result carries a warning. A row or column of several layers goes into a new frame without fill or clipping, sized to it and inserted in its place (it hugs its content once the split gives it auto layout; a band whose own layers overlap along both axes gets none, with a warning, and stays a Fixed frame that cannot reflow those layers), and the split repeats inside it, to a depth of 16 and for up to 1,000 layers per frame (past that, or when a mask is among the layers, the layers are laid out in one list as Add auto layout does, with a warning). The frame keeps its size, Fixed: the gap is the distance between the bands, the padding along the flow is the first band's offset and the room left after the last, across the flow the smallest offset (alignment start), so with equal gaps and bands that start at the same offset every layer keeps its box exactly. When the gaps differ by more than 0.5 px the smallest is used and `warnings` says the later bands move; when the bands start at different offsets across the flow (a centred title above a card) they line up at the smallest, which moves the others, and `warnings` says so. Instances and layers inside them are refused with the error Convert to group gives, before anything changes; a main component works. `direction` sets the top level only. A single group becomes a frame in place and several layers are wrapped in a frame (both hug), as Add auto layout does; a frame with fewer than two layers is laid out as Add auto layout does. One undo step. Tests in `crates/engine/src/layout_suggest_tests.rs`: `two_rows_of_two_squares_become_a_vertical_frame_of_two_horizontal_rows`, `suggesting_auto_layout_is_one_undo_step`, `three_squares_in_a_row_get_one_horizontal_layout_without_nesting`, `three_squares_in_a_column_get_one_vertical_layout_without_nesting`, `a_header_above_two_columns_of_squares_gives_a_row_per_line`, `a_header_above_a_tall_layer_beside_a_column_nests_three_levels`, `unequal_gaps_use_the_smallest_and_say_so`, `overlapping_layers_leave_the_frame_without_auto_layout_and_say_so`, `a_group_becomes_a_frame_in_place_and_follows_the_rules`, `several_layers_are_wrapped_in_a_frame_that_is_then_split`, `a_direction_forces_the_top_level_and_nested_frames_follow_the_gaps`, `a_frame_with_one_layer_is_laid_out_like_add_auto_layout`, `add_auto_layout_still_makes_a_single_row`, `a_centred_title_above_a_card_is_lined_up_at_the_card_edge_with_a_warning`, `instances_and_layers_inside_them_are_refused_and_a_main_component_works`. Not attempted: overlapping layers, keeping uneven offsets across the flow (they line up at the smallest, with a warning), grids | -| "Add auto layout" on a selection | done | the Layout sidebar exposes Add auto layout (+) for groups and frames using the same `layout.add` command as the context menu; a single group becomes a frame in place, keeping its id, name and direct children; adding auto layout to an empty frame keeps its size, Fixed (it collapsed to 20×20); a frame with content still hugs it, as does a new frame wrapped around a selection (#369). `node.set` with auto layout keys on a mix of layers applies them to the frames and warns about the rest instead of failing the whole call (#603) | +| "Add auto layout" on a selection | done | the Layout sidebar exposes Add auto layout (+) for groups and frames using the same `layout.add` command as the context menu; a single group becomes a frame in place, keeping its id, name and direct children; adding auto layout to an empty frame keeps its size, Fixed (it collapsed to 20×20); a frame with content still hugs it, as does a new frame wrapped around a selection (#369). Add auto layout on a selection follows the defaults measured in Figma's web app with synthetic rectangles, 2026-11-09 (`al_behaviour_tests::shift_a_*`): the height hugs; the width is fixed in a vertical flow (a converted frame shrinks to its content plus the left and right padding) and with an Auto gap, and hugs otherwise; the gap is Auto (main align Space between, the measured gap stored) only in a horizontal flow of exactly two layers whose gap is at least the narrower layer's width (for a converted frame also with equal left and right offsets within 0.5 px), otherwise the rounded mean of the gaps; a converted frame takes the content's left offset for left and right padding and its top offset for top and bottom, a wrap of several layers has no padding, and a wrap of one layer pads 10 on every side with a gap of 10, hugs both ways and keeps the layer in place on the canvas (converting a frame with one child is unmeasured and unchanged). `node.set` with auto layout keys on a mix of layers applies them to the frames and warns about the rest instead of failing the whole call (#603) | | Real Figma files laid out identically | **not checked** | needs `.fig` or REST import of real files ([gaps](gaps.md) #1, #3) | | Performance: re-flow only where sizes or places changed | done | measured in `cargo xtask bench` (components at scale) | @@ -101,6 +101,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Date | Change | Summary | |---|---|---| +| 2026-11-09 | patch | M2: Add auto layout (`layout.add`, Shift+A) picks Figma's defaults, measured in Figma's web app with synthetic rectangles: height Hug; width Fixed in a vertical flow (a converted frame shrinks to its content plus padding) and with an Auto gap, Hug otherwise; Auto gap (Space between) for two layers in a horizontal flow whose gap is at least the narrower one (a converted frame also needs equal left and right offsets); a converted frame's padding is its left and top offsets mirrored; one wrapped layer gets padding 10, gap 10 and keeps its place. Tests: `al_behaviour_tests::shift_a_*`. Numbers unchanged | | 2026-11-05 | patch | M2, #1823: Suggest auto layout is no longer Add auto layout under another name: `layout.suggest` splits a frame's layers into rows (Vertical) or else columns (Horizontal) by the gaps between their boxes, wraps each band of several layers in a new frame without fill or clipping that hugs it, and repeats inside it (16 levels, 1,000 layers per frame at most). The frame keeps its size; gap and padding come from the bands, so layers keep their boxes where the gaps are even and the bands start at the same offset; instances and layers inside them are refused; uneven gaps (smallest used), bands that start at different offsets across the flow (lined up at the smallest) and layers that overlap along both axes come back as `warnings`. A band frame hugs only when its own split succeeds: a band whose layers overlap along both axes gets no auto layout and stays Fixed, so it cannot reflow those children. `direction` sets the top level only; one undo step; `layout.add` is unchanged. Tests in `layout_suggest_tests.rs` | | 2026-11-02 | patch | M2: 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. The modifier was ignored before. Test: `padding_individual_tests` | | 2026-11-03 | patch | M2, #1825: baseline alignment of a layer without text (an icon next to a text) puts its bottom on the line's baseline, as the help center's figure shows ("the bottoms of the icon and the word home are aligned on the red line"); it kept to the top of the line. A layer reaching below the text's baseline moves the text down, and a line with no text lines the layers' bottoms up (the documentation is silent; CSS baseline alignment does the same). Tests: `alignment_rules` (three cases), engine `baseline_alignment_puts_an_icons_bottom_on_the_text_baseline`. Numbers unchanged. | From 024281136acafaa5b63ddbd5cec41b384ccb730c Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 8 Nov 2026 23:29:20 -0500 Subject: [PATCH 04/48] M2: auto layout parity wording for the measured Add auto layout defaults Row 96 still said a frame with content hugs it before stating the measured rule, and the group paragraph's "therefore" followed the new clause. Docs only. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- docs/auto-layout-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index 2c45dad42..089d04bb4 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -15,7 +15,7 @@ With one group selected, Add auto layout converts that group into a frame in pla id, name, parent and direct children. The Layout sidebar’s +, context menu, Shift+A and API calls all dispatch `layout.add`, so they share the conversion and a single undo step restores the group. The layout settings are inferred from visible, non-absolute children, matching the layout engine’s -flow, with the sizing, gap and padding defaults measured in Figma (see the Add auto layout row below); a converted group follows the rule for a wrap of several layers and ends with no fill and clip off. Hidden and absolute children therefore do not distort direction, gap or padding. A converted +flow, so hidden and absolute children do not distort direction, gap or padding. The sizing, gap and padding defaults are the ones measured in Figma (see the Add auto layout row below): a converted group follows the rule for a wrap of several layers and ends with no fill and clip off. A converted group keeps Fill sizing on either axis in its auto layout parent. Sorting by position preserves mask boundaries and the paint order within masked runs. The sidebar offers Add only when every selected container has no auto layout, including mixed selections. @@ -93,7 +93,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Constraints: left, right, left and right, centre, scale; top/bottom likewise | done | | | Layout grids: columns, rows, grid; stretch/left/centre/right; variables bound | done | | | Suggest auto layout | done | The target works out which layers belong together and adds as many auto layout frames as the design needs, in one step, keeping the placement. `layout.suggest` used to run `layout.add` and made one row of everything (#1823). Now it splits a frame's layers, by their boxes in the frame, along the vertical axis first: sorted by top edge, a layer joins the current row while it starts above the row's bottom (or together with it), and a gap, even a zero one, between the row and the next layer starts a new row. With two or more rows the frame becomes a Vertical auto layout whose items are the rows; otherwise the same split by columns gives a Horizontal one; if the layers overlap along both axes the frame gets no auto layout and the result carries a warning. A row or column of several layers goes into a new frame without fill or clipping, sized to it and inserted in its place (it hugs its content once the split gives it auto layout; a band whose own layers overlap along both axes gets none, with a warning, and stays a Fixed frame that cannot reflow those layers), and the split repeats inside it, to a depth of 16 and for up to 1,000 layers per frame (past that, or when a mask is among the layers, the layers are laid out in one list as Add auto layout does, with a warning). The frame keeps its size, Fixed: the gap is the distance between the bands, the padding along the flow is the first band's offset and the room left after the last, across the flow the smallest offset (alignment start), so with equal gaps and bands that start at the same offset every layer keeps its box exactly. When the gaps differ by more than 0.5 px the smallest is used and `warnings` says the later bands move; when the bands start at different offsets across the flow (a centred title above a card) they line up at the smallest, which moves the others, and `warnings` says so. Instances and layers inside them are refused with the error Convert to group gives, before anything changes; a main component works. `direction` sets the top level only. A single group becomes a frame in place and several layers are wrapped in a frame (both hug), as Add auto layout does; a frame with fewer than two layers is laid out as Add auto layout does. One undo step. Tests in `crates/engine/src/layout_suggest_tests.rs`: `two_rows_of_two_squares_become_a_vertical_frame_of_two_horizontal_rows`, `suggesting_auto_layout_is_one_undo_step`, `three_squares_in_a_row_get_one_horizontal_layout_without_nesting`, `three_squares_in_a_column_get_one_vertical_layout_without_nesting`, `a_header_above_two_columns_of_squares_gives_a_row_per_line`, `a_header_above_a_tall_layer_beside_a_column_nests_three_levels`, `unequal_gaps_use_the_smallest_and_say_so`, `overlapping_layers_leave_the_frame_without_auto_layout_and_say_so`, `a_group_becomes_a_frame_in_place_and_follows_the_rules`, `several_layers_are_wrapped_in_a_frame_that_is_then_split`, `a_direction_forces_the_top_level_and_nested_frames_follow_the_gaps`, `a_frame_with_one_layer_is_laid_out_like_add_auto_layout`, `add_auto_layout_still_makes_a_single_row`, `a_centred_title_above_a_card_is_lined_up_at_the_card_edge_with_a_warning`, `instances_and_layers_inside_them_are_refused_and_a_main_component_works`. Not attempted: overlapping layers, keeping uneven offsets across the flow (they line up at the smallest, with a warning), grids | -| "Add auto layout" on a selection | done | the Layout sidebar exposes Add auto layout (+) for groups and frames using the same `layout.add` command as the context menu; a single group becomes a frame in place, keeping its id, name and direct children; adding auto layout to an empty frame keeps its size, Fixed (it collapsed to 20×20); a frame with content still hugs it, as does a new frame wrapped around a selection (#369). Add auto layout on a selection follows the defaults measured in Figma's web app with synthetic rectangles, 2026-11-09 (`al_behaviour_tests::shift_a_*`): the height hugs; the width is fixed in a vertical flow (a converted frame shrinks to its content plus the left and right padding) and with an Auto gap, and hugs otherwise; the gap is Auto (main align Space between, the measured gap stored) only in a horizontal flow of exactly two layers whose gap is at least the narrower layer's width (for a converted frame also with equal left and right offsets within 0.5 px), otherwise the rounded mean of the gaps; a converted frame takes the content's left offset for left and right padding and its top offset for top and bottom, a wrap of several layers has no padding, and a wrap of one layer pads 10 on every side with a gap of 10, hugs both ways and keeps the layer in place on the canvas (converting a frame with one child is unmeasured and unchanged). `node.set` with auto layout keys on a mix of layers applies them to the frames and warns about the rest instead of failing the whole call (#603) | +| "Add auto layout" on a selection | done | the Layout sidebar exposes Add auto layout (+) for groups and frames using the same `layout.add` command as the context menu; a single group becomes a frame in place, keeping its id, name and direct children; adding auto layout to an empty frame keeps its size, Fixed (it collapsed to 20×20, #369). A frame with content, and a new frame wrapped around a selection, take the defaults measured in Figma's web app with synthetic rectangles, 2026-11-09 (`al_behaviour_tests::shift_a_*`): the height hugs; the width is fixed in a vertical flow (a converted frame shrinks to its content plus the left and right padding) and with an Auto gap, and hugs otherwise; the gap is Auto (main align Space between, the measured gap stored) only in a horizontal flow of exactly two layers whose gap is at least the narrower layer's width (for a converted frame also with equal left and right offsets within 0.5 px), otherwise the rounded mean of the gaps; a converted frame takes the content's left offset for left and right padding and its top offset for top and bottom, a wrap of several layers has no padding, and a wrap of one layer pads 10 on every side with a gap of 10, hugs both ways and keeps the layer in place on the canvas (converting a frame with one child is unmeasured and unchanged). `node.set` with auto layout keys on a mix of layers applies them to the frames and warns about the rest instead of failing the whole call (#603) | | Real Figma files laid out identically | **not checked** | needs `.fig` or REST import of real files ([gaps](gaps.md) #1, #3) | | Performance: re-flow only where sizes or places changed | done | measured in `cargo xtask bench` (components at scale) | From 75fdf5ce585967db45e0931d2e409b6b24cd05a1 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 9 Nov 2026 15:19:26 -0500 Subject: [PATCH 05/48] M2: Shift+A tests pinned: exact alignment, narrower vs mean width, direction, one-child frame, group positions (#2137 review) Tests only. The ArkUI and Flutter card tests assert the hugged height (30) and the literal in the generated code; the Auto gap rule is tested with widths 40 and 100 and gap 60; direction vertical and horizontal are forced on a pair; non-Auto cases assert MainAlign::Min; a one-child frame keeps its inferred layout; a converted group keeps its children's positions; overlapping children clamp the gap to 0 and fractional gaps and offsets round. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 triaged and briefed; Sonnet 5.5 verified and wrote at medium --- crates/engine/src/al_behaviour_tests.rs | 86 +++++++++++++++++++++++-- crates/engine/src/dev/codegen.rs | 8 ++- 2 files changed, 87 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/al_behaviour_tests.rs b/crates/engine/src/al_behaviour_tests.rs index e0a1bd078..f7cb799a8 100644 --- a/crates/engine/src/al_behaviour_tests.rs +++ b/crates/engine/src/al_behaviour_tests.rs @@ -391,7 +391,7 @@ fn shift_a_gap_auto_needs_a_gap_at_least_the_narrower_child() { if auto { assert_eq!((l.main_align, n.child_layout.sizing_h, n.width), (MainAlign::SpaceBetween, Sizing::Fixed, x2 + w2), "{w} {x2}"); } else { - assert_ne!(l.main_align, MainAlign::SpaceBetween, "{w} {x2}"); + assert_eq!(l.main_align, MainAlign::Min, "{w} {x2}"); assert_eq!(n.child_layout.sizing_h, Sizing::Hug, "{w} {x2}"); } } @@ -406,7 +406,7 @@ fn shift_a_on_three_rects_in_a_row_uses_the_mean_gap_and_hugs() { let n = s.doc().unwrap().node(f).unwrap(); let l = n.layout.clone().unwrap(); assert_eq!(l.gap, gap); - assert_ne!(l.main_align, MainAlign::SpaceBetween); + assert_eq!(l.main_align, MainAlign::Min); assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v, n.width), (Sizing::Hug, Sizing::Hug, width)); } } @@ -429,7 +429,7 @@ fn shift_a_on_stacked_rects_fixes_the_width_and_hugs_the_height() { let n = s.doc().unwrap().node(f).unwrap(); let l = n.layout.clone().unwrap(); assert_eq!((l.mode, l.gap), (LayoutMode::Vertical, 200.0)); - assert_ne!(l.main_align, MainAlign::SpaceBetween); + assert_eq!(l.main_align, MainAlign::Min); assert_eq!((n.child_layout.sizing_h, n.width), (Sizing::Fixed, 40.0)); } @@ -464,7 +464,7 @@ fn shift_a_on_a_frame_mirrors_its_left_and_top_offsets() { let n = s.doc().unwrap().node(f).unwrap(); let l = n.layout.clone().unwrap(); assert_eq!((l.mode, l.gap, l.padding), (LayoutMode::Horizontal, 60.0, [30.0, 20.0, 30.0, 20.0])); - assert_ne!(l.main_align, MainAlign::SpaceBetween); + assert_eq!(l.main_align, MainAlign::Min); assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug)); assert_eq!((n.width, n.height), (180.0, 100.0)); assert_eq!((n.fills.len(), n.clip), (fills, clip)); @@ -512,4 +512,82 @@ fn shift_a_on_a_group_follows_the_wrap_rule() { assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug)); assert_eq!((n.width, n.height), (140.0, 40.0)); assert!(n.fills.is_empty() && !n.clip); + assert_eq!((canvas(&s, a).0, canvas(&s, b).0), (0.0, 100.0)); +} + +fn add_layout_dir(s: &mut Session, ids: &[NodeId], direction: &str) -> NodeId { + let r = s.execute("layout.add", &json!({"ids": ids, "direction": direction})).unwrap(); + id_of(&r["ids"][0]).unwrap() +} + +#[test] +fn shift_a_gap_auto_compares_the_narrower_width_not_the_mean() { + // Widths 40 and 100, gap 60: at least the narrower (40), below the mean (70). + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let b = rect_at(&mut s, None, 100.0, 0.0, 100.0, 40.0); + let f = add_layout(&mut s, &[a, b]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.gap, l.main_align, n.child_layout.sizing_h, n.width), (60.0, MainAlign::SpaceBetween, Sizing::Fixed, 200.0)); +} + +#[test] +fn shift_a_direction_vertical_on_a_horizontal_pair_stacks_with_a_fixed_width_and_no_space_between() { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let b = rect_at(&mut s, None, 100.0, 0.0, 40.0, 40.0); + let f = add_layout_dir(&mut s, &[a, b], "vertical"); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + // Measured along y the two overlap, so the gap clamps to 0. + assert_eq!((l.mode, l.gap, l.main_align), (LayoutMode::Vertical, 0.0, MainAlign::Min)); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v, n.width), (Sizing::Fixed, Sizing::Hug, 140.0)); +} + +#[test] +fn shift_a_direction_horizontal_on_a_stacked_pair_hugs_the_width() { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let b = rect_at(&mut s, None, 0.0, 100.0, 80.0, 60.0); + let f = add_layout_dir(&mut s, &[a, b], "horizontal"); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.gap, l.main_align), (LayoutMode::Horizontal, 0.0, MainAlign::Min)); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug)); +} + +#[test] +fn shift_a_overlapping_children_clamp_the_gap_to_zero_and_fractions_round() { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let b = rect_at(&mut s, None, 30.0, 0.0, 40.0, 40.0); + let f = add_layout(&mut s, &[a, b]); + let l = s.doc().unwrap().node(f).unwrap().layout.clone().unwrap(); + assert_eq!((l.gap, l.main_align), (0.0, MainAlign::Min)); + // Gaps 5 and 6 average 5.5, which rounds to 6. + let mut s = Session::new(); + let ids: Vec = [0.0, 45.0, 91.0].iter().map(|x| rect_at(&mut s, None, *x, 0.0, 40.0, 40.0)).collect(); + let f = add_layout(&mut s, &ids); + assert_eq!(s.doc().unwrap().node(f).unwrap().layout.clone().unwrap().gap, 6.0); + // Fractional left and top offsets round to whole padding. + let mut s = Session::new(); + let f = filled_frame(&mut s); + rect_at(&mut s, Some(f), 20.4, 30.6, 40.0, 40.0); + rect_at(&mut s, Some(f), 120.0, 30.6, 40.0, 40.0); + add_layout(&mut s, &[f]); + assert_eq!(s.doc().unwrap().node(f).unwrap().layout.clone().unwrap().padding, [31.0, 20.0, 31.0, 20.0]); +} + +#[test] +fn shift_a_on_a_frame_with_one_child_keeps_the_inferred_layout() { + let mut s = Session::new(); + let f = filled_frame(&mut s); + rect_at(&mut s, Some(f), 20.0, 30.0, 40.0, 40.0); + add_layout(&mut s, &[f]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.gap, l.padding, l.main_align), (LayoutMode::Horizontal, 10.0, [30.0, 240.0, 130.0, 20.0], MainAlign::Min)); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug)); + assert_eq!((n.width, n.height), (300.0, 200.0)); } diff --git a/crates/engine/src/dev/codegen.rs b/crates/engine/src/dev/codegen.rs index 80c3a19f7..cea82aee7 100644 --- a/crates/engine/src/dev/codegen.rs +++ b/crates/engine/src/dev/codegen.rs @@ -534,6 +534,8 @@ mod tests { let mut s = Session::new(); let f = card(&mut s); let doc = s.doc().unwrap(); + // Add auto layout hugs the height: the taller of the 24 ellipse and the text line (30). + assert_eq!(doc.node(f).map(|n| n.height), Some(30.0)); let ark = code_for(doc, f, CodeLang::ArkUi); for want in [ "Row({ space: ", @@ -544,7 +546,7 @@ mod tests { ".backgroundColor('#FFFFFF')", ".borderRadius(12)", ".width(", - &format!(".height({})", num(doc.node(f).map(|n| n.height).unwrap_or_default())), + ".height(30)", ".clip(true)", ] { assert!(ark.contains(want), "ArkUI has {want:?}:\n{ark}"); @@ -627,8 +629,8 @@ mod tests { let dart = code_for(doc, f, CodeLang::Flutter); // The card hugs its content, so its width is the layout's, not the 200 it was created with. let w = doc.node(f).map(|n| n.width).unwrap_or_default(); - let h = doc.node(f).map(|n| n.height).unwrap_or_default(); - assert!(dart.starts_with(&format!("Container(\n width: {},\n height: {},\n", num(w), num(h))), "{dart}"); + assert_eq!(doc.node(f).map(|n| n.height), Some(30.0), "hugs the taller of the ellipse and the text line"); + assert!(dart.starts_with(&format!("Container(\n width: {},\n height: 30,\n", num(w))), "{dart}"); assert!(dart.contains("borderRadius: BorderRadius.circular(12)"), "{dart}"); assert!(dart.contains("child: Row(\n"), "{dart}"); assert!(dart.contains(" Text(\n \"Say \\\"hi\\\" \\$5\\nnow\",\n"), "escaped: {dart}"); From 143067f2d59f5b901d86d0e58a397495bcfe187f Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 10 Nov 2026 13:47:19 -0500 Subject: [PATCH 06/48] M7: Variables JSON: export and import text styles (#2173) variable.export {format: "json"} now writes a top-level textStyles array beside meta: each own text style as style.list returns it, with bound holding the ids meta.variables is keyed by. variable.import reads it back: styles merge by name, bindings are re-pointed to the imported variables (one naming a variable the JSON lacks is dropped with a warning), junk entries are skipped with warnings, and the result gains styles {added, updated}. A shared text_kind helper now serves style.create, style.update and the new upsert_text_style. CSS, Tailwind and Dart stay variables-only. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.1 designed; Sonnet 5.5 wrote at medium --- ROADMAP.md | 1 + crates/engine/src/cmd/styles.rs | 39 ++++++++++++- crates/engine/src/cmd/variables_io.rs | 77 +++++++++++++++++++++++-- crates/engine/src/variables_io_tests.rs | 74 ++++++++++++++++++++++++ docs/components-parity.md | 2 + docs/file-format-parity.md | 2 +- docs/gaps.md | 2 +- docs/mcp.md | 4 +- 8 files changed, 190 insertions(+), 11 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index dc6204b44..c05574114 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | M7, #2173: `variable.export {format: "json"}` writes a top-level `textStyles` array beside `meta` (each text style as `style.list {type: "text"}` returns it, `bound` holding the ids `meta.variables` is keyed by), and `variable.import` reads it back (styles merged by name, bindings re-pointed, a binding to a variable the JSON lacks dropped with a warning). A FigCraft extension: the REST `styles` metadata has no values. CSS, Tailwind and Dart stay variables-only | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged | | 2026-11-06 | patch | M1, #2028: Edit ▸ Set default properties gives new rectangles, ellipses, polygons and stars drawn with the tools (and, set from a text layer, new text) the selected layer's properties; it only copied them for Paste properties. Tests: `default_props_tests` (3). Numbers unchanged | | 2026-11-06 | patch | M5, #2027: `proto.settings` refuses an unknown device name with the list of devices (it saved any string, and the presenter showed no device), takes known names in any case, and answers the page's prototype settings, so `proto.settings {}` reads them back over MCP. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back`. Numbers unchanged | diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index 9ba420c43..e50f5589d 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -256,6 +256,41 @@ fn text_style_json(cmd: &str, v: &Value) -> Result { serde_json::from_value::(v).map(|t| t.as_text_style()).map_err(|e| bad(cmd, e.to_string())) } +/// A text style value from JSON: the character values from `style`, the paragraph values from +/// `paragraph` (the same object for the flat `value` of `style.create`). +fn text_kind(cmd: &str, style: &Value, paragraph: &Value) -> Result { + Ok(StyleKind::Text { style: text_style_json(cmd, style)?, paragraph: Box::new(paragraph_style_json(cmd, paragraph)?) }) +} + +/// Make or redefine this file's text style `name` from JSON (see [`text_kind`]), with `bound` as its +/// variable bindings (those that name no field of the value are dropped). True when a style of +/// that name existed and was redefined (with the style's id); the caller settles and propagates. +pub(crate) fn upsert_text_style( + doc: &mut Document, + name: &str, + description: &str, + style: &Value, + paragraph: &Value, + bound: BTreeMap, +) -> Result<(StyleId, bool)> { + let cmd = "variable.import"; + let kind = text_kind(cmd, style, paragraph)?; + let same = + doc.styles.iter().position(|x| x.name == name && matches!(x.kind, StyleKind::Text { .. }) && !crate::library::is_remote_style(doc, &x.id)); + let updated = same.is_some(); + let mut st = match same.and_then(|i| doc.styles.get(i)) { + Some(x) => Style { kind, bound, ..x.clone() }, + None => Style { id: doc.new_style_id(), name: name.to_string(), description: description.to_string(), kind, bound }, + }; + crate::style_vars::prune(&mut st); + let sid = st.id.clone(); + match same.and_then(|i| doc.styles.get_mut(i)) { + Some(slot) => *slot = st, + None => doc.styles.push(st), + } + Ok((sid, updated)) +} + /// The text style definition a layer's chars from `at` (None = its base style) show. fn text_style_of(n: &Node, at: Option) -> Option { let t = n.kind.text()?; @@ -353,7 +388,7 @@ fn create(s: &mut Session, p: &Value) -> Result { let kind = if let Some(v) = get(p, "value") { match t.as_str() { "paint" | "color" | "fill" => StyleKind::Paint { paints: paints_of(v).ok_or_else(|| bad(cmd, "value: paints"))? }, - "text" => StyleKind::Text { style: text_style_json(cmd, v)?, paragraph: Box::new(paragraph_style_json(cmd, v)?) }, + "text" => text_kind(cmd, v, v)?, "effect" => StyleKind::Effect { effects: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, "grid" => StyleKind::Grid { grids: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, _ => return Err(bad(cmd, "type: paint|text|effect|grid")), @@ -550,7 +585,7 @@ fn update(s: &mut Session, p: &Value) -> Result { let cur = doc.styles.get(idx).map(|x| x.kind.type_name()).unwrap_or("paint"); Some(match cur { "paint" => StyleKind::Paint { paints: paints_of(v).ok_or_else(|| bad(cmd, "value: paints"))? }, - "text" => StyleKind::Text { style: text_style_json(cmd, v)?, paragraph: Box::new(paragraph_style_json(cmd, v)?) }, + "text" => text_kind(cmd, v, v)?, "effect" => StyleKind::Effect { effects: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, _ => StyleKind::Grid { grids: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, }) diff --git a/crates/engine/src/cmd/variables_io.rs b/crates/engine/src/cmd/variables_io.rs index 1b3b4ee29..e59027a11 100644 --- a/crates/engine/src/cmd/variables_io.rs +++ b/crates/engine/src/cmd/variables_io.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; -use figcraft_doc::{Collection, CollectionId, Document, Mode, ModeId, Variable, VariableId, VariableValue, Variables, trim_num}; +use figcraft_doc::{Collection, CollectionId, Document, Mode, ModeId, StyleKind, Variable, VariableId, VariableValue, Variables, trim_num}; use serde_json::{Value, json}; use super::CommandSpec; @@ -25,7 +25,7 @@ pub fn specs() -> Vec { spec!( "variable.import", "Import variables", - "{variables (the local variables JSON, as variable.export writes it: an object, JSON text or a path to a regular file of at most 256 MiB; `variableCollections` and `variables` under `meta` or at the top level)} collections join this file's collection of the same name (values by mode name; new modes and variables are added, a variable of another type is skipped), others are added → {collections (added), variables (added), updated, warnings (also when it holds no variables, or fewer than its collections list)}", + "{variables (the local variables JSON, as variable.export writes it: an object, JSON text or a path to a regular file of at most 256 MiB; `variableCollections` and `variables` under `meta` or at the top level; a top-level `textStyles` array, a FigCraft extension, adds this file's text styles by name with their variable bindings re-pointed)} collections join this file's collection of the same name (values by mode name; new modes and variables are added, a variable of another type is skipped), others are added → {collections (added), variables (added), updated, warnings (also when it holds no variables, or fewer than its collections list)}", true, import ), @@ -44,8 +44,13 @@ fn export(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(cmd, "collections: [collection ids or names]")), }; let text = match string(p, "format").as_deref().unwrap_or("json") { - "json" => serde_json::to_string_pretty(&figcraft_format::rest::export_variables(&doc.variables, &colls)) - .map_err(|e| EngineError::Other(e.to_string()))?, + "json" => { + let mut out = figcraft_format::rest::export_variables(&doc.variables, &colls); + if let Value::Object(m) = &mut out { + m.insert("textStyles".into(), text_styles(doc)); + } + serde_json::to_string_pretty(&out).map_err(|e| EngineError::Other(e.to_string()))? + } "css" => css(doc, &colls, false), "tailwind" => css(doc, &colls, true), "dart" => dart(&doc.variables, &colls), @@ -60,6 +65,61 @@ fn export(s: &mut Session, p: &Value) -> Result { } } +/// This file's own text styles as `style.list {type: "text"}` returns them (values and `bound`, +/// the variable ids being those `meta.variables` is keyed by): the `textStyles` of the variables +/// JSON, a FigCraft extension beside the REST-compatible `meta`. +fn text_styles(doc: &Document) -> Value { + let own = |st: &&figcraft_doc::Style| matches!(st.kind, StyleKind::Text { .. }) && !crate::library::is_remote_style(doc, &st.id); + Value::Array(doc.styles.iter().filter(own).filter_map(|st| serde_json::to_value(st).ok()).collect()) +} + +/// Read `entries` (the `textStyles` of a variables JSON) into this file: a style joins this file's +/// text style of the same name, others are added; bindings follow `ids` (imported variable id to +/// this file's). Returns (added, updated); what can't be read is a warning. +fn import_text_styles(doc: &mut Document, entries: &Value, ids: &BTreeMap, warnings: &mut Vec) -> (usize, usize) { + let Value::Array(list) = entries else { + warnings.push("`textStyles` should be an array of text styles: skipped".to_string()); + return (0, 0); + }; + let (mut added, mut updated) = (0, 0); + let mut touched = Vec::new(); + for (i, e) in list.iter().enumerate() { + let name = e.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()); + let (Some(name), Some(style)) = (name, e.get("style").filter(|x| x.is_object())) else { + warnings.push(format!("`textStyles` entry {i} needs a `name` and a `style` object: skipped")); + continue; + }; + let mut bound = BTreeMap::new(); + if let Some(Value::Object(m)) = e.get("bound") { + for (field, id) in m { + match id.as_str().and_then(|v| ids.get(v)) { + Some(local) => { + bound.insert(field.clone(), local.clone()); + } + None => warnings.push(format!("text style `{name}`: `{field}` is bound to a variable the JSON doesn't hold: left unbound")), + } + } + } + let description = e.get("description").and_then(Value::as_str).unwrap_or_default(); + match super::styles::upsert_text_style(doc, name, description, style, e.get("paragraph").unwrap_or(&Value::Null), bound) { + Ok((sid, was)) => { + touched.push(sid); + if was { + updated += 1; + } else { + added += 1; + } + } + Err(err) => warnings.push(format!("text style `{name}`: {err}")), + } + } + crate::style_vars::settle(doc); + for sid in touched { + super::styles::propagate_style(doc, &sid); + } + (added, updated) +} + /// `text` as a CSS comment or quoted string body. fn css_safe(text: &str) -> String { text.replace("*/", "* /").replace(['"', '\\', '\n', '\r', '\u{c}'], " ") @@ -362,5 +422,12 @@ fn import(s: &mut Session, p: &Value) -> Result { } } } - Ok(json!({"collections": added_colls, "variables": added, "updated": updated, "warnings": warnings})) + let (styles_added, styles_updated) = match v.get("textStyles") { + Some(entries) => import_text_styles(doc, entries, &ids, &mut warnings), + None => (0, 0), + }; + Ok(json!({ + "collections": added_colls, "variables": added, "updated": updated, + "styles": {"added": styles_added, "updated": styles_updated}, "warnings": warnings + })) } diff --git a/crates/engine/src/variables_io_tests.rs b/crates/engine/src/variables_io_tests.rs index eba692802..1d459207f 100644 --- a/crates/engine/src/variables_io_tests.rs +++ b/crates/engine/src/variables_io_tests.rs @@ -302,6 +302,80 @@ fn variables_import_checks_what_it_reads() { let (a, b) = (vars.get("a").unwrap(), vars.get("b").unwrap()); assert!(!a.values.values().chain(b.values.values()).all(|v| matches!(v, VariableValue::Alias(_))), "no loop"); healthy(&s); + // Junk `textStyles` entries are skipped with a warning, never an internal error. + let long = "n".repeat(200); + let empty = json!({"variableCollections": {}, "variables": {}}); + for junk in [json!(5), json!([3]), json!([{"name": 3}]), json!([{"name": "x", "style": "nope"}]), json!([{"name": long, "style": 7}])] { + let mut file = empty.clone(); + file["textStyles"] = junk.clone(); + match s.execute("variable.import", &json!({"variables": file})) { + Ok(r) => assert!(r["warnings"].to_string().contains("text style") || r["warnings"].to_string().contains("textStyles"), "{junk}: {r}"), + Err(e) => assert!(!matches!(e, crate::EngineError::Internal { .. }), "{junk}: {e}"), + } + } + assert!(s.doc().unwrap().styles.is_empty(), "no junk style got in"); +} + +/// A file with a "Body" text style whose size, line height and style name follow variables. +fn body_session() -> Session { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "Type", "modes": ["Base"]})); + ex(&mut s, "variable.create", json!({"collection": "Type", "name": "size", "type": "number", "value": 16})); + ex(&mut s, "variable.create", json!({"collection": "Type", "name": "lh", "type": "number", "value": 24})); + ex(&mut s, "variable.create", json!({"collection": "Type", "name": "face", "type": "string", "value": "Bold"})); + ex(&mut s, "style.create", json!({"type": "text", "name": "Body", "value": {"fontFamily": "Inter", "fontSize": 12, "lineHeight": "150%"}})); + for (field, v) in [("fontSize", "size"), ("lineHeight", "lh"), ("fontStyle", "face")] { + ex(&mut s, "style.bind", json!({"style": "Body", "field": field, "variable": v})); + } + s +} + +#[test] +fn variables_export_carries_text_styles_with_their_bindings() { + let mut s = body_session(); + let out = ex(&mut s, "variable.export", json!({})); + let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap(); + let styles = file["textStyles"].as_array().unwrap(); + assert_eq!(styles.len(), 1, "{file}"); + assert_eq!(styles[0]["name"], "Body"); + assert_eq!(styles[0]["style"]["font_size"], 16.0); + assert_eq!(styles[0]["style"]["font_style"], "Bold"); + assert_eq!(styles[0], ex(&mut s, "style.list", json!({"type": "text"}))[0], "what style.list returns"); + for field in ["fontSize", "lineHeight", "fontStyle"] { + let id = styles[0]["bound"][field].as_str().unwrap(); + assert!(file["meta"]["variables"].get(id).is_some(), "{field} -> {id}"); + } + let css = ex(&mut s, "variable.export", json!({"format": "css"})); + assert!(!css["text"].as_str().unwrap().contains("Body"), "{css}"); +} + +#[test] +fn text_styles_round_trip_through_variables_import() { + let mut s = body_session(); + let out = ex(&mut s, "variable.export", json!({})); + let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap(); + let mut t = Session::new(); + let r = ex(&mut t, "variable.import", json!({"variables": file})); + assert_eq!(r["styles"], json!({"added": 1, "updated": 0}), "{r}"); + let doc = t.doc().unwrap(); + let body = doc.styles.iter().find(|x| x.name == "Body").unwrap(); + let ids: Vec<&str> = body.bound.values().map(|v| v.as_str()).collect(); + assert_eq!(body.bound.len(), 3, "{body:?}"); + assert!(ids.iter().all(|i| doc.variables.get(i).is_some()), "bindings point at this file's variables"); + let StyleKind::Text { style, .. } = &body.kind else { panic!("{body:?}") }; + assert_eq!((style.font_style.as_str(), style.font_size), ("Bold", 16.0)); + // Again: the style is updated, not duplicated. + let r = ex(&mut t, "variable.import", json!({"variables": file})); + assert_eq!(r["styles"], json!({"added": 0, "updated": 1}), "{r}"); + assert_eq!(t.doc().unwrap().styles.len(), 1); + // A binding to a variable the JSON lacks is dropped with a warning naming the style. + let mut u = Session::new(); + let mut lone = file.clone(); + lone["meta"] = json!({"variableCollections": {}, "variables": {}}); + let r = ex(&mut u, "variable.import", json!({"variables": lone})); + assert_eq!(r["styles"]["added"], 1, "{r}"); + assert!(u.doc().unwrap().styles[0].bound.is_empty()); + assert!(r["warnings"].to_string().contains("Body"), "{r}"); } #[test] diff --git a/docs/components-parity.md b/docs/components-parity.md index 8fcaea78a..726fabeed 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -67,6 +67,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once | | Modes: add, duplicate, rename, delete, set as default / reorder | done | layers on Auto follow a new default; explicit modes stay | | Deleting a bound variable or its collection | done | layers keep their last value and are unbound; aliases to it take its values and colour calculations reading it keep the colour they show | +| Text styles in the Variables JSON export and import (`textStyles`, a FigCraft extension: the REST `styles` metadata has no values) | done | `variable.export {format: "json"}` adds a top-level `textStyles` array (values and `bound`, ids matching `meta.variables`); `variable.import` merges it by style name and re-points bindings; CSS, Tailwind and Dart are variables only | | 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) | | 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 | @@ -79,6 +80,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | M7, #2173: `variable.export {format: "json"}` writes a top-level `textStyles` array beside `meta` (each text style as `style.list {type: "text"}` returns it, `bound` holding the ids `meta.variables` is keyed by), and `variable.import` reads it back (styles merged by name, bindings re-pointed, a binding to a variable the JSON lacks dropped with a warning). A FigCraft extension: the REST `styles` metadata has no values. CSS, Tailwind and Dart stay variables-only | | 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/file-format-parity.md b/docs/file-format-parity.md index dd04fdf75..5031f1151 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -22,7 +22,7 @@ and prototype interactions are still unchecked there. | `.sketch` (Sketch 48 and newer) | import (file browser ▸ Import or drop, desktop app too; converted to a Figma file, symbols as components; per the help center) | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP; Open With from Finder, Explorer and Linux file managers once installed; recent files show its `previews/preview.png`) | no (out of scope) | zip + JSON read from the public format description; Sketch 43–47 (text as binary property lists) and older (SQLite) files are refused with a message to resave them in a newer Sketch. Pages, artboards as frames with their background, groups; Sketch 2025 and newer: frames (clipping or not) with their style, graphics, stacks as auto layout (direction, gap, alignment, padding, wrap, hug/fill sizing, stretching filling every item across, items ignoring the stack), corners in the style (rounded, smooth with its smoothing; angled, inside square and inside arc as paths), pins and sizing, per-side borders, lists of blurs (progressive background blurs, glass), inner shadows in the shadow list, tints (a graphic's, group's or instance's fill colouring its layers, and colour overrides; from Sketch 64, before which a group's fill draws nothing), text colour and visibility overrides, text sized by its sizing; rectangles with corner radii, ovals, stars and polygons while their points are the generated ones, paths as editable vector networks, shape groups as their shape, as one compound path (children without an operation, by the group's winding rule) or as boolean operations (mixed operations nested from the left); operands' own borders ignored as Sketch does; open paths filled as if closed, edited ovals and rectangles as paths, bitmaps (their image under their style's fills; colour adjustments as image filters with Sketch's tone curve, contrast and then brightness added), slices, hotspots; transforms (rotation, flips after it), resizing constraints; fills (solid, gradients with Sketch's geometry, gradients mixed in OKLab or OKLCH as sRGB stops along the same colours, image patterns), borders (the first enabled border's width and position), shadows, inner shadows, layer, motion and background blurs (Sketch's radius is the standard deviation), opacity and blend modes; clipping masks (an outline mask that shows its own style draws a copy under itself, as Sketch does, and its opacity fades it and what it clips together; alpha masks only mask; broken mask chains wrapped), progressive opacity (Fade) as an alpha mask of its gradient; text with styled runs (UTF-16 ranges), paragraph and vertical alignment, lines placed by Sketch's line spacing behaviour, box sizing, fonts found by their PostScript names among the installed ones (else the family read from the name), variable font axes, Sketch's natural line (ascent and descent rounded, no line gap, a fifth more for classic Mac fonts) for text without a fixed line height; symbols as components (library copies on a page of their own) and instances carrying their masters' layers with overrides (text, nested swaps and hiding, images, also on shapes' image fills, layer and text styles, nested paths), clipping only where the master clips (`clippingBehavior` 1), laid out for their size the way Sketch does it (proportional sharing per pins from format 110, scaling before) and still live; master backgrounds in instances only when the master includes them in both instances and exports, as on Sketch's canvas and renders; Apple's system fonts found under the names designs use, with the platform's tracking kept as letter spacing; shared layer styles as paint (fills, border colours) and effect styles, shared text styles as text styles; Color Variables (also library ones) as colour variables with bindings; prototype links, flow starts, export options, layout and square grids (hidden, as Sketch shows them only in its layout view). Instances of a stack laid out at their size and texts an override changed measured again on open, an auto-width one growing from its aligned edge. Warnings: noise fills, OKLab and OKLCH gradients, motion and zoom blurs (drawn as plain blurs), fonts embedded with their data (not used), Smart Layout (kept as laid out), locked overrides, scaled instances. Tested on fixtures built in code (`crates/format/src/sketch/*_tests.rs`, fuzzed) and locally (`FIGCRAFT_SKETCH_SAMPLES`) on one real Sketch 50 file and the public Apache-2.0 IBM Carbon Design Kit saved by Sketch 68 and 83 (70,000 layers open in ~3 s, debug build; its edition saved by Sketch 47 is refused, as it should be); compared artboard by artboard with Sketch 2026's own renders (`FIGCRAFT_SKETCHTOOL`, black-box): the Sketch 50 file's 73 artboards differ in at most 2.3% of their pixels (0.8% on average) (text metrics, fonts FigCraft doesn't find, antialiasing), Carbon 11's 69 1.1% on average and at most 4.4% (text in IBM Plex, which the file embeds and FigCraft doesn't use yet), a Sketch 64 file's 65 artboards 2.1% on average, a Sketch 2026 showcase file's 16 frames 0.9% on average (at most 1.9%); the rules for master backgrounds, symbol clipping, mask opacity, bitmap fills, image overrides, stretching stacks, blur radii, colour adjustments, gradient interpolation and text growth checked against Sketch's renders of files built for each case (black-box, synthetic) | 5–10 (Smart Layout as auto layout, motion and zoom blurs, several borders of different widths; fonts embedded in the file once `.figcraft` documents can carry fonts: until then they would only last the session). Known limitations: a plain group (not a frame) that fills a stack keeps its layers' size where Sketch stretches them; a font Sketch can't find draws in the installed family's own weight (Sketch falls back to a regular face); text in the system SF Pro comes out a few percent narrower than Sketch's; macOS's reserved system fonts (PingFang) aren't found; brightness past about +0.4 is approximated (image filters can't add); OKLab gradients become sRGB stops (FigCraft gradients mix in sRGB) | | `.jam` (whiteboards) | native to FigJam | **yes, best effort** (`file.open`, `file.import`, File ▸ Open, drop, CLI, MCP) | no | the same archive as a `.fig` (its canvas header reads `fig-jam.`) through the same reader (#1342): it opens as a board (the file kind; a `.fig` stays a design file), with generated sticky and shape backgrounds and text kept (#1341) as ordinary layers rather than native board objects (see [boards-parity](boards-parity.md)); tables, stamps, code blocks and the like come in as frames with their text and connectors as vectors (an elbowed connector keeps the path it was saved with, #1910), with an import note; a layer type the reader doesn't know is left out with a note naming it; writing `.jam` is not supported | — | | `.deck` (Slides) | native to other Figma products | no | no | out of scope | — | -| REST API file JSON (`GET /v1/files/:key`) + local variables JSON + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints, strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings, image adjustments (the same tint sign as `.fig`); the import report after opening; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — | +| REST API file JSON (`GET /v1/files/:key`) + local variables JSON (+ a FigCraft `textStyles` array on export and import) + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints, strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings, image adjustments (the same tint sign as `.fig`); the import report after opening; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — | | `.figcraft` (ours: zip of `document.json` + images, versions inside) | — | yes | yes | streamed JSON, 50k layers save ~0.09 s / load ~0.16 s (`cargo xtask bench`); old files keep opening (`large_tests.rs`); image members are `images/`, and a key that can't be one — path text, a space, over 128 chars — is left out with a complaint instead of loaded (`image_tests`); saves write a unique staging file and rename it into place (#284); optional auto-save of files with a path (`pref.autoSave`, #305); Save and auto-save refuse to write over a file another app (figcraft-cli, say) changed since it was opened or saved here, judged by its size and modification time: Revert to saved loads those changes, Save as keeps both, `file.save {overwrite: true}` replaces them (#1330); `kind: "board"` marks a board (left out for design files, so files from before boards are design files; the home screen reads it for the file's mark); board objects keep their `board` metadata on the layer; Developer Mode measurements are kept on the layer they start from (`measurements: [{to} | {side}]`, left out when there are none, so older files open with none) | — | | Local library files | team libraries in the cloud | yes (enable a `.figcraft` as a library) | yes (publish) | per-asset versions, updates with overrides kept | see [collaboration-parity](collaboration-parity.md) | diff --git a/docs/gaps.md b/docs/gaps.md index f42b97e4e..f31c41183 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -408,7 +408,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe - **Landed:** extended collections (`library.extendCollection`: a library collection's modes and variables in a collection of this file, values overridden per mode with reset, following library updates, variables of its own), variables import/export (`variable.export` / `variable.import`: - the REST local variables JSON, merged by name; CSS custom properties), gradient stops and variant + the REST local variables JSON, merged by name, with the file's text styles under `textStyles`; CSS custom properties), gradient stops and variant properties bound to variables. - **Landed (2026-10-12):** variables a library adds to a collection this file extends are a library update of their own (`library.updates` lists them by name, without an `id` until they have a diff --git a/docs/mcp.md b/docs/mcp.md index 04b37e1f0..3f19b8379 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1232,13 +1232,13 @@ Dart constants for Flutter (`format: "dart"`: an `abstract final class` per coll default mode's named after the collection and the others after the collection and the mode, with a `static const` `Color`, `double`, `String` or `bool` per variable; names become camelCase Dart identifiers kept apart, aliases are resolved to their value in that mode), and -returns `{text}` (or writes `path` and returns `{path}`). `variable.import {variables}` (an object, +returns `{text}` (or writes `path` and returns `{path}`). The JSON format also carries a top-level `textStyles` array beside `meta`, a FigCraft extension (the REST `styles` metadata has no values): each entry is what `style.list {type: "text"}` returns (`name`, `style`, `paragraph`, and `bound` holding the same variable ids `meta.variables` is keyed by); CSS, Tailwind and Dart are variables only. `variable.import {variables}` (an object, JSON text or a path to a regular file of at most 256 MiB; `variableCollections` and `variables` under `meta` or at the top level) reads one back: a collection joins this file's collection of the same name (values matched by mode name, new modes and variables added, a same-named variable of another type skipped with a warning; library copies and extended collections are never targets), others are -added; aliases are checked for loops; it returns `{collections, variables, updated, warnings}`, +added; aliases are checked for loops; a `textStyles` array is read too (a style joins this file's text style of the same name, others are added; bindings follow the imported variables, one to a variable the JSON lacks is dropped with a warning); it returns `{collections, variables, updated, styles: {added, updated}, warnings}`, with a warning when the JSON holds no variables (`no variables found: expected meta.variables …`) or fewer than its collections list in `variableIds`. The Variables editor's Import… and Export… buttons do the same through file dialogs. From 355caa79dcd18bd4c7dfabef2690e9d988b04bd2 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 10 Nov 2026 14:07:44 -0500 Subject: [PATCH 07/48] M7: Variables JSON text styles: a file's own export round-trips, caps, binding checks (#2173) Importing a file's own export keeps the bindings of the text styles it replaces (ids the import doesn't carry), and same-named styles match one by one instead of all hitting the first. Entries (10,000), names (500), descriptions (10,000) and bindings (32 per style) are capped; a binding to a field the style lacks or a variable of another type is dropped with a warning. Warnings no longer name the command. The spec strings, status lines and docs/mcp.md describe the format. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.1 reviewed; Sonnet 5.5 wrote at medium --- ROADMAP.md | 2 +- crates/engine/src/cmd/styles.rs | 19 +++--- crates/engine/src/cmd/variables_io.rs | 84 +++++++++++++++++++------ crates/engine/src/variables_io_tests.rs | 78 ++++++++++++++++++++++- docs/components-parity.md | 2 +- docs/file-format-parity.md | 2 +- docs/gaps.md | 2 +- docs/mcp.md | 4 +- 8 files changed, 157 insertions(+), 36 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c05574114..0a7ca6c78 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** patch (the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index e50f5589d..a61f4f18c 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -262,22 +262,25 @@ fn text_kind(cmd: &str, style: &Value, paragraph: &Value) -> Result { Ok(StyleKind::Text { style: text_style_json(cmd, style)?, paragraph: Box::new(paragraph_style_json(cmd, paragraph)?) }) } -/// Make or redefine this file's text style `name` from JSON (see [`text_kind`]), with `bound` as its -/// variable bindings (those that name no field of the value are dropped). True when a style of -/// that name existed and was redefined (with the style's id); the caller settles and propagates. +/// Make or redefine this file's text style `name` from JSON (see [`text_kind`]). `bind` gives its +/// variable bindings from the document, the new value and the style it replaces. The style +/// redefined is the first local text style of that name not in `touched`. True when one existed +/// (with the style's id); the caller settles and propagates. pub(crate) fn upsert_text_style( doc: &mut Document, name: &str, description: &str, style: &Value, paragraph: &Value, - bound: BTreeMap, + touched: &[StyleId], + bind: impl FnOnce(&Document, &StyleKind, Option<&Style>) -> BTreeMap, ) -> Result<(StyleId, bool)> { - let cmd = "variable.import"; - let kind = text_kind(cmd, style, paragraph)?; - let same = - doc.styles.iter().position(|x| x.name == name && matches!(x.kind, StyleKind::Text { .. }) && !crate::library::is_remote_style(doc, &x.id)); + let kind = text_kind("variable.import", style, paragraph)?; + let same = doc.styles.iter().position(|x| { + x.name == name && matches!(x.kind, StyleKind::Text { .. }) && !crate::library::is_remote_style(doc, &x.id) && !touched.contains(&x.id) + }); let updated = same.is_some(); + let bound = bind(doc, &kind, same.and_then(|i| doc.styles.get(i))); let mut st = match same.and_then(|i| doc.styles.get(i)) { Some(x) => Style { kind, bound, ..x.clone() }, None => Style { id: doc.new_style_id(), name: name.to_string(), description: description.to_string(), kind, bound }, diff --git a/crates/engine/src/cmd/variables_io.rs b/crates/engine/src/cmd/variables_io.rs index e59027a11..5816ea44b 100644 --- a/crates/engine/src/cmd/variables_io.rs +++ b/crates/engine/src/cmd/variables_io.rs @@ -18,14 +18,14 @@ pub fn specs() -> Vec { spec!( "variable.export", "Export variables", - "{collections? [ids or names; default every collection of this file, not library copies], format? (json (default): the local variables JSON that variable.import reads, colour calculations as the colour they show in each mode with other collections in their default modes | css: custom properties, the default mode on :root and each other mode on [data-=\"\"], colour calculations as the colour they show in that mode with other collections in their default modes; numbers in px unless layers or scopes use them as opacity or font weight | tailwind: a Tailwind CSS v4 stylesheet, the default mode as an @theme block named the way inspect.code's tailwind utilities read them: --color-*, --radius-*, --text-*, --spacing-*, --font-*, unique per file; each other mode as in css; colour calculations as the colour they show in that mode, other collections in their default modes) | dart: a Dart file for Flutter, a class of constants per collection and mode (Color, double, String, bool), aliases and colour calculations resolved), path? (write it there)} → {text}, or {path} when written", + "{collections? [ids or names; default every collection of this file, not library copies], format? (json (default): the local variables JSON that variable.import reads, colour calculations as the colour they show in each mode with other collections in their default modes | css: custom properties, the default mode on :root and each other mode on [data-=\"\"], colour calculations as the colour they show in that mode with other collections in their default modes; numbers in px unless layers or scopes use them as opacity or font weight | tailwind: a Tailwind CSS v4 stylesheet, the default mode as an @theme block named the way inspect.code's tailwind utilities read them: --color-*, --radius-*, --text-*, --spacing-*, --font-*, unique per file; each other mode as in css; colour calculations as the colour they show in that mode, other collections in their default modes) | dart: a Dart file for Flutter, a class of constants per collection and mode (Color, double, String, bool), aliases and colour calculations resolved), path? (write it there)} → {text}, or {path} when written; the json format adds a top-level `textStyles` array (this file's text styles as style.list returns them, `bound` holding the ids `meta.variables` is keyed by), a FigCraft extension beside the REST-compatible `meta`", false, export ), spec!( "variable.import", "Import variables", - "{variables (the local variables JSON, as variable.export writes it: an object, JSON text or a path to a regular file of at most 256 MiB; `variableCollections` and `variables` under `meta` or at the top level; a top-level `textStyles` array, a FigCraft extension, adds this file's text styles by name with their variable bindings re-pointed)} collections join this file's collection of the same name (values by mode name; new modes and variables are added, a variable of another type is skipped), others are added → {collections (added), variables (added), updated, warnings (also when it holds no variables, or fewer than its collections list)}", + "{variables (the local variables JSON, as variable.export writes it: an object, JSON text or a path to a regular file of at most 256 MiB; `variableCollections` and `variables` under `meta` or at the top level; a top-level `textStyles` array, a FigCraft extension, adds this file's text styles by name with their variable bindings re-pointed)} collections join this file's collection of the same name (values by mode name; new modes and variables are added, a variable of another type is skipped), others are added → {collections (added), variables (added), updated, styles {added, updated}, warnings (also when it holds no variables, or fewer than its collections list)}", true, import ), @@ -73,35 +73,38 @@ fn text_styles(doc: &Document) -> Value { Value::Array(doc.styles.iter().filter(own).filter_map(|st| serde_json::to_value(st).ok()).collect()) } +/// At most this many text styles are read from a variables JSON, this many bindings per style, and +/// this many chars of a description. +const MAX_TEXT_STYLES: usize = 10_000; +const MAX_STYLE_BINDINGS: usize = 32; +const MAX_STYLE_DESCRIPTION: usize = 10_000; + /// Read `entries` (the `textStyles` of a variables JSON) into this file: a style joins this file's -/// text style of the same name, others are added; bindings follow `ids` (imported variable id to -/// this file's). Returns (added, updated); what can't be read is a warning. +/// text style of the same name (the first one this import hasn't touched yet), others are added; +/// bindings follow `ids` (imported variable id to this file's). Returns (added, updated); what +/// can't be read is a warning. fn import_text_styles(doc: &mut Document, entries: &Value, ids: &BTreeMap, warnings: &mut Vec) -> (usize, usize) { let Value::Array(list) = entries else { warnings.push("`textStyles` should be an array of text styles: skipped".to_string()); return (0, 0); }; + if list.len() > MAX_TEXT_STYLES { + warnings.push(format!("`textStyles` holds {} entries: only the first {MAX_TEXT_STYLES} are read", list.len())); + } let (mut added, mut updated) = (0, 0); let mut touched = Vec::new(); - for (i, e) in list.iter().enumerate() { - let name = e.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()); + for (i, e) in list.iter().take(MAX_TEXT_STYLES).enumerate() { + let name = e.get("name").and_then(Value::as_str).and_then(super::variables::clean_name); let (Some(name), Some(style)) = (name, e.get("style").filter(|x| x.is_object())) else { warnings.push(format!("`textStyles` entry {i} needs a `name` and a `style` object: skipped")); continue; }; - let mut bound = BTreeMap::new(); - if let Some(Value::Object(m)) = e.get("bound") { - for (field, id) in m { - match id.as_str().and_then(|v| ids.get(v)) { - Some(local) => { - bound.insert(field.clone(), local.clone()); - } - None => warnings.push(format!("text style `{name}`: `{field}` is bound to a variable the JSON doesn't hold: left unbound")), - } - } - } - let description = e.get("description").and_then(Value::as_str).unwrap_or_default(); - match super::styles::upsert_text_style(doc, name, description, style, e.get("paragraph").unwrap_or(&Value::Null), bound) { + let description: String = e.get("description").and_then(Value::as_str).unwrap_or_default().chars().take(MAX_STYLE_DESCRIPTION).collect(); + let wanted = e.get("bound"); + let bind = |doc: &Document, kind: &StyleKind, current: Option<&figcraft_doc::Style>| { + text_style_bindings(&name, wanted, ids, doc, kind, current, warnings) + }; + match super::styles::upsert_text_style(doc, &name, &description, style, e.get("paragraph").unwrap_or(&Value::Null), &touched, bind) { Ok((sid, was)) => { touched.push(sid); if was { @@ -110,6 +113,7 @@ fn import_text_styles(doc: &mut Document, entries: &Value, ids: &BTreeMap warnings.push(format!("text style `{name}`: {msg}")), Err(err) => warnings.push(format!("text style `{name}`: {err}")), } } @@ -120,6 +124,48 @@ fn import_text_styles(doc: &mut Document, entries: &Value, ids: &BTreeMap, + ids: &BTreeMap, + doc: &Document, + kind: &StyleKind, + current: Option<&figcraft_doc::Style>, + warnings: &mut Vec, +) -> BTreeMap { + let mut bound = BTreeMap::new(); + let Some(Value::Object(m)) = wanted else { return bound }; + if m.len() > MAX_STYLE_BINDINGS { + warnings.push(format!("text style `{name}`: {} bindings: only the first {MAX_STYLE_BINDINGS} are read", m.len())); + } + for (field, id) in m.iter().take(MAX_STYLE_BINDINGS) { + let held = current.and_then(|c| c.bound.get(field)).filter(|h| id.as_str() == Some(h.as_str())); + let local = id.as_str().and_then(|v| ids.get(v)).or(held); + match checked_binding(doc, kind, field, local) { + Ok(local) => { + bound.insert(field.clone(), local.clone()); + } + Err(why) => warnings.push(format!("text style `{name}`: {why}: left unbound")), + } + } + bound +} + +/// `local` when it is a variable of this file of the type a text style's `field` takes. +fn checked_binding<'a>(doc: &Document, kind: &StyleKind, field: &str, local: Option<&'a VariableId>) -> std::result::Result<&'a VariableId, String> { + let local = local.ok_or_else(|| format!("`{field}` is bound to a variable the JSON doesn't hold"))?; + let want = crate::style_vars::field_type(kind, field).ok_or_else(|| format!("no field `{field}` to bind"))?; + match doc.variables.get_by_id(local).map(|v| v.kind) { + Some(k) if k == want => Ok(local), + Some(k) => Err(format!("`{field}` takes a {} variable, not a {} one", want.id(), k.id())), + None => Err(format!("`{field}` is bound to a variable this file lacks")), + } +} + /// `text` as a CSS comment or quoted string body. fn css_safe(text: &str) -> String { text.replace("*/", "* /").replace(['"', '\\', '\n', '\r', '\u{c}'], " ") diff --git a/crates/engine/src/variables_io_tests.rs b/crates/engine/src/variables_io_tests.rs index 1d459207f..5ac6654a3 100644 --- a/crates/engine/src/variables_io_tests.rs +++ b/crates/engine/src/variables_io_tests.rs @@ -302,10 +302,17 @@ fn variables_import_checks_what_it_reads() { let (a, b) = (vars.get("a").unwrap(), vars.get("b").unwrap()); assert!(!a.values.values().chain(b.values.values()).all(|v| matches!(v, VariableValue::Alias(_))), "no loop"); healthy(&s); +} + +#[test] +fn text_styles_in_a_variables_json_are_checked_and_capped() { + let mut s = Session::new(); + let mode = json!([{"modeId": "m", "name": "Mode 1"}]); // Junk `textStyles` entries are skipped with a warning, never an internal error. - let long = "n".repeat(200); let empty = json!({"variableCollections": {}, "variables": {}}); - for junk in [json!(5), json!([3]), json!([{"name": 3}]), json!([{"name": "x", "style": "nope"}]), json!([{"name": long, "style": 7}])] { + for junk in + [json!(5), json!([3]), json!([{"name": 3}]), json!([{"name": "x", "style": "nope"}]), json!([{"name": "x", "style": {"font_size": "big"}}])] + { let mut file = empty.clone(); file["textStyles"] = junk.clone(); match s.execute("variable.import", &json!({"variables": file})) { @@ -313,7 +320,35 @@ fn variables_import_checks_what_it_reads() { Err(e) => assert!(!matches!(e, crate::EngineError::Internal { .. }), "{junk}: {e}"), } } + let mut file = empty.clone(); + file["textStyles"] = json!([{"name": "x", "style": {"font_size": "big"}}]); + let r = ex(&mut s, "variable.import", json!({"variables": file})); + assert!(r["warnings"].to_string().contains("text style `x`"), "{r}"); assert!(s.doc().unwrap().styles.is_empty(), "no junk style got in"); + // A name is cut to 500 chars, a description to 10,000, and only the first 10,000 entries are read. + let mut file = empty.clone(); + file["textStyles"] = json!([{"name": "n".repeat(100_000), "description": "d".repeat(100_000), "style": {}}]); + ex(&mut s, "variable.import", json!({"variables": file})); + let styles = &s.doc().unwrap().styles; + assert_eq!(styles.len(), 1); + assert!(styles[0].name.chars().count() <= 500 && styles[0].description.chars().count() <= 10_000, "{}", styles[0].name.len()); + let mut file = empty.clone(); + file["textStyles"] = Value::Array((0..10_050).map(|i| json!({"name": format!("s{i}"), "style": {}})).collect()); + let r = ex(&mut s, "variable.import", json!({"variables": file})); + assert_eq!(r["styles"]["added"], 10_000, "{}", r["styles"]); + assert!(r["warnings"].to_string().contains("10000") || r["warnings"].to_string().contains("10,000"), "{}", r["warnings"]); + // A binding to a field the style lacks, or to a variable of another type, is dropped with a warning. + let mut t = Session::new(); + let file = json!({ + "meta": {"variableCollections": {"c": {"id": "c", "name": "T", "modes": mode}}, + "variables": {"s": {"id": "s", "name": "s", "variableCollectionId": "c", "resolvedType": "STRING", "valuesByMode": {"m": "x"}}}}, + "textStyles": [{"name": "t", "style": {}, "bound": {"fontSize": "s", "nope": "s"}}] + }); + let r = ex(&mut t, "variable.import", json!({"variables": file})); + assert_eq!(r["styles"]["added"], 1, "{r}"); + assert!(t.doc().unwrap().styles[0].bound.is_empty(), "{r}"); + let w = r["warnings"].as_array().unwrap().iter().filter_map(|x| x.as_str()).filter(|x| x.contains("text style `t`")).collect::>(); + assert!(w.len() == 2 && w.iter().any(|x| x.contains("fontSize")) && w.iter().any(|x| x.contains("nope")), "{r}"); } /// A file with a "Body" text style whose size, line height and style name follow variables. @@ -323,7 +358,11 @@ fn body_session() -> Session { ex(&mut s, "variable.create", json!({"collection": "Type", "name": "size", "type": "number", "value": 16})); ex(&mut s, "variable.create", json!({"collection": "Type", "name": "lh", "type": "number", "value": 24})); ex(&mut s, "variable.create", json!({"collection": "Type", "name": "face", "type": "string", "value": "Bold"})); - ex(&mut s, "style.create", json!({"type": "text", "name": "Body", "value": {"fontFamily": "Inter", "fontSize": 12, "lineHeight": "150%"}})); + ex( + &mut s, + "style.create", + json!({"type": "text", "name": "Body", "value": {"fontFamily": "Inter", "fontSize": 12, "lineHeight": "150%", "paragraphSpacing": 8, "listStyle": "bulleted"}}), + ); for (field, v) in [("fontSize", "size"), ("lineHeight", "lh"), ("fontStyle", "face")] { ex(&mut s, "style.bind", json!({"style": "Body", "field": field, "variable": v})); } @@ -340,6 +379,11 @@ fn variables_export_carries_text_styles_with_their_bindings() { assert_eq!(styles[0]["name"], "Body"); assert_eq!(styles[0]["style"]["font_size"], 16.0); assert_eq!(styles[0]["style"]["font_style"], "Bold"); + assert_eq!(styles[0]["paragraph"]["paragraph_spacing"], 8.0, "{file}"); + assert_eq!(styles[0]["paragraph"]["list"], "bulleted", "{file}"); + let mut keys: Vec<&str> = styles[0].as_object().unwrap().keys().map(String::as_str).collect(); + keys.sort_unstable(); + assert_eq!(keys, ["bound", "description", "id", "name", "paragraph", "style", "type"], "the entry's shape is public: {file}"); assert_eq!(styles[0], ex(&mut s, "style.list", json!({"type": "text"}))[0], "what style.list returns"); for field in ["fontSize", "lineHeight", "fontStyle"] { let id = styles[0]["bound"][field].as_str().unwrap(); @@ -355,19 +399,31 @@ fn text_styles_round_trip_through_variables_import() { let out = ex(&mut s, "variable.export", json!({})); let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap(); let mut t = Session::new(); + ex(&mut t, "variable.createCollection", json!({"name": "Type", "modes": ["Base"]})); + for (name, v) in [("gap", 4), ("pad", 6), ("lh", 30)] { + ex(&mut t, "variable.create", json!({"collection": "Type", "name": name, "type": "number", "value": v})); + } let r = ex(&mut t, "variable.import", json!({"variables": file})); assert_eq!(r["styles"], json!({"added": 1, "updated": 0}), "{r}"); + assert!(r["warnings"].as_array().unwrap().is_empty(), "{r}"); let doc = t.doc().unwrap(); let body = doc.styles.iter().find(|x| x.name == "Body").unwrap(); let ids: Vec<&str> = body.bound.values().map(|v| v.as_str()).collect(); assert_eq!(body.bound.len(), 3, "{body:?}"); assert!(ids.iter().all(|i| doc.variables.get(i).is_some()), "bindings point at this file's variables"); + for (field, name) in [("fontSize", "size"), ("lineHeight", "lh"), ("fontStyle", "face")] { + assert_eq!(doc.variables.get(&body.bound[field]).unwrap().name, name, "{field}"); + } + let StyleKind::Text { paragraph, .. } = &body.kind else { panic!("{body:?}") }; + assert_eq!((paragraph.paragraph_spacing, paragraph.list), (8.0, ListStyle::Bulleted)); let StyleKind::Text { style, .. } = &body.kind else { panic!("{body:?}") }; assert_eq!((style.font_style.as_str(), style.font_size), ("Bold", 16.0)); // Again: the style is updated, not duplicated. let r = ex(&mut t, "variable.import", json!({"variables": file})); assert_eq!(r["styles"], json!({"added": 0, "updated": 1}), "{r}"); assert_eq!(t.doc().unwrap().styles.len(), 1); + assert!(r["warnings"].as_array().unwrap().is_empty(), "{r}"); + assert_eq!(t.doc().unwrap().styles[0].bound.len(), 3); // A binding to a variable the JSON lacks is dropped with a warning naming the style. let mut u = Session::new(); let mut lone = file.clone(); @@ -378,6 +434,22 @@ fn text_styles_round_trip_through_variables_import() { assert!(r["warnings"].to_string().contains("Body"), "{r}"); } +#[test] +fn a_files_own_export_leaves_its_text_styles_alone() { + let mut s = body_session(); + ex(&mut s, "style.create", json!({"type": "text", "name": "Body", "value": {"fontFamily": "Inter", "fontSize": 20}})); + ex(&mut s, "variable.createCollection", json!({"name": "Other", "modes": ["Base"]})); + ex(&mut s, "variable.create", json!({"collection": "Other", "name": "o", "type": "number", "value": 1})); + let out = ex(&mut s, "variable.export", json!({"collections": ["Other"]})); + let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap(); + let before = s.doc().unwrap().styles.clone(); + assert_eq!(before.len(), 2); + let r = ex(&mut s, "variable.import", json!({"variables": file})); + assert_eq!(s.doc().unwrap().styles, before, "{r}"); + assert_eq!(r["styles"], json!({"added": 0, "updated": 2}), "{r}"); + assert!(!r["warnings"].to_string().contains("left unbound"), "{r}"); +} + #[test] fn variables_import_caps_the_file_it_reads() { let dir = std::env::temp_dir().join(format!("figcraft-vars-io-cap-{}", std::process::id())); diff --git a/docs/components-parity.md b/docs/components-parity.md index 726fabeed..879dd7e31 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-10 · **Change:** minor (the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); 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/file-format-parity.md b/docs/file-format-parity.md index 5031f1151..e0fc1c4c4 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-08 · **Change:** minor (`.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-10 · **Change:** minor (the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); `.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 diff --git a/docs/gaps.md b/docs/gaps.md index f31c41183..f60e83afe 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-10-31 · **Change:** minor (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-10 · **Change:** minor (the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); 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 diff --git a/docs/mcp.md b/docs/mcp.md index 3f19b8379..2b548b704 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1232,13 +1232,13 @@ Dart constants for Flutter (`format: "dart"`: an `abstract final class` per coll default mode's named after the collection and the others after the collection and the mode, with a `static const` `Color`, `double`, `String` or `bool` per variable; names become camelCase Dart identifiers kept apart, aliases are resolved to their value in that mode), and -returns `{text}` (or writes `path` and returns `{path}`). The JSON format also carries a top-level `textStyles` array beside `meta`, a FigCraft extension (the REST `styles` metadata has no values): each entry is what `style.list {type: "text"}` returns (`name`, `style`, `paragraph`, and `bound` holding the same variable ids `meta.variables` is keyed by); CSS, Tailwind and Dart are variables only. `variable.import {variables}` (an object, +returns `{text}` (or writes `path` and returns `{path}`). The JSON format also carries a top-level `textStyles` array beside `meta`, a FigCraft extension (the REST `styles` metadata has no values): each entry is what `style.list {type: "text"}` returns (`name`, `style`, `paragraph`, and `bound` holding the ids `meta.variables` is keyed by, which it holds only for the variables of the exported local collections, so a file's own export with `collections` left out of it names variables its `meta` lacks, and an import keeps such a binding on the style it replaces; an entry's `style` keys are snake_case and its `bound` keys camelCase, `bound.fontSize` binding `style.font_size`); CSS, Tailwind and Dart are variables only. `variable.import {variables}` (an object, JSON text or a path to a regular file of at most 256 MiB; `variableCollections` and `variables` under `meta` or at the top level) reads one back: a collection joins this file's collection of the same name (values matched by mode name, new modes and variables added, a same-named variable of another type skipped with a warning; library copies and extended collections are never targets), others are -added; aliases are checked for loops; a `textStyles` array is read too (a style joins this file's text style of the same name, others are added; bindings follow the imported variables, one to a variable the JSON lacks is dropped with a warning); it returns `{collections, variables, updated, styles: {added, updated}, warnings}`, +added; aliases are checked for loops; a `textStyles` array is read too (a style joins this file's text style of the same name, others are added; bindings follow the imported variables; one to a variable the JSON lacks (unless the style it replaces already holds that id), to a field the style lacks or to a variable of another type is dropped with a warning; at most 10,000 styles and 32 bindings each are read); it returns `{collections, variables, updated, styles: {added, updated}, warnings}`, with a warning when the JSON holds no variables (`no variables found: expected meta.variables …`) or fewer than its collections list in `variableIds`. The Variables editor's Import… and Export… buttons do the same through file dialogs. From 81c3cc6369b0f738efb5a0708745fdcc3c5da1e9 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 10 Nov 2026 15:37:27 -0500 Subject: [PATCH 08/48] M7: Docs: who reads textStyles, the kept binding, filtered exports (#2173) The file-format row says only variable.import reads textStyles (file.open and file.import read the variables but not the text styles). The ROADMAP row says a binding is kept without a warning when the existing style already holds that variable, and that an export filtered by collections can name variables meta.variables doesn't include, as docs/mcp.md already does. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- ROADMAP.md | 2 +- docs/file-format-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 0a7ca6c78..953aca9ba 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -365,7 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| -| 2026-11-10 | minor | M7, #2173: `variable.export {format: "json"}` writes a top-level `textStyles` array beside `meta` (each text style as `style.list {type: "text"}` returns it, `bound` holding the ids `meta.variables` is keyed by), and `variable.import` reads it back (styles merged by name, bindings re-pointed, a binding to a variable the JSON lacks dropped with a warning). A FigCraft extension: the REST `styles` metadata has no values. CSS, Tailwind and Dart stay variables-only | +| 2026-11-10 | minor | M7, #2173: `variable.export {format: "json"}` writes a top-level `textStyles` array beside `meta` (each text style as `style.list {type: "text"}` returns it; `bound` holds the ids `meta.variables` is keyed by for variables of the exported collections, so an export filtered by `collections` can name variables it doesn't include), and `variable.import` reads it back (styles merged by name, bindings re-pointed; a binding to a variable the JSON lacks is kept without a warning when the existing style already holds that same variable, and otherwise dropped with a warning). A FigCraft extension: the REST `styles` metadata has no values. CSS, Tailwind and Dart stay variables-only | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged | | 2026-11-06 | patch | M1, #2028: Edit ▸ Set default properties gives new rectangles, ellipses, polygons and stars drawn with the tools (and, set from a text layer, new text) the selected layer's properties; it only copied them for Paste properties. Tests: `default_props_tests` (3). Numbers unchanged | | 2026-11-06 | patch | M5, #2027: `proto.settings` refuses an unknown device name with the list of devices (it saved any string, and the presenter showed no device), takes known names in any case, and answers the page's prototype settings, so `proto.settings {}` reads them back over MCP. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back`. Numbers unchanged | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index e0fc1c4c4..8b9b3bdab 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -22,7 +22,7 @@ and prototype interactions are still unchecked there. | `.sketch` (Sketch 48 and newer) | import (file browser ▸ Import or drop, desktop app too; converted to a Figma file, symbols as components; per the help center) | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP; Open With from Finder, Explorer and Linux file managers once installed; recent files show its `previews/preview.png`) | no (out of scope) | zip + JSON read from the public format description; Sketch 43–47 (text as binary property lists) and older (SQLite) files are refused with a message to resave them in a newer Sketch. Pages, artboards as frames with their background, groups; Sketch 2025 and newer: frames (clipping or not) with their style, graphics, stacks as auto layout (direction, gap, alignment, padding, wrap, hug/fill sizing, stretching filling every item across, items ignoring the stack), corners in the style (rounded, smooth with its smoothing; angled, inside square and inside arc as paths), pins and sizing, per-side borders, lists of blurs (progressive background blurs, glass), inner shadows in the shadow list, tints (a graphic's, group's or instance's fill colouring its layers, and colour overrides; from Sketch 64, before which a group's fill draws nothing), text colour and visibility overrides, text sized by its sizing; rectangles with corner radii, ovals, stars and polygons while their points are the generated ones, paths as editable vector networks, shape groups as their shape, as one compound path (children without an operation, by the group's winding rule) or as boolean operations (mixed operations nested from the left); operands' own borders ignored as Sketch does; open paths filled as if closed, edited ovals and rectangles as paths, bitmaps (their image under their style's fills; colour adjustments as image filters with Sketch's tone curve, contrast and then brightness added), slices, hotspots; transforms (rotation, flips after it), resizing constraints; fills (solid, gradients with Sketch's geometry, gradients mixed in OKLab or OKLCH as sRGB stops along the same colours, image patterns), borders (the first enabled border's width and position), shadows, inner shadows, layer, motion and background blurs (Sketch's radius is the standard deviation), opacity and blend modes; clipping masks (an outline mask that shows its own style draws a copy under itself, as Sketch does, and its opacity fades it and what it clips together; alpha masks only mask; broken mask chains wrapped), progressive opacity (Fade) as an alpha mask of its gradient; text with styled runs (UTF-16 ranges), paragraph and vertical alignment, lines placed by Sketch's line spacing behaviour, box sizing, fonts found by their PostScript names among the installed ones (else the family read from the name), variable font axes, Sketch's natural line (ascent and descent rounded, no line gap, a fifth more for classic Mac fonts) for text without a fixed line height; symbols as components (library copies on a page of their own) and instances carrying their masters' layers with overrides (text, nested swaps and hiding, images, also on shapes' image fills, layer and text styles, nested paths), clipping only where the master clips (`clippingBehavior` 1), laid out for their size the way Sketch does it (proportional sharing per pins from format 110, scaling before) and still live; master backgrounds in instances only when the master includes them in both instances and exports, as on Sketch's canvas and renders; Apple's system fonts found under the names designs use, with the platform's tracking kept as letter spacing; shared layer styles as paint (fills, border colours) and effect styles, shared text styles as text styles; Color Variables (also library ones) as colour variables with bindings; prototype links, flow starts, export options, layout and square grids (hidden, as Sketch shows them only in its layout view). Instances of a stack laid out at their size and texts an override changed measured again on open, an auto-width one growing from its aligned edge. Warnings: noise fills, OKLab and OKLCH gradients, motion and zoom blurs (drawn as plain blurs), fonts embedded with their data (not used), Smart Layout (kept as laid out), locked overrides, scaled instances. Tested on fixtures built in code (`crates/format/src/sketch/*_tests.rs`, fuzzed) and locally (`FIGCRAFT_SKETCH_SAMPLES`) on one real Sketch 50 file and the public Apache-2.0 IBM Carbon Design Kit saved by Sketch 68 and 83 (70,000 layers open in ~3 s, debug build; its edition saved by Sketch 47 is refused, as it should be); compared artboard by artboard with Sketch 2026's own renders (`FIGCRAFT_SKETCHTOOL`, black-box): the Sketch 50 file's 73 artboards differ in at most 2.3% of their pixels (0.8% on average) (text metrics, fonts FigCraft doesn't find, antialiasing), Carbon 11's 69 1.1% on average and at most 4.4% (text in IBM Plex, which the file embeds and FigCraft doesn't use yet), a Sketch 64 file's 65 artboards 2.1% on average, a Sketch 2026 showcase file's 16 frames 0.9% on average (at most 1.9%); the rules for master backgrounds, symbol clipping, mask opacity, bitmap fills, image overrides, stretching stacks, blur radii, colour adjustments, gradient interpolation and text growth checked against Sketch's renders of files built for each case (black-box, synthetic) | 5–10 (Smart Layout as auto layout, motion and zoom blurs, several borders of different widths; fonts embedded in the file once `.figcraft` documents can carry fonts: until then they would only last the session). Known limitations: a plain group (not a frame) that fills a stack keeps its layers' size where Sketch stretches them; a font Sketch can't find draws in the installed family's own weight (Sketch falls back to a regular face); text in the system SF Pro comes out a few percent narrower than Sketch's; macOS's reserved system fonts (PingFang) aren't found; brightness past about +0.4 is approximated (image filters can't add); OKLab gradients become sRGB stops (FigCraft gradients mix in sRGB) | | `.jam` (whiteboards) | native to FigJam | **yes, best effort** (`file.open`, `file.import`, File ▸ Open, drop, CLI, MCP) | no | the same archive as a `.fig` (its canvas header reads `fig-jam.`) through the same reader (#1342): it opens as a board (the file kind; a `.fig` stays a design file), with generated sticky and shape backgrounds and text kept (#1341) as ordinary layers rather than native board objects (see [boards-parity](boards-parity.md)); tables, stamps, code blocks and the like come in as frames with their text and connectors as vectors (an elbowed connector keeps the path it was saved with, #1910), with an import note; a layer type the reader doesn't know is left out with a note naming it; writing `.jam` is not supported | — | | `.deck` (Slides) | native to other Figma products | no | no | out of scope | — | -| REST API file JSON (`GET /v1/files/:key`) + local variables JSON (+ a FigCraft `textStyles` array on export and import) + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints, strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings, image adjustments (the same tint sign as `.fig`); the import report after opening; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — | +| REST API file JSON (`GET /v1/files/:key`) + local variables JSON (+ a FigCraft `textStyles` array, written by `variable.export` and read only by `variable.import`: `file.open` and `file.import` read the variables but not `textStyles`) + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints, strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings, image adjustments (the same tint sign as `.fig`); the import report after opening; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — | | `.figcraft` (ours: zip of `document.json` + images, versions inside) | — | yes | yes | streamed JSON, 50k layers save ~0.09 s / load ~0.16 s (`cargo xtask bench`); old files keep opening (`large_tests.rs`); image members are `images/`, and a key that can't be one — path text, a space, over 128 chars — is left out with a complaint instead of loaded (`image_tests`); saves write a unique staging file and rename it into place (#284); optional auto-save of files with a path (`pref.autoSave`, #305); Save and auto-save refuse to write over a file another app (figcraft-cli, say) changed since it was opened or saved here, judged by its size and modification time: Revert to saved loads those changes, Save as keeps both, `file.save {overwrite: true}` replaces them (#1330); `kind: "board"` marks a board (left out for design files, so files from before boards are design files; the home screen reads it for the file's mark); board objects keep their `board` metadata on the layer; Developer Mode measurements are kept on the layer they start from (`measurements: [{to} | {side}]`, left out when there are none, so older files open with none) | — | | Local library files | team libraries in the cloud | yes (enable a `.figcraft` as a library) | yes (publish) | per-asset versions, updates with overrides kept | see [collaboration-parity](collaboration-parity.md) | From 737df567a32e0736f1472097af4eeab5a66a62c9 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 10 Nov 2026 16:41:17 -0500 Subject: [PATCH 09/48] M7: Variables JSON import: a re-imported style keeps its identity (#2173) Two text styles sharing a name and reordered after the export swapped their values on re-import, because each entry took the first untouched style of its name. An entry now takes the local text style with its exported id and name first, and falls back to the name, so a file's own export round-trips and another file's still matches by name. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- crates/engine/src/cmd/styles.rs | 12 ++++++++---- crates/engine/src/cmd/variables_io.rs | 3 ++- crates/engine/src/variables_io_tests.rs | 14 ++++++++++++++ 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index a61f4f18c..76c953bc6 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -264,11 +264,14 @@ fn text_kind(cmd: &str, style: &Value, paragraph: &Value) -> Result { /// Make or redefine this file's text style `name` from JSON (see [`text_kind`]). `bind` gives its /// variable bindings from the document, the new value and the style it replaces. The style -/// redefined is the first local text style of that name not in `touched`. True when one existed -/// (with the style's id); the caller settles and propagates. +/// redefined is the local text style of that name with the exported `id` (so a file re-importing +/// its own export keeps each style's identity when two share a name), else the first of that +/// name; never one in `touched`. True when one existed (with the style's id); the caller settles +/// and propagates. pub(crate) fn upsert_text_style( doc: &mut Document, name: &str, + id: Option<&str>, description: &str, style: &Value, paragraph: &Value, @@ -276,9 +279,10 @@ pub(crate) fn upsert_text_style( bind: impl FnOnce(&Document, &StyleKind, Option<&Style>) -> BTreeMap, ) -> Result<(StyleId, bool)> { let kind = text_kind("variable.import", style, paragraph)?; - let same = doc.styles.iter().position(|x| { + let eligible = |x: &Style| { x.name == name && matches!(x.kind, StyleKind::Text { .. }) && !crate::library::is_remote_style(doc, &x.id) && !touched.contains(&x.id) - }); + }; + let same = id.and_then(|id| doc.styles.iter().position(|x| x.id == id && eligible(x))).or_else(|| doc.styles.iter().position(&eligible)); let updated = same.is_some(); let bound = bind(doc, &kind, same.and_then(|i| doc.styles.get(i))); let mut st = match same.and_then(|i| doc.styles.get(i)) { diff --git a/crates/engine/src/cmd/variables_io.rs b/crates/engine/src/cmd/variables_io.rs index 5816ea44b..93133edba 100644 --- a/crates/engine/src/cmd/variables_io.rs +++ b/crates/engine/src/cmd/variables_io.rs @@ -104,7 +104,8 @@ fn import_text_styles(doc: &mut Document, entries: &Value, ids: &BTreeMap| { text_style_bindings(&name, wanted, ids, doc, kind, current, warnings) }; - match super::styles::upsert_text_style(doc, &name, &description, style, e.get("paragraph").unwrap_or(&Value::Null), &touched, bind) { + let id = e.get("id").and_then(Value::as_str); + match super::styles::upsert_text_style(doc, &name, id, &description, style, e.get("paragraph").unwrap_or(&Value::Null), &touched, bind) { Ok((sid, was)) => { touched.push(sid); if was { diff --git a/crates/engine/src/variables_io_tests.rs b/crates/engine/src/variables_io_tests.rs index 5ac6654a3..2225f12a3 100644 --- a/crates/engine/src/variables_io_tests.rs +++ b/crates/engine/src/variables_io_tests.rs @@ -450,6 +450,20 @@ fn a_files_own_export_leaves_its_text_styles_alone() { assert!(!r["warnings"].to_string().contains("left unbound"), "{r}"); } +/// Two text styles share a name and are reordered after the export: re-importing it gives each +/// style its own values back (matched by the exported id), not its namesake's. +#[test] +fn a_files_own_export_keeps_each_same_named_style_after_a_reorder() { + let mut s = body_session(); + ex(&mut s, "style.create", json!({"type": "text", "name": "Body", "value": {"fontFamily": "Inter", "fontSize": 20}})); + let out = ex(&mut s, "variable.export", json!({})); + let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap(); + s.doc_mut().unwrap().styles.reverse(); + let before = s.doc().unwrap().styles.clone(); + let r = ex(&mut s, "variable.import", json!({"variables": file})); + assert_eq!(s.doc().unwrap().styles, before, "{r}"); +} + #[test] fn variables_import_caps_the_file_it_reads() { let dir = std::env::temp_dir().join(format!("figcraft-vars-io-cap-{}", std::process::id())); From fa5938e6493525c81a21f178b94f33a1b3c4fb3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B6=E6=9E=97=E6=A9=A6?= <108113065+yelintong@users.noreply.github.com> Date: Wed, 11 Nov 2026 09:19:24 +0800 Subject: [PATCH 10/48] M6: .fig export writes slot properties and instance slot content The .fig exporter refused to write SLOT component properties: prop_type returned None for Slot, prop_def skipped it and prop_ref warned that slot layers were written as plain layers. Instances never wrote a SLOT_CONTENT_ID assignment and no private slot content frame was emitted, so a round trip through our own importer dropped every slot definition and replaced each instance's own slot content with the main's default. A second, quieter bug cleared every property binding on expanded instance layers: changed(mine, theirs) saw no parameterConsumptionMap on a layer whose main owns it and wrote an explicit "unset" row, which the importer read back as clearing the main's SLOT_CONTENT_ID / TEXT_DATA / VISIBLE references. Instance rows now inherit the main's binding fields for the diff. - SCHEMA carries SLOT with the format's real field ids (ComponentPropType SLOT=7, SLOT_CONTENT_ID 40/4/18/12, VariableAnyValue.slotContentIdValue=18, NodeChange.isSlotContent=495), so other readers name the same fields. - SLOT definitions, the main frame's SLOT_CONTENT_ID reference and each instance's slot assignment are written. - An instance whose slot content is its own gets a private isSlotContent frame on the hidden page with its layers below it; unassigned slots keep the main's default content. Variant copies of a set's slot property round trip too. New fig::export_slot_tests covers the written message, full round trips, synced instances whose layers keep no references, default content and set variants. docs/file-format-parity.md moves slot export out of "Left out". Numbers unchanged. --- crates/format/src/fig.rs | 2 + crates/format/src/fig/export.rs | 49 +++- crates/format/src/fig/export/assets.rs | 67 +++++- crates/format/src/fig/export/common.rs | 3 +- crates/format/src/fig/export/component.rs | 49 +++- crates/format/src/fig/export/layer.rs | 7 +- crates/format/src/fig/export_slot_tests.rs | 265 +++++++++++++++++++++ docs/file-format-parity.md | 21 +- 8 files changed, 432 insertions(+), 31 deletions(-) create mode 100644 crates/format/src/fig/export_slot_tests.rs diff --git a/crates/format/src/fig.rs b/crates/format/src/fig.rs index f7547c3d0..e29314e99 100644 --- a/crates/format/src/fig.rs +++ b/crates/format/src/fig.rs @@ -23,6 +23,8 @@ mod deep_import_tests; mod expansion_cost_tests; mod export; #[cfg(test)] +mod export_slot_tests; +#[cfg(test)] mod export_tests; #[cfg(test)] mod interop_tests; diff --git a/crates/format/src/fig/export.rs b/crates/format/src/fig/export.rs index f00de3606..487221016 100644 --- a/crates/format/src/fig/export.rs +++ b/crates/format/src/fig/export.rs @@ -14,7 +14,7 @@ //! through our own importer are tested, and written files were opened in other software //! (`docs/file-format-parity.md` says what was checked); other apps may not open every file. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::io::Write; use std::sync::Arc; @@ -104,7 +104,7 @@ enum SourceDirectionality AUTO=0 LTR=1 RTL=2 enum DocumentColorProfile LEGACY=0 SRGB=1 DISPLAY_P3=2 enum EmojiImageSet APPLE=0 NOTO=1 enum MaskType ALPHA=0 OUTLINE=1 LUMINANCE=2 -enum VariableResolvedDataType BOOLEAN=0 FLOAT=1 STRING=2 COLOR=4 SYMBOL_ID=6 TEXT_DATA=8 +enum VariableResolvedDataType BOOLEAN=0 FLOAT=1 STRING=2 COLOR=4 SYMBOL_ID=6 TEXT_DATA=8 SLOT_CONTENT_ID=12 enum VectorMirror NONE=0 ANGLE=1 ANGLE_AND_LENGTH=2 enum BooleanOperation UNION=0 INTERSECT=1 SUBTRACT=2 XOR=3 enum LayoutGridType MIN=0 CENTER=1 STRETCH=2 MAX=3 @@ -112,9 +112,9 @@ enum LayoutGridPattern STRIPES=0 GRID=1 enum Axis X=0 Y=1 enum ImageType PNG=0 JPEG=1 SVG=2 PDF=3 enum ExportConstraintType CONTENT_SCALE=0 CONTENT_WIDTH=1 CONTENT_HEIGHT=2 -enum ComponentPropType BOOL=0 TEXT=1 INSTANCE_SWAP=3 VARIANT=4 -enum VariableField MISSING=0 CORNER_RADIUS=1 PARAGRAPH_SPACING=2 PARAGRAPH_INDENT=3 STROKE_WEIGHT=4 STACK_SPACING=5 STACK_PADDING_LEFT=6 STACK_PADDING_TOP=7 STACK_PADDING_RIGHT=8 STACK_PADDING_BOTTOM=9 VISIBLE=10 TEXT_DATA=11 WIDTH=12 HEIGHT=13 RECTANGLE_TOP_LEFT_CORNER_RADIUS=14 RECTANGLE_TOP_RIGHT_CORNER_RADIUS=15 RECTANGLE_BOTTOM_LEFT_CORNER_RADIUS=16 RECTANGLE_BOTTOM_RIGHT_CORNER_RADIUS=17 BORDER_TOP_WEIGHT=18 BORDER_BOTTOM_WEIGHT=19 BORDER_LEFT_WEIGHT=20 BORDER_RIGHT_WEIGHT=21 STACK_COUNTER_SPACING=23 MIN_WIDTH=24 MAX_WIDTH=25 MIN_HEIGHT=26 MAX_HEIGHT=27 FONT_FAMILY=28 FONT_STYLE=29 OPACITY=31 FONT_SIZE=32 LETTER_SPACING=34 LINE_HEIGHT=36 OVERRIDDEN_SYMBOL_ID=37 -enum VariableDataType BOOLEAN=0 FLOAT=1 STRING=2 ALIAS=3 COLOR=4 SYMBOL_ID=7 TEXT_DATA=9 PROP_REF=13 +enum ComponentPropType BOOL=0 TEXT=1 INSTANCE_SWAP=3 VARIANT=4 SLOT=7 +enum VariableField MISSING=0 CORNER_RADIUS=1 PARAGRAPH_SPACING=2 PARAGRAPH_INDENT=3 STROKE_WEIGHT=4 STACK_SPACING=5 STACK_PADDING_LEFT=6 STACK_PADDING_TOP=7 STACK_PADDING_RIGHT=8 STACK_PADDING_BOTTOM=9 VISIBLE=10 TEXT_DATA=11 WIDTH=12 HEIGHT=13 RECTANGLE_TOP_LEFT_CORNER_RADIUS=14 RECTANGLE_TOP_RIGHT_CORNER_RADIUS=15 RECTANGLE_BOTTOM_LEFT_CORNER_RADIUS=16 RECTANGLE_BOTTOM_RIGHT_CORNER_RADIUS=17 BORDER_TOP_WEIGHT=18 BORDER_BOTTOM_WEIGHT=19 BORDER_LEFT_WEIGHT=20 BORDER_RIGHT_WEIGHT=21 STACK_COUNTER_SPACING=23 MIN_WIDTH=24 MAX_WIDTH=25 MIN_HEIGHT=26 MAX_HEIGHT=27 FONT_FAMILY=28 FONT_STYLE=29 OPACITY=31 FONT_SIZE=32 LETTER_SPACING=34 LINE_HEIGHT=36 OVERRIDDEN_SYMBOL_ID=37 SLOT_CONTENT_ID=40 +enum VariableDataType BOOLEAN=0 FLOAT=1 STRING=2 ALIAS=3 COLOR=4 SYMBOL_ID=7 TEXT_DATA=9 PROP_REF=13 SLOT_CONTENT_ID=18 enum VariableScope ALL_SCOPES=0 TEXT_CONTENT=1 CORNER_RADIUS=2 WIDTH_HEIGHT=3 GAP=4 ALL_FILLS=5 FRAME_FILL=6 SHAPE_FILL=7 TEXT_FILL=8 STROKE=9 STROKE_FLOAT=10 EFFECT_FLOAT=11 EFFECT_COLOR=12 OPACITY=13 FONT_STYLE=14 FONT_FAMILY=15 FONT_SIZE=16 LINE_HEIGHT=17 LETTER_SPACING=18 PARAGRAPH_SPACING=19 PARAGRAPH_INDENT=20 enum StyleType NONE=0 FILL=1 STROKE=2 TEXT=3 EFFECT=4 EXPORT=5 GRID=6 enum InteractionType ON_CLICK=0 DRAG=9 ON_HOVER=4 ON_PRESS=7 MOUSE_IN=2 MOUSE_OUT=3 MOUSE_DOWN=5 MOUSE_UP=6 AFTER_TIMEOUT=1 ON_KEY_DOWN=10 @@ -161,13 +161,14 @@ message ComponentPropValue bool boolValue=1, TextData textValue=2, GUID guidValu message ComponentPropPreferredValues string[] stringValues=1 message ComponentPropDef GUID id=1, string name=2, ComponentPropValue initialValue=3, string sortPosition=4, GUID parentPropDefId=5, ComponentPropType type=6, ComponentPropPreferredValues preferredValues=8, VariableData varValue=9 message ComponentPropAssignment GUID defID=1, ComponentPropValue value=2, VariableData varValue=3 -enum ComponentPropNodeField VISIBLE=0 TEXT_DATA=1 OVERRIDDEN_SYMBOL_ID=2 +enum ComponentPropNodeField VISIBLE=0 TEXT_DATA=1 OVERRIDDEN_SYMBOL_ID=2 SLOT_CONTENT_ID=4 message ComponentPropRef GUID defID=2, ComponentPropNodeField componentPropNodeField=4 message VariantPropSpec GUID propDefId=1, string value=2 message StateGroupPropertyValueOrder string property=1, string[] values=2 message PropRefValue GUID defId=1 message SymbolId GUID guid=1 -message VariableAnyValue bool boolValue=1, string textValue=2, float floatValue=3, VariableID alias=4, Color colorValue=5, SymbolId symbolIdValue=8, TextData textDataValue=10, PropRefValue propRefValue=13 +message SlotContentId GUID guid=1 +message VariableAnyValue bool boolValue=1, string textValue=2, float floatValue=3, VariableID alias=4, Color colorValue=5, SymbolId symbolIdValue=8, TextData textDataValue=10, PropRefValue propRefValue=13, SlotContentId slotContentIdValue=18 message VariableData VariableAnyValue value=1, VariableDataType dataType=2, VariableResolvedDataType resolvedDataType=3 message VariableDataMapEntry uint nodeField=1, VariableData variableData=2, VariableField variableField=3 message VariableDataMap VariableDataMapEntry[] entries=1 @@ -189,7 +190,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, 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, 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 +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, 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, 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, bool isSlotContent=495 struct Blob byte[] bytes message Message MessageType type=1, uint sessionID=2, NodeChange[] nodeChanges=4, Blob[] blobs=6 "; @@ -446,10 +447,31 @@ struct Overlay { background: Option, } +/// An instance's own slot content: a private `isSlotContent` frame on the hidden page, assigned +/// to the instance's SLOT property. Its layers are written below that frame instead of as +/// overrides of the main's layers. +#[derive(Clone)] +struct SlotContent { + /// Local id of the private frame's GUID (session [`LAYERS`]). + frame: u32, + /// The slot frame's own layers, in order. + content: Vec, + /// Local id of the SLOT definition's GUID (session [`AUX`]). + def: u32, +} + struct Exporter<'d> { doc: &'d Document, /// Layer → local id of its GUID (session [`LAYERS`]). ids: BTreeMap, + /// Highest local id handed out for a layer GUID, including private slot content. + next_layer: u32, + /// Slot frame of an instance whose content is its own → its private content frame. + slot_frames: BTreeMap, + /// Instance → the slot frames whose assignments it writes. + instance_slots: BTreeMap>, + /// Layers written as private slot content (not as overrides of their main). + private_layers: BTreeSet, nodes: Vec>, /// Blob bytes → index (identical blobs are written once). blobs: BTreeMap, u32>, @@ -499,6 +521,10 @@ impl<'d> Exporter<'d> { Self { doc, ids: BTreeMap::new(), + next_layer: 0, + slot_frames: BTreeMap::new(), + instance_slots: BTreeMap::new(), + private_layers: BTreeSet::new(), nodes: Vec::new(), blobs: BTreeMap::new(), blob_bytes: 0, @@ -530,6 +556,13 @@ impl<'d> Exporter<'d> { self.aux } + /// A fresh GUID for a layer written outside the document's tree (a private slot content frame + /// or one of the layers under it). `assign` hands out all of these before the asset nodes. + fn next_layer_local(&mut self) -> u32 { + self.next_layer = self.next_layer.saturating_add(1); + self.next_layer + } + fn guid_of(&self, id: NodeId) -> Option> { self.ids.get(&id).map(|l| guid(LAYERS, *l)) } diff --git a/crates/format/src/fig/export/assets.rs b/crates/format/src/fig/export/assets.rs index f1df1874d..16850dfdc 100644 --- a/crates/format/src/fig/export/assets.rs +++ b/crates/format/src/fig/export/assets.rs @@ -1,7 +1,7 @@ use super::common::{layout_grid, node_field, prop_type, resolved_type, scope_name, variant_pairs}; use super::{ - AUX, Action, Affine, Bound, Color, Exporter, Fields, Kv, LAYERS, MAX_NODES, Node, NodeId, NodeKind, Overlay, OverlayPosition, Paint, StyleKind, - TextData, VariableValue, arr, b, color, e, fl, guid, matrix, o, position, root_fields, s, u, xy, + AUX, Action, Affine, Bound, Color, Exporter, Fields, Kv, LAYERS, MAX_NODES, Node, NodeId, NodeKind, Overlay, OverlayPosition, Paint, SlotContent, + StyleKind, TextData, VariableValue, arr, b, color, e, fl, guid, matrix, o, position, root_fields, s, u, xy, }; impl<'d> Exporter<'d> { @@ -73,8 +73,48 @@ impl<'d> Exporter<'d> { } } } - // The page that holds styles and variables takes the next id, then their nodes. - let mut next = u32::try_from(self.ids.len() + 1).unwrap_or(u32::MAX); + self.next_layer = u32::try_from(self.ids.len()).unwrap_or(u32::MAX); + // An instance's own slot content is a private frame on the hidden page, named by the + // instance's SLOT property assignment. Reserve GUIDs for that frame and for the layers + // written under it: an instance's layers otherwise have none, since its main's stand in. + let slot_frames: Vec = doc + .ids() + .filter(|id| { + doc.node(*id).is_some_and(|n| { + n.overrides.contains("slot") && n.source.and_then(|s| doc.node(s)).and_then(|s| s.prop_refs.get("slot")).is_some() + }) + }) + .collect(); + for id in slot_frames { + let Some(n) = doc.node(id) else { continue }; + let Some(prop) = n.source.and_then(|s| doc.node(s)).and_then(|s| s.prop_refs.get("slot")).cloned() else { continue }; + let Some(inst) = doc.ancestors(id).into_iter().find(|a| doc.node(*a).is_some_and(|x| matches!(x.kind, NodeKind::Instance { .. }))) else { + continue; + }; + let Some(NodeKind::Instance { component, .. }) = doc.node(inst).map(|x| &x.kind) else { continue }; + let Some(def) = self.def_for(*component, &prop, "SLOT") else { + self.warn("slot content without a matching slot property was left out"); + continue; + }; + let content: Vec = n.children.iter().copied().filter(|c| doc.node(*c).is_some_and(|x| x.source.is_none())).collect(); + let mut pending = content.clone(); + while let Some(c) = pending.pop() { + let Some(x) = doc.node(c) else { continue }; + // Mirrored layers come from a main and are not written as private content. + if x.source.is_some() || !self.private_layers.insert(c) { + continue; + } + let local = self.next_layer_local(); + self.ids.insert(c, local); + pending.extend(x.children.iter().copied()); + } + let frame = self.next_layer_local(); + self.slot_frames.insert(id, SlotContent { frame, content, def }); + self.instance_slots.entry(inst).or_default().push(id); + } + // The page that holds styles, variables and private slot content takes the next id; its + // nodes start one after that page's own GUID. + let mut next = self.next_layer.saturating_add(1); let mut node = || { next = next.saturating_add(1); next @@ -104,10 +144,10 @@ impl<'d> Exporter<'d> { /// collections and the variables, each a node of its own. pub(super) fn assets(&mut self, pages: usize) { let doc = self.doc; - if self.style_ids.is_empty() && self.set_ids.is_empty() { + if self.style_ids.is_empty() && self.set_ids.is_empty() && self.slot_frames.is_empty() { return; } - let page = u32::try_from(self.ids.len() + 1).unwrap_or(u32::MAX); + let page = self.next_layer.saturating_add(1); let mut f: Fields = vec![ ("guid", guid(LAYERS, page)), ("phase", e("CREATED")), @@ -258,6 +298,21 @@ impl<'d> Exporter<'d> { } self.nodes.push(o(f)); } + // Private slot content frames, one per instance slot whose content is its own. Their layers + // are ordinary layers below the frame, using the GUIDs reserved in `assign`. A reader takes + // the frame's children through the instance's SLOT assignment, never as page layers. + let slots: Vec<_> = self.slot_frames.clone().into_iter().collect(); + for (slot, info) in slots { + let mut f = head(info.frame, "FRAME", "Slot content"); + f.extend(root_fields()); + f.push(("isSlotContent", b(true))); + self.nodes.push(o(f)); + let parent = doc.node(slot); + let frame_guid = guid(LAYERS, info.frame); + for (i, c) in info.content.iter().enumerate() { + self.emit(*c, frame_guid.clone(), i, parent, 1); + } + } } /// A reference to variable `var` (a stored id: no name stands in for it, #1613) as variable data. diff --git a/crates/format/src/fig/export/common.rs b/crates/format/src/fig/export/common.rs index ee7293dc9..c9bc770b4 100644 --- a/crates/format/src/fig/export/common.rs +++ b/crates/format/src/fig/export/common.rs @@ -258,7 +258,8 @@ pub(super) fn prop_type(d: &PropDef) -> Option<&'static str> { PropDef::Boolean { .. } => Some("BOOL"), PropDef::Text { .. } => Some("TEXT"), PropDef::InstanceSwap { .. } => Some("INSTANCE_SWAP"), - PropDef::Variant { .. } | PropDef::Slot { .. } => None, + PropDef::Slot { .. } => Some("SLOT"), + PropDef::Variant { .. } => None, } } diff --git a/crates/format/src/fig/export/component.rs b/crates/format/src/fig/export/component.rs index f43e1d3ac..41935be11 100644 --- a/crates/format/src/fig/export/component.rs +++ b/crates/format/src/fig/export/component.rs @@ -3,7 +3,9 @@ use super::common::{ bool_data, changed, layout_grid, prop_type, resolved_alike, scaled, sort_position, symbol_data, text_data, text_value, var_data, variant_pairs, }; use super::scale::main_equal_lengths; -use super::{AUX, BTreeMap, Bound, Exporter, Fields, Kv, MAX_NODES, Node, NodeId, NodeKind, PropDef, StyleKind, Value, arr, b, e, fl, guid, o, s}; +use super::{ + AUX, BTreeMap, Bound, Exporter, Fields, Kv, LAYERS, MAX_NODES, Node, NodeId, NodeKind, PropDef, StyleKind, Value, arr, b, e, fl, guid, o, s, +}; /// A changed effect/grid style, and a payload only when it differs from that style's values. struct ListStyleOverride { @@ -47,7 +49,16 @@ impl<'d> Exporter<'d> { let main = self.guid_of(*default)?; (o(vec![("guidValue", main.clone())]), symbol_data(main)) } - PropDef::Variant { .. } | PropDef::Slot { .. } => return None, + // A slot has no scalar default: its content lives in a private frame assigned by each + // instance. `initialValue` and `varValue` stay empty, as readers of SLOT definitions do. + PropDef::Slot { preferred } => { + if !preferred.is_empty() { + self.warn("preferred components of slot properties were left out"); + } + (o(Vec::new()), o(Vec::new())) + } + // A variant's definitions are written on its set (`set_props`), not on the variant. + PropDef::Variant { .. } => return None, }; Some(o(vec![ ("id", guid(AUX, id)), @@ -134,6 +145,7 @@ impl<'d> Exporter<'d> { "visible" => ("VISIBLE", "BOOL", "BOOLEAN"), "characters" => ("TEXT_DATA", "TEXT", "TEXT_DATA"), "mainComponent" => ("OVERRIDDEN_SYMBOL_ID", "INSTANCE_SWAP", "SYMBOL_ID"), + "slot" => ("SLOT_CONTENT_ID", "SLOT", "SLOT_CONTENT_ID"), _ => { self.warn("slot layers were written as plain layers"); return None; @@ -189,6 +201,10 @@ impl<'d> Exporter<'d> { let mut seen = 0usize; while let Some((id, parent)) = stack.pop() { let Some(d) = doc.node(id) else { continue }; + // Layers written as private slot content are not overrides of the main's layers. + if self.private_layers.contains(&id) { + continue; + } seen += 1; if seen > MAX_NODES { break; @@ -203,6 +219,15 @@ impl<'d> Exporter<'d> { let (mut mine, mut theirs) = (Vec::new(), Vec::new()); self.layer(d, doc.node(parent), &mut mine, true); self.layer(src, src.parent.and_then(|p| doc.node(p)), &mut theirs, true); + // Property bindings belong to the main: an instance layer does not repeat them in the + // document. Inherit them for the diff, or `changed` writes an "unset" row for + // `parameterConsumptionMap` that clears the binding on import — including a slot's + // SLOT_CONTENT_ID reference, and with it the instance's own slot content. + for (k, v) in &theirs { + if matches!(*k, "parameterConsumptionMap" | "componentPropRefs") && !mine.iter().any(|(mk, _)| *mk == *k) { + mine.push((*k, v.clone())); + } + } // A nested instance swapped for another component. let swap = match (&d.kind, &src.kind) { (NodeKind::Instance { component, .. }, NodeKind::Instance { component: was, .. }) if component == was => None, @@ -298,10 +323,28 @@ impl<'d> Exporter<'d> { assignments.push(o(vec![("defID", guid(AUX, id)), ("value", value), ("varValue", var)])); } } + // A slot whose content is this instance's own names the private frame that holds it. The + // frame's GUID was reserved in `assign`; the importer resolves the property definition + // (a variant's copy included) and expands the frame's layers into the instance's slot. + for slot in self.instance_slots.get(&n.id).cloned().unwrap_or_default() { + let Some(info) = self.slot_frames.get(&slot) else { continue }; + assignments.push(o(vec![ + ("defID", guid(AUX, info.def)), + ("value", o(Vec::new())), + ( + "varValue", + o(vec![ + ("value", o(vec![("slotContentIdValue", o(vec![("guid", guid(LAYERS, info.frame))]))])), + ("dataType", e("SLOT_CONTENT_ID")), + ("resolvedDataType", e("SLOT_CONTENT_ID")), + ]), + ), + ])); + } if !assignments.is_empty() { f.push(("componentPropAssignments", arr(assignments))); } - if n.children.iter().filter_map(|c| doc.node(*c)).any(|c| c.source.is_none()) { + if n.children.iter().filter_map(|c| doc.node(*c)).any(|c| c.source.is_none() && !self.private_layers.contains(&c.id)) { self.warn("instance layers that don't come from their main component were left out"); } } diff --git a/crates/format/src/fig/export/layer.rs b/crates/format/src/fig/export/layer.rs index bebd09059..5db4d4196 100644 --- a/crates/format/src/fig/export/layer.rs +++ b/crates/format/src/fig/export/layer.rs @@ -1,8 +1,8 @@ use super::common::{export_setting, layout_grid, outlined, prop_type, variant_pairs}; use super::{ AUX, AutoLayout, BoolOp, Bound, ContentAlign, CrossAlign, Exporter, Fields, HConstraint, Kv, LAYERS, LayoutMode, MAX_DEPTH, MainAlign, MaskType, - Node, NodeId, NodeKind, PropDef, STASH, Sizing, TextData, TextStyle, VConstraint, WindingRule, arr, b, blend_name, color, e, fl, grid_sizing, - guid, int, matrix, o, position, root_fields, s, u, xy, + Node, NodeId, NodeKind, STASH, Sizing, TextData, TextStyle, VConstraint, WindingRule, arr, b, blend_name, color, e, fl, grid_sizing, guid, int, + matrix, o, position, root_fields, s, u, xy, }; impl<'d> Exporter<'d> { @@ -148,9 +148,6 @@ impl<'d> Exporter<'d> { f.push(("componentPropDefs", arr(defs))); } } - if props.values().any(|d| matches!(d, PropDef::Slot { .. })) { - self.warn("slot properties were left out"); - } if !description.is_empty() { f.push(("symbolDescription", s(description))); } diff --git a/crates/format/src/fig/export_slot_tests.rs b/crates/format/src/fig/export_slot_tests.rs new file mode 100644 index 000000000..72da737a4 --- /dev/null +++ b/crates/format/src/fig/export_slot_tests.rs @@ -0,0 +1,265 @@ +//! `.fig` export round trips of component properties, especially slots: the definitions on a +//! main, the property references on its layers, an instance's property values and the content its +//! slots hold. These are the fields a `.fig` written by the exporter is read back from. + +use std::collections::BTreeMap; + +use figcraft_doc::{Document, NodeId, NodeKind, PropDef, TextData}; +use serde_json::Value; + +use super::kiwi::Kv; +use super::{Archive, decode_canvas, export, import}; + +/// A copy of `src` below `parent`, linked back to it as an instance's expanded layer. +fn mirror(doc: &mut Document, src: NodeId, parent: NodeId) -> NodeId { + let mut n = doc.node(src).unwrap().clone(); + let kids = std::mem::take(&mut n.children); + n.id = doc.alloc_id(); + n.source = Some(src); + let id = doc.insert(n, parent, None).unwrap(); + for k in kids { + mirror(doc, k, id); + } + id +} + +/// A "Card" main with a text, a boolean and a slot property. Its slot has default content; the +/// instance overrides every property. With `own_slot`, it also puts its own content in the slot. +fn slots_document_with(own_slot: bool) -> Document { + let mut doc = Document::new("Slots"); + let page = doc.first_page().unwrap(); + let props = BTreeMap::from([ + ("Label".to_string(), PropDef::Text { default: "Title".into() }), + ("Visible".to_string(), PropDef::Boolean { default: true }), + ("Content".to_string(), PropDef::Slot { preferred: Vec::new() }), + ]); + let main = + doc.create(page, NodeKind::Component { description: String::new(), props, prop_order: Vec::new() }, "Card", 0.0, 0.0, 300.0, 160.0).unwrap(); + let label = doc.create(main, NodeKind::Text(TextData::new("Title")), "Label", 0.0, 0.0, 200.0, 20.0).unwrap(); + doc.node_mut(label).unwrap().prop_refs.insert("characters".into(), "Label".into()); + let slot = doc.create(main, NodeKind::Frame, "Content", 0.0, 30.0, 280.0, 100.0).unwrap(); + doc.node_mut(slot).unwrap().prop_refs.insert("slot".into(), "Content".into()); + doc.create(slot, NodeKind::Rectangle, "Default", 0.0, 0.0, 40.0, 20.0).unwrap(); + + let id = doc.alloc_id(); + let mut inst = doc.node(main).unwrap().clone(); + let inst_props = BTreeMap::from([("Label".to_string(), Value::String("Hi".into())), ("Visible".to_string(), Value::Bool(false))]); + (inst.id, inst.kind, inst.name, inst.parent, inst.source) = + (id, NodeKind::Instance { component: main, props: inst_props }, "Card".into(), None, None); + inst.children.clear(); + doc.insert(inst, page, None).unwrap(); + let mirrored: Vec<_> = doc.node(main).unwrap().children.clone(); + for k in mirrored { + let m = mirror(&mut doc, k, id); + let is_slot = doc.node(m).unwrap().prop_refs.contains_key("slot"); + let is_text = matches!(doc.node(m).unwrap().kind, NodeKind::Text(_)); + let n = doc.node_mut(m).unwrap(); + if is_text { + if let NodeKind::Text(td) = &mut n.kind { + td.characters = "Hi".into(); + } + n.overrides.insert("characters".into()); + } + // The slot keeps its own content instead of the main's default. + if own_slot && is_slot { + n.prop_refs.clear(); + n.overrides.insert("slot".into()); + n.children.clear(); + doc.create(m, NodeKind::Text(TextData::new("Own")), "Own", 0.0, 0.0, 100.0, 20.0).unwrap(); + } + } + doc +} + +fn slots_document() -> Document { + slots_document_with(true) +} + +fn names(doc: &Document, id: NodeId) -> Vec { + doc.node(id).unwrap().children.iter().map(|c| doc.node(*c).unwrap().name.clone()).collect() +} + +fn instance_slot(doc: &Document) -> &figcraft_doc::Node { + let inst = doc.nodes().find(|n| matches!(n.kind, NodeKind::Instance { .. })).unwrap(); + inst.children.iter().filter_map(|c| doc.node(*c)).find(|n| n.name == "Content").unwrap() +} + +/// A component set whose variants share a slot property, with an instance of the large variant +/// putting its own content in that slot. +fn set_slots_document() -> Document { + let mut doc = Document::new("Set slots"); + let page = doc.first_page().unwrap(); + let set = doc.create(page, NodeKind::ComponentSet { description: String::new() }, "Panel", 0.0, 0.0, 300.0, 100.0).unwrap(); + let mut variants = Vec::new(); + for (i, name) in ["Size=Small", "Size=Large"].into_iter().enumerate() { + let props = BTreeMap::from([("Content".to_string(), PropDef::Slot { preferred: Vec::new() })]); + let v = doc + .create(set, NodeKind::Component { description: String::new(), props, prop_order: Vec::new() }, name, 0.0, 60.0 * i as f64, 100.0, 100.0) + .unwrap(); + let slot = doc.create(v, NodeKind::Frame, "Content", 0.0, 0.0, 90.0, 60.0).unwrap(); + doc.node_mut(slot).unwrap().prop_refs.insert("slot".into(), "Content".into()); + variants.push(v); + } + let large = variants[1]; + let id = doc.alloc_id(); + let mut inst = doc.node(large).unwrap().clone(); + (inst.id, inst.kind, inst.name, inst.parent, inst.source) = + (id, NodeKind::Instance { component: large, props: BTreeMap::new() }, "Panel".into(), None, None); + inst.children.clear(); + doc.insert(inst, page, None).unwrap(); + for k in doc.node(large).unwrap().children.clone() { + mirror(&mut doc, k, id); + } + let slot = doc.node(id).unwrap().children[0]; + let n = doc.node_mut(slot).unwrap(); + n.prop_refs.clear(); + n.overrides.insert("slot".into()); + n.children.clear(); + doc.create(slot, NodeKind::Text(TextData::new("Mine")), "Mine", 0.0, 0.0, 80.0, 20.0).unwrap(); + doc +} + +/// The written message carries the SLOT definition, the main layer's SLOT_CONTENT_ID reference, +/// the instance's assignment and its private slot content frame — with the field ids of the real +/// format. No override row may unset the main's bindings. +#[test] +fn slot_fields_are_written_to_the_kiwi_message() { + let doc = slots_document(); + 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 changes = msg.get("nodeChanges").unwrap().list(); + + let main = changes.iter().find(|n| n.get("type").and_then(Kv::str) == Some("SYMBOL")).unwrap(); + let defs = main.get("componentPropDefs").unwrap().list(); + assert_eq!(defs.iter().filter(|d| d.get("type").and_then(Kv::str) == Some("SLOT")).count(), 1); + + let slot_frame = changes.iter().find(|n| n.get("name").and_then(Kv::str) == Some("Content")).unwrap(); + let entries = slot_frame.get("parameterConsumptionMap").unwrap().get("entries").unwrap().list(); + assert!(entries.iter().any(|e| e.get("variableField").and_then(Kv::str) == Some("SLOT_CONTENT_ID"))); + + let inst = changes.iter().find(|n| n.get("type").and_then(Kv::str) == Some("INSTANCE")).unwrap(); + let assignments = inst.get("componentPropAssignments").unwrap().list(); + assert!(assignments.iter().any(|a| a.get("varValue").and_then(|v| v.get("dataType")).and_then(Kv::str) == Some("SLOT_CONTENT_ID"))); + assert!(changes.iter().any(|n| n.get("isSlotContent").and_then(Kv::bool) == Some(true))); + + // An "unset" row for parameterConsumptionMap would clear the main's binding on import. + let overrides = inst.get("symbolData").unwrap().get("symbolOverrides").unwrap().list(); + assert!(!overrides.iter().any(|o| o.get("parameterConsumptionMap").is_some()), "instance rows must inherit the main's property bindings"); +} + +#[test] +fn component_properties_and_slot_content_round_trip() { + let doc = slots_document(); + let (bytes, warnings) = export(&doc, None).unwrap(); + let (back, _) = import(&bytes, "Slots").unwrap(); + + // The main keeps all three definitions, its text binding and its slot binding. + let main = back.nodes().find(|n| matches!(n.kind, NodeKind::Component { .. })).unwrap(); + let NodeKind::Component { props, .. } = &main.kind else { panic!("not a component") }; + assert_eq!(props.get("Label"), Some(&PropDef::Text { default: "Title".into() }), "{props:?}"); + assert_eq!(props.get("Visible"), Some(&PropDef::Boolean { default: true }), "{props:?}"); + assert!(matches!(props.get("Content"), Some(PropDef::Slot { .. })), "the slot definition came back: {props:?}"); + let main_slot = main.children.iter().filter_map(|c| back.node(*c)).find(|n| n.prop_refs.contains_key("slot")).unwrap(); + assert_eq!(main_slot.prop_refs.get("slot").map(String::as_str), Some("Content")); + assert_eq!(names(&back, main_slot.id), ["Default"]); + + // The instance's own values, its slot override and the content it holds. + let inst = back.nodes().find(|n| matches!(n.kind, NodeKind::Instance { .. })).unwrap(); + let NodeKind::Instance { props, .. } = &inst.kind else { panic!("not an instance") }; + assert_eq!(props.get("Label"), Some(&Value::String("Hi".into())), "{props:?}"); + assert_eq!(props.get("Visible"), Some(&Value::Bool(false)), "{props:?}"); + let slot = inst.children.iter().filter_map(|c| back.node(*c)).find(|n| n.overrides.contains("slot")).unwrap(); + assert_eq!(names(&back, slot.id), ["Own"], "the instance's slot content came back"); + assert!(!warnings.iter().any(|w| w.contains("slot")), "slots should be written, not warned about: {warnings:?}"); +} + +/// A synced instance keeps no property references on its expanded layers at all. The exporter +/// must not turn that into "unset" rows, which used to clear every binding (slots included). +#[test] +fn instance_layers_inherit_their_mains_property_bindings() { + let mut doc = slots_document(); + for id in doc.ids().collect::>() { + if let Some(n) = doc.node_mut(id) + && n.source.is_some() + { + n.prop_refs.clear(); + } + } + let (bytes, warnings) = export(&doc, None).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + let (back, _) = import(&bytes, "Slots").unwrap(); + + let labels: Vec<_> = back.nodes().filter(|n| n.name == "Label").collect(); + assert_eq!(labels.len(), 2, "the main's and the instance's label"); + assert!(labels.iter().all(|n| n.prop_refs.get("characters").map(String::as_str) == Some("Label")), "both keep the text binding"); + let inst = back.nodes().find(|n| matches!(n.kind, NodeKind::Instance { .. })).unwrap(); + let slot = inst.children.iter().filter_map(|c| back.node(*c)).find(|n| n.overrides.contains("slot")).unwrap(); + assert_eq!(names(&back, slot.id), ["Own"]); +} + +/// An instance that doesn't assign its slot keeps the main's default content: no private frame, +/// no assignment, and no override of the slot. +#[test] +fn unassigned_slot_keeps_the_mains_default_content() { + let doc = slots_document_with(false); + let (bytes, warnings) = export(&doc, None).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + 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 changes = msg.get("nodeChanges").unwrap().list(); + let inst = changes.iter().find(|n| n.get("type").and_then(Kv::str) == Some("INSTANCE")).unwrap(); + assert!( + !inst.get("componentPropAssignments").map(Kv::list).unwrap_or_default().iter().any(|a| a + .get("varValue") + .and_then(|v| v.get("dataType")) + .and_then(Kv::str) + == Some("SLOT_CONTENT_ID")) + ); + assert!(!changes.iter().any(|n| n.get("isSlotContent").and_then(Kv::bool) == Some(true))); + + let (back, _) = import(&bytes, "Slots").unwrap(); + let slot = instance_slot(&back); + assert!(!slot.overrides.contains("slot")); + assert_eq!(names(&back, slot.id), ["Default"]); +} + +/// Variants share their set's slot property: each variant's layer names its own copy of the +/// definition, and an instance of one variant still gets its own slot content. +#[test] +fn a_variants_slot_property_and_content_round_trip() { + let doc = set_slots_document(); + let (bytes, warnings) = export(&doc, None).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + let (back, _) = import(&bytes, "Set slots").unwrap(); + for name in ["Size=Small", "Size=Large"] { + let v = back.nodes().find(|n| n.name == name).unwrap(); + let NodeKind::Component { props, .. } = &v.kind else { panic!("{name} is a component") }; + assert!(matches!(props.get("Content"), Some(PropDef::Slot { .. })), "{name}: {props:?}"); + let slot = v.children.iter().filter_map(|c| back.node(*c)).find(|n| n.prop_refs.contains_key("slot")).unwrap(); + assert_eq!(slot.prop_refs.get("slot").map(String::as_str), Some("Content"), "{name}"); + } + let inst = back.nodes().find(|n| matches!(n.kind, NodeKind::Instance { .. })).unwrap(); + let slot = inst.children.iter().filter_map(|c| back.node(*c)).find(|n| n.overrides.contains("slot")).unwrap(); + assert_eq!(names(&back, slot.id), ["Mine"]); +} + +/// Preferred slot components have no public field in the format, so they are dropped — but not +/// silently: the exporter warns, the way it does for an instance swap's preferred values. +#[test] +fn preferred_slot_components_are_left_out_with_a_warning() { + const WARN: &str = "preferred components of slot properties were left out"; + let plain = slots_document(); + let (_, warnings) = export(&plain, None).unwrap(); + assert!(!warnings.iter().any(|w| w == WARN), "no preferred components: {warnings:?}"); + + let mut doc = slots_document(); + let main = doc.nodes().find(|n| matches!(n.kind, NodeKind::Component { .. })).unwrap().id; + let preferred = doc.alloc_id(); + let NodeKind::Component { props, .. } = &mut doc.node_mut(main).unwrap().kind else { panic!("not a component") }; + props.insert("Content".to_string(), PropDef::Slot { preferred: vec![preferred] }); + let (_, warnings) = export(&doc, None).unwrap(); + assert!(warnings.iter().any(|w| w == WARN), "preferred components were dropped without a warning: {warnings:?}"); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index dd04fdf75..fcfd65019 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-08 · **Change:** minor (`.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-11 · **Change:** minor (`.fig` export writes SLOT component properties, their layer references and each instance's own slot content, and no longer clears a main's property bindings with an "unset" override row; `.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 @@ -108,15 +108,17 @@ scales and empty-style clears; they have not been checked in other software. "Semi Bold" in Inter; size; line height, a share of the font size as a raw multiplier; letter spacing, case, decoration, links), alignment, auto resize, truncation, paragraph spacing and indent, list types and styled runs with their fills (indexed - by UTF-16 unit); components (description, boolean, text and instance swap properties and the - layers bound to them, with their values also as variable data), component sets (the set holds + by UTF-16 unit); components (description, boolean, text, instance swap and slot properties and + the layers bound to them, with their values also as variable data), component sets (the set holds the definitions, variant properties included with their values in order; each variant has its own copy of each definition and its variant values, and its layers and instances name that copy), instances (their main, property values, what the instance itself changes from its main, such as its size, name and paints, as an override addressed by the main's id, the fields its layers change, by id path, through nested instances and swaps, and what follows from those as derived data: each layer's size, place and outline and the colours its - variables give in the instance's mode; an instance scaled as a whole says its scale factor); + variables give in the instance's mode; an instance scaled as a whole says its scale factor; + a slot whose content is the instance's own names a private `isSlotContent` frame on the hidden + page, whose layers are written below it); variable collections with their modes and variables (colour, number, string and boolean values per mode, aliases, colour calculations as the colour they show in each mode, descriptions, scopes) as nodes on a hidden page, the variables bound to @@ -137,16 +139,18 @@ scales and empty-style clears; they have not been checked in other software. text (written as values), 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, prototype device settings, slot properties and slot content, brush + guides, prototype device settings, 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), image adjustments, glass settings other than frost, springs other than Gentle (written as ease out), set-variable, set-variable-mode and conditional actions, scroll-to offsets, text decoration looks, variable font axes, text on a path, nested list levels, list spacing, hanging punctuation, leading trim, OpenType features, per-layer operations inside boolean groups, different stroke ends - on lines, the Dash cap (no public name for it). Not written at all: stroke outlines of dashed and per-side strokes and of inside or - outside strokes on polygons, stars and vectors, glyph outlines of text (a reader lays text out - with its own fonts), version history and branches. + on lines, the Dash cap (no public name for it), preferred slot components (the editor keeps no + field for the components a slot suggests). Not written at all: slot insertion and child-count + settings (the editor keeps no fields for them), stroke outlines of dashed and per-side strokes and + of inside or outside strokes on polygons, stars and vectors, glyph outlines of text (a reader lays + text out with its own fonts), version history and branches. - **Checked by opening written files in other software:** the example documents and a small test file open there, and layers, fills, gradients, strokes, shadows, vectors, components and text draw as in FigCraft. A file saved again there and read back keeps the layer tree and properties; two @@ -196,6 +200,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | `.fig` export keeps component properties through a round trip: SLOT definitions, the `SLOT_CONTENT_ID` reference on a main's slot frame and an instance's slot assignment use the format's real field ids (7 / 40 / 4 / 18 / 12 / 18 / 495), and an instance's own slot content is written as a private `isSlotContent` frame on the hidden page. Property bindings belong to the main: instance override rows no longer write an "unset" `parameterConsumptionMap` for layers that simply do not repeat them, which used to clear every binding — slots included — on import. Synthetic round trips cover defaults, variants, synced instances and the written message (`fig::export_slot_tests`). Not checked in other software. Numbers unchanged | | 2026-11-08 | minor | M6, #2097 follow-up: per-point vector corner radii take the scale of the row supplying `vectorData`, including nested instance rows; override and derived rows are not scaled twice. Network caching distinguishes the instance scale even when resizing gives two vectors the same final box. Synthetic tests cover missing/unit factors, half/double scale, derived size alone, overridden and derived vector data, nested scale and equal-size cache separation. Layer-radius fallback remains the separate #2115 change. Numbers unchanged. | | 2026-11-08 | patch | #2097 / #2100: scaled-instance lengths reset to the unscaled main value survive export/import as explicit overrides. Dimensionless values and zero do not gain scale overrides. Exported factors stay within the importer's 0.001–1000 range; larger or smaller ratios use explicit values instead. Effect/grid payload rows above an inherited style link take precedence at their own scale, including nested instances and empty-list clears, without detaching styles. Synthetic regressions cover corners, dashes/shadows, layout/grids and bounds, typography and styled runs, linked text and nested styles. Numbers unchanged. | | 2026-11-07 | minor | `.fig` import, #2091 item 1: an instance scaled with the Scale tool stores `symbolData.uniformScaleFactor`, which the import never read, so the layers of a 128 px instance of a 256 px component came in at 256 px with the main's radii, strokes and spacing. The layers of an instance now take the main's lengths times the factor (composed through nested instances, so 0.5 inside 0.5 is 0.25 for the inner layers), the lengths the Scale tool scales: sizes and places, corner radii, stroke weights and dashes, effect radii, spreads and offsets, auto layout gaps and paddings, grid gaps, min and max sizes, layout grids, font sizes, pixel line heights and letter spacings, paragraph spacing and indent. A value an override or derived row gives is taken as written, already at the instance's scale; the instance's own size is the file's; a missing, non-finite, non-positive or out-of-range factor (outside 0.001 to 1000) changes nothing. Not scaled: vector outline paths (a network's points follow the layer's size), per-point corner radii, fixed grid tracks, image tile scales and glass effects. Tests: `fig::tests::a_scaled_instance_draws_its_layers_at_the_factor` and `fig::scale_factor_tests`. Numbers unchanged | From 8c0a60a36370b8140aa5e79d1a2c81557884774b Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 05:46:09 -0500 Subject: [PATCH 11/48] Merge fix: main's auto layout drag tests with this PR's defaults main's al_drag_tests `three()` fixture builds its frame with Add auto layout, then sets fixed sizing without a size. With the Shift+A defaults the frame now hugs its three overlapping children (60 wide) instead of keeping 300, so the siblings sit outside it and a drag reparents them out. The fixture now states width and height 300 explicitly; the reorder rule and its pixel thresholds 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/al_drag_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/al_drag_tests.rs b/crates/engine/src/al_drag_tests.rs index 0c5119fc5..33793ea5f 100644 --- a/crates/engine/src/al_drag_tests.rs +++ b/crates/engine/src/al_drag_tests.rs @@ -76,7 +76,7 @@ fn three(s: &mut Session, mode: &str) -> (NodeId, [NodeId; 3]) { let kids: Vec = (0..3).map(|_| id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 60, "height": 60, "parent": f})).unwrap())).collect(); s.execute("layout.add", &json!({"ids": [f]})).unwrap(); - s.execute("node.set", &json!({"id": f, "props": {"layoutMode": mode, "gap": 20, "padding": 0, "sizingH": "fixed", "sizingV": "fixed"}})).unwrap(); + s.execute("node.set", &json!({"id": f, "props": {"layoutMode": mode, "gap": 20, "padding": 0, "sizingH": "fixed", "sizingV": "fixed", "width": 300, "height": 300}})).unwrap(); s.execute("select.none", &json!({})).unwrap(); (f, [kids[0], kids[1], kids[2]]) } From bd5b6ac37bce5c69f801ae89f0017bf337e45d08 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 05:51:20 -0500 Subject: [PATCH 12/48] M2: Shift+A on a one-child group follows the group rule A group with one flow child hit the one-child frame exception (the early return for !new_wrap) and skipped the wrapped-group defaults, so in a vertical flow it got Hug width instead of Fixed. docs/auto-layout-parity.md says a converted group follows the multi-layer wrap rule; the exception is now limited to non-group conversions. 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/al_behaviour_tests.rs | 14 ++++++++++++++ crates/engine/src/cmd/structure.rs | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/al_behaviour_tests.rs b/crates/engine/src/al_behaviour_tests.rs index f7cb799a8..9ed90de09 100644 --- a/crates/engine/src/al_behaviour_tests.rs +++ b/crates/engine/src/al_behaviour_tests.rs @@ -515,6 +515,20 @@ fn shift_a_on_a_group_follows_the_wrap_rule() { assert_eq!((canvas(&s, a).0, canvas(&s, b).0), (0.0, 100.0)); } +#[test] +fn shift_a_on_a_one_child_group_follows_the_group_rule_not_the_one_child_frame_exception() { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let g = id(s.execute("object.group", &json!({"ids": [a]})).unwrap()); + let r = s.execute("layout.add", &json!({"ids": [g], "direction": "vertical"})).unwrap(); + assert_eq!(id_of(&r["ids"][0]), Some(g)); + let n = s.doc().unwrap().node(g).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.padding), (LayoutMode::Vertical, [0.0; 4])); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug)); + assert!(n.fills.is_empty() && !n.clip); +} + fn add_layout_dir(s: &mut Session, ids: &[NodeId], direction: &str) -> NodeId { let r = s.execute("layout.add", &json!({"ids": ids, "direction": direction})).unwrap(); id_of(&r["ids"][0]).unwrap() diff --git a/crates/engine/src/cmd/structure.rs b/crates/engine/src/cmd/structure.rs index 27d88f318..4634f38fa 100644 --- a/crates/engine/src/cmd/structure.rs +++ b/crates/engine/src/cmd/structure.rs @@ -714,7 +714,7 @@ fn add_layout(doc: &Document, frame: NodeId, new_wrap: bool, group: bool, dir: O plan.layout = al; return plan; }; - if flow.is_empty() || (!new_wrap && flow.len() == 1) { + if flow.is_empty() || (!wrapped && flow.len() == 1) { plan.layout = al; return plan; } From b3da0ef69f21f6a483fc60c41bf24b753f9d9c4d Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 16 Nov 2026 04:37:42 -0500 Subject: [PATCH 13/48] 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 --- ROADMAP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index 87c1e76da..46e9f4843 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-15 · **Change:** minor (the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); 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; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7); 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-15 · **Change:** minor (the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); 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 From 32967e849dd0d922a0f427425b6491a652ad5771 Mon Sep 17 00:00:00 2001 From: Andrej Skvorc Date: Tue, 10 Nov 2026 10:18:11 +0100 Subject: [PATCH 14/48] M6: Uno C# Markup code target: wiring --- crates/engine/src/assets/playground.rs | 4 +-- crates/engine/src/dev/codegen.rs | 33 +++++++++++++++------ crates/engine/src/dev/codegen/uno.rs | 10 +++++++ crates/engine/src/dev/component_codegen.rs | 6 ++-- crates/engine/src/lib.rs | 2 ++ crates/engine/src/uno_codegen_tests.rs | 34 ++++++++++++++++++++++ 6 files changed, 76 insertions(+), 13 deletions(-) create mode 100644 crates/engine/src/dev/codegen/uno.rs create mode 100644 crates/engine/src/uno_codegen_tests.rs diff --git a/crates/engine/src/assets/playground.rs b/crates/engine/src/assets/playground.rs index ddb969c25..d9186556e 100644 --- a/crates/engine/src/assets/playground.rs +++ b/crates/engine/src/assets/playground.rs @@ -52,7 +52,7 @@ pub fn specs() -> Vec { vec![spec!( "component.playground", "Component playground", - "{id? (an instance, a component or a component set; default the selection), properties? {name: value} (variant, boolean, text and instance-swap properties, as instance.setProperties takes them), language? css|html|react|leptos|vue|swiftui|compose|arkui|flutter (default react), path? (write the preview there as a PNG), scale? (the PNG's, default 2)} → {component, properties: [{name, type, options?, value}], language, code, width, height, path?} the component with those property values, tried on a copy: its code and its look. Nothing in the document changes", + "{id? (an instance, a component or a component set; default the selection), properties? {name: value} (variant, boolean, text and instance-swap properties, as instance.setProperties takes them), language? css|html|react|leptos|vue|swiftui|compose|arkui|flutter|uno (default react), path? (write the preview there as a PNG), scale? (the PNG's, default 2)} → {component, properties: [{name, type, options?, value}], language, code, width, height, path?} the component with those property values, tried on a copy: its code and its look. Nothing in the document changes", false, |s, p| { let cmd = "component.playground"; @@ -63,7 +63,7 @@ pub fn specs() -> Vec { Some(_) => return Err(bad(cmd, "properties: {name: value}")), }; let lang = match string(p, "language") { - Some(l) => CodeLang::from_id(&l).ok_or_else(|| bad(cmd, "language: css|html|react|leptos|vue|swiftui|compose|arkui|flutter"))?, + Some(l) => CodeLang::from_id(&l).ok_or_else(|| bad(cmd, "language: css|html|react|leptos|vue|swiftui|compose|arkui|flutter|uno"))?, None => CodeLang::React, }; let (copy, inst) = build(s.doc()?, target, &values)?; diff --git a/crates/engine/src/dev/codegen.rs b/crates/engine/src/dev/codegen.rs index 28213e234..34bafb758 100644 --- a/crates/engine/src/dev/codegen.rs +++ b/crates/engine/src/dev/codegen.rs @@ -1,7 +1,7 @@ //! Code for a layer, as shown by the Inspect panel and returned by `inspect.code`: CSS for the -//! layer itself, HTML or React for its subtree, and SwiftUI, Jetpack Compose, ArkUI (HarmonyOS) or -//! Flutter (stacks for auto layout, absolute offsets otherwise). Components become components -//! whose properties are parameters and instances become calls passing their values (see +//! layer itself, HTML or React for its subtree, and SwiftUI, Jetpack Compose, ArkUI (HarmonyOS), +//! Flutter (stacks for auto layout, absolute offsets otherwise) or Uno Platform C# Markup. +//! Components become components whose properties are parameters and instances become calls passing their values (see //! [`crate::component_codegen`]); variables bound to a layer become CSS custom properties, and //! their iOS and Android code syntax in SwiftUI and Compose. The output is a starting point, not a //! pixel-exact translation. @@ -24,6 +24,7 @@ mod css; mod flutter; mod html; mod swift; +mod uno; pub(crate) use arkui::arkui; pub(crate) use compose::{compose, kotlin_color}; @@ -36,19 +37,20 @@ pub(crate) use flutter::{FLUTTER_IMPORT, Place, flutter, flutter_indent}; use html::html; pub(crate) use html::{Markup, Names, class_name}; pub(crate) use swift::swift; +pub(crate) use uno::uno; pub fn specs() -> Vec { vec![spec!( "inspect.code", "Code for layer", - "{id?, language?: css|html|react|leptos|vue|tailwind|swiftui|compose|arkui|flutter (default css; html, react, leptos and vue are the whole layer tree; components take their properties as parameters, instances pass their values; a component connected to code (codeConnect.set) gives its import and snippet instead; tailwind is React with Tailwind CSS v4 utilities for pages: fluid auto layout boxes, instances inlined with their overrides, bound variables as theme utilities), mobile? (tailwind: a mobile frame with the same layer names; the code is mobile first with the desktop layer's classes behind lg:), unit?: px|rem (CSS, HTML, React, Leptos and Vue; default px), rootFontSize? (rem: pixels per rem, default 16)} → {code, language, connected}", + "{id?, language?: css|html|react|leptos|vue|tailwind|swiftui|compose|arkui|flutter|uno (default css; html, react, leptos and vue are the whole layer tree; components take their properties as parameters, instances pass their values; a component connected to code (codeConnect.set) gives its import and snippet instead; tailwind is React with Tailwind CSS v4 utilities for pages: fluid auto layout boxes, instances inlined with their overrides, bound variables as theme utilities), mobile? (tailwind: a mobile frame with the same layer names; the code is mobile first with the desktop layer's classes behind lg:), unit?: px|rem (CSS, HTML, React, Leptos and Vue; default px), rootFontSize? (rem: pixels per rem, default 16)} → {code, language, connected}", false, |s, p| { let cmd = "inspect.code"; let id = targets(s, p).first().copied().ok_or_else(|| bad(cmd, "select a layer"))?; let lang = match string(p, "language") { Some(l) => { - CodeLang::from_id(&l).ok_or_else(|| bad(cmd, "language: css|html|react|leptos|vue|tailwind|swiftui|compose|arkui|flutter"))? + CodeLang::from_id(&l).ok_or_else(|| bad(cmd, "language: css|html|react|leptos|vue|tailwind|swiftui|compose|arkui|flutter|uno"))? } None => CodeLang::Css, }; @@ -103,10 +105,12 @@ pub enum CodeLang { ArkUi, /// A Flutter `StatelessWidget` (Dart) with its widget tree. Flutter, + /// Uno Platform C# Markup (.NET): a fluent C# expression tree of WinUI elements. + Uno, } impl CodeLang { - pub const ALL: [CodeLang; 10] = [ + pub const ALL: [CodeLang; 11] = [ CodeLang::Css, CodeLang::Html, CodeLang::React, @@ -117,6 +121,7 @@ impl CodeLang { CodeLang::Compose, CodeLang::ArkUi, CodeLang::Flutter, + CodeLang::Uno, ]; pub fn id(self) -> &'static str { match self { @@ -130,6 +135,7 @@ impl CodeLang { CodeLang::Compose => "compose", CodeLang::ArkUi => "arkui", CodeLang::Flutter => "flutter", + CodeLang::Uno => "uno", } } pub fn label(self) -> &'static str { @@ -144,6 +150,7 @@ impl CodeLang { CodeLang::Compose => "Compose", CodeLang::ArkUi => "ArkUI", CodeLang::Flutter => "Flutter", + CodeLang::Uno => "Uno C# Markup", } } /// Languages whose lengths are CSS pixels that can be shown in rem (not Tailwind: its lengths @@ -169,6 +176,9 @@ impl CodeLang { if s.eq_ignore_ascii_case("dart") { return Some(CodeLang::Flutter); } + if ["csharp-markup", "cs-markup"].iter().any(|a| s.eq_ignore_ascii_case(a)) { + return Some(CodeLang::Uno); + } CodeLang::ALL.into_iter().find(|l| l.id().eq_ignore_ascii_case(s) || l.label().eq_ignore_ascii_case(s)) } } @@ -284,9 +294,14 @@ pub fn code_for(doc: &Document, id: NodeId, lang: CodeLang) -> String { CodeLang::Css => css(doc, id), CodeLang::Html => html(doc, id), CodeLang::Tailwind => crate::tailwind::code(doc, id, None), - CodeLang::React | CodeLang::Leptos | CodeLang::Vue | CodeLang::SwiftUi | CodeLang::Compose | CodeLang::ArkUi | CodeLang::Flutter => { - crate::component_codegen::code(doc, id, lang) - } + CodeLang::React + | CodeLang::Leptos + | CodeLang::Vue + | CodeLang::SwiftUi + | CodeLang::Compose + | CodeLang::ArkUi + | CodeLang::Flutter + | CodeLang::Uno => crate::component_codegen::code(doc, id, lang), } } diff --git a/crates/engine/src/dev/codegen/uno.rs b/crates/engine/src/dev/codegen/uno.rs new file mode 100644 index 000000000..53267575b --- /dev/null +++ b/crates/engine/src/dev/codegen/uno.rs @@ -0,0 +1,10 @@ +//! Uno Platform C# Markup: a layer and its subtree as a fluent C# expression tree of WinUI +//! elements (`Uno.Extensions.Markup`), inside a small `UserControl` class. + +use figcraft_doc::{Document, NodeId}; + +/// Uno C# Markup for layer `id` and its subtree. +pub(crate) fn uno(doc: &Document, id: NodeId) -> String { + let name = doc.node(id).map_or("Layer", |n| n.name.as_str()); + format!("// {name}: Uno C# Markup is not mapped yet\n") +} diff --git a/crates/engine/src/dev/component_codegen.rs b/crates/engine/src/dev/component_codegen.rs index 11b380b73..4884a9627 100644 --- a/crates/engine/src/dev/component_codegen.rs +++ b/crates/engine/src/dev/component_codegen.rs @@ -12,7 +12,7 @@ use serde_json::{Value, json}; use crate::cmd::CommandSpec; use crate::codegen::{ - CodeLang, Ctx, FLUTTER_IMPORT, Markup, Names, Place, arkui, class_name, compose, flutter, flutter_indent, indent, literal, swift, + CodeLang, Ctx, FLUTTER_IMPORT, Markup, Names, Place, arkui, class_name, compose, flutter, flutter_indent, indent, literal, swift, uno, }; use crate::components::{prop_default_value, slot_edited, slots_of, variant_options, variant_props, variant_set}; use crate::params::{id_of, string, targets}; @@ -119,7 +119,8 @@ pub fn code(doc: &Document, id: NodeId, lang: CodeLang) -> String { if let Some(code) = crate::code_connect::link(doc, id, lang).and_then(|l| crate::code_connect::connected_code(doc, id, lang, l)) { return code; } - let comp = main_of(doc, id).and_then(|m| describe(doc, m)); + // Uno C# Markup writes the layer tree only (instances and components are walked as frames). + let comp = main_of(doc, id).and_then(|m| describe(doc, m)).filter(|_| lang != CodeLang::Uno); let code = match (&n.kind, comp) { (NodeKind::Instance { .. }, Some(c)) => { let call = usage(doc, id, lang, 0).unwrap_or_default(); @@ -155,6 +156,7 @@ pub fn code(doc: &Document, id: NodeId, lang: CodeLang) -> String { flutter(&Ctx::new(doc, id), id, 0, &mut out, Place::Flow); out } + CodeLang::Uno => uno(doc, id), _ => { let mut out = String::new(); compose(&Ctx::new(doc, id), id, 0, &mut out); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index f7d8b029f..906fb42a4 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -620,6 +620,8 @@ mod transform_behaviour_tests; #[cfg(test)] mod unknown_params_tests; #[cfg(test)] +mod uno_codegen_tests; +#[cfg(test)] mod variable_props_tests; #[cfg(test)] mod variable_tests; diff --git a/crates/engine/src/uno_codegen_tests.rs b/crates/engine/src/uno_codegen_tests.rs new file mode 100644 index 000000000..e4c52db31 --- /dev/null +++ b/crates/engine/src/uno_codegen_tests.rs @@ -0,0 +1,34 @@ +//! Uno C# Markup code: `inspect.code {language: "uno"}` writes a fluent C# expression tree of +//! WinUI elements for a layer and its subtree. + +use crate::Session; +use crate::codegen::CodeLang; +use crate::components::tests::{ex, idv}; +use figcraft_doc::*; +use serde_json::json; + +fn uno(s: &mut Session, id: NodeId) -> String { + ex(s, "inspect.code", json!({"id": id, "language": "uno"}))["code"].as_str().unwrap_or_default().to_string() +} + +#[test] +fn uno_is_a_code_language() { + assert!(CodeLang::ALL.contains(&CodeLang::Uno)); + assert_eq!(CodeLang::Uno.id(), "uno"); + assert_eq!(CodeLang::Uno.label(), "Uno C# Markup"); + for alias in ["uno", "UNO", "csharp-markup", "cs-markup", "Uno C# Markup"] { + assert_eq!(CodeLang::from_id(alias), Some(CodeLang::Uno), "{alias}"); + } + assert!(!CodeLang::Uno.is_web() && !CodeLang::Uno.escapes_dollar()); + // Not connectable to code until components are mapped. + assert!(crate::code_connect::language("uno").is_none()); +} + +#[test] +fn inspect_code_answers_in_uno() { + let mut s = Session::new(); + let f = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 100, "height": 50, "name": "Box"}))); + let r = ex(&mut s, "inspect.code", json!({"id": f, "language": "uno"})); + assert_eq!(r["language"], "uno"); + assert!(!uno(&mut s, f).is_empty()); +} From dcefb3870795b838d97476b38bfea18a965678b6 Mon Sep 17 00:00:00 2001 From: Andrej Skvorc Date: Tue, 10 Nov 2026 10:18:11 +0100 Subject: [PATCH 15/48] M6: Uno C# Markup code target: frames, text and images --- README.md | 2 +- ROADMAP.md | 3 +- crates/engine/src/dev/codegen.rs | 2 + crates/engine/src/dev/codegen/uno.rs | 694 ++++++++++++++++++++++++- crates/engine/src/uno_codegen_tests.rs | 304 ++++++++++- docs/gaps.md | 4 + docs/mcp.md | 12 + docs/target-app-parity.md | 2 +- 8 files changed, 1014 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 7bbc4d524..c10d86577 100644 --- a/README.md +++ b/README.md @@ -208,7 +208,7 @@ exposes to agents, and exported at 2x by FigCraft's own renderer. The source fil

Prototype and hand off

- Connections, triggers, actions and Smart Animate-style transitions, variables with conditionals (if / else if / else built in the interaction editor, expressions like count + 1), flows, a presentation view with device frames, hotspot hints and an Inspect panel, and a live preview pane. Alt to measure distances and padding on the canvas, Inspect mode with measurements, annotations in colour-coded categories, a ready-for-dev list with a focus view and Compare changes (before / after with property-level diffs since a frame was marked ready), and code (CSS, HTML, React, Vue, Leptos, SwiftUI, Compose, ArkUI, Flutter) where components take their properties as parameters, comment threads pinned to frames (replies, @mentions, reactions, read state) and named version history. Export any layer at any scale to PNG, JPG, WebP, SVG or PDF. + Connections, triggers, actions and Smart Animate-style transitions, variables with conditionals (if / else if / else built in the interaction editor, expressions like count + 1), flows, a presentation view with device frames, hotspot hints and an Inspect panel, and a live preview pane. Alt to measure distances and padding on the canvas, Inspect mode with measurements, annotations in colour-coded categories, a ready-for-dev list with a focus view and Compare changes (before / after with property-level diffs since a frame was marked ready), and code (CSS, HTML, React, Vue, Leptos, SwiftUI, Compose, ArkUI, Flutter, Uno C# Markup) where components take their properties as parameters, comment threads pinned to frames (replies, @mentions, reactions, read state) and named version history. Export any layer at any scale to PNG, JPG, WebP, SVG or PDF. diff --git a/ROADMAP.md b/ROADMAP.md index fa01afc21..1a62ea0c0 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-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 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-16 · **Change:** minor (Uno C# Markup code generation for layers, with auto layout and vectors as paths; 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 @@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | M6: Uno Platform C# Markup code (ours; the incumbent generates CSS, iOS and Android only): `inspect.code {language: uno}` (aliases `csharp-markup`, `cs-markup`) writes a `UserControl` class whose content is a fluent C# Markup tree for a layer: a frame, group or rectangle is a `Border` (fill as `Color.FromArgb`, border brush and thickness, per-side thickness, per-corner radius, opacity, rotation) holding a `Canvas` with the children at their offsets (a stroke and children put the border behind the canvas in a `Grid`, so the stroke does not push the children in), an ellipse is an `Ellipse`, text is a `TextBlock` (family, size, weight, italic, colour, line height, character spacing, alignment, wrapping, trimming and max lines from the auto resize mode, decoration, case applied when the code runs, mixed styles as `Run`s) and vectors and other shapes are an `Image` on an SVG asset (`ms-appx:///Assets/.svg`, a lowercase ASCII name unique in the snippet) with a comment to export it; image fills are an `ImageBrush` on a PNG asset. Fixed sizes everywhere; auto layout, variables, components and the project export are later steps. Shadows, blurs, blend modes, gradients beyond the first stop, masks and corner smoothing stay as `// not mapped: …` comments in the chain. Not offered for code connect or component code yet. Headline numbers unchanged. | | 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged | | 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. | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged | diff --git a/crates/engine/src/dev/codegen.rs b/crates/engine/src/dev/codegen.rs index 34bafb758..e62b1ab82 100644 --- a/crates/engine/src/dev/codegen.rs +++ b/crates/engine/src/dev/codegen.rs @@ -38,6 +38,8 @@ use html::html; pub(crate) use html::{Markup, Names, class_name}; pub(crate) use swift::swift; pub(crate) use uno::uno; +#[cfg(test)] +pub(crate) use uno::{asset_name, cs_ident, cs_literal, cs_unique}; pub fn specs() -> Vec { vec![spec!( diff --git a/crates/engine/src/dev/codegen/uno.rs b/crates/engine/src/dev/codegen/uno.rs index 53267575b..14d06050b 100644 --- a/crates/engine/src/dev/codegen/uno.rs +++ b/crates/engine/src/dev/codegen/uno.rs @@ -1,10 +1,694 @@ //! Uno Platform C# Markup: a layer and its subtree as a fluent C# expression tree of WinUI -//! elements (`Uno.Extensions.Markup`), inside a small `UserControl` class. +//! elements (`Uno.Extensions.Markup`), inside a small `UserControl` class. Lengths are fixed and +//! children sit at their offsets in a `Canvas`, as in the Flutter target before its auto layout +//! code. Whatever has no counterpart is left as a `// not mapped: …` comment in the chain. -use figcraft_doc::{Document, NodeId}; +use std::collections::BTreeSet; -/// Uno C# Markup for layer `id` and its subtree. +use figcraft_color::{BlendMode, Color, ImageScaleMode, PaintKind}; +use figcraft_doc::{ + Document, EffectKind, LetterSpacing, LineHeight, Node, NodeId, NodeKind, StrokeAlign, TextAlignH, TextAlignV, TextAutoResize, TextCase, TextData, + TextDecoration, TextStyle, +}; + +use super::swift::one_line; +use super::{Ctx, MAX_CHILDREN, first_fill, num, stroke_color}; + +/// Longest string literal written (characters); the rest is cut. +const MAX_LITERAL: usize = 10_000; +/// Longest layer name written into a comment (characters). +const MAX_COMMENT: usize = 80; +/// Longest identifier or asset name written (characters). +const MAX_IDENT: usize = 40; +/// Most style runs of one text written as `Run`s. +const MAX_RUNS: usize = 200; +/// Where the app keeps the images and vectors the code refers to. +const ASSETS: &str = "ms-appx:///Assets"; + +/// C# indents by four spaces. +pub(crate) fn uno_indent(depth: usize) -> String { + " ".repeat(depth) +} + +/// A C# string literal: `"` and `\` escaped, control and line separator characters as escapes, +/// never an interpolated string. Cut at [`MAX_LITERAL`] characters. +pub(crate) fn cs_literal(s: &str) -> String { + let mut out = String::from("\""); + for c in s.chars().take(MAX_LITERAL) { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + // Other control characters and the line and paragraph separators end a C# line. + c if c.is_control() || matches!(c, '\u{2028}' | '\u{2029}') => out.push_str(&format!("\\u{:04X}", u32::from(c))), + c => out.push(c), + } + } + out.push('"'); + out +} + +/// C# reserved words, which an identifier may not be (all lowercase, so only camelCase meets them). +const CS_KEYWORDS: &[&str] = &[ + "abstract", + "as", + "base", + "bool", + "break", + "byte", + "case", + "catch", + "char", + "checked", + "class", + "const", + "continue", + "decimal", + "default", + "delegate", + "do", + "double", + "else", + "enum", + "event", + "explicit", + "extern", + "false", + "finally", + "fixed", + "float", + "for", + "foreach", + "goto", + "if", + "implicit", + "in", + "int", + "interface", + "internal", + "is", + "lock", + "long", + "namespace", + "new", + "null", + "object", + "operator", + "out", + "override", + "params", + "private", + "protected", + "public", + "readonly", + "ref", + "return", + "sbyte", + "sealed", + "short", + "sizeof", + "stackalloc", + "static", + "string", + "struct", + "switch", + "this", + "throw", + "true", + "try", + "typeof", + "uint", + "ulong", + "unchecked", + "unsafe", + "ushort", + "using", + "virtual", + "void", + "volatile", + "while", +]; + +/// The ASCII alphanumeric words of `name` after transliteration (so non-Latin names stay +/// readable), kept whole up to [`MAX_IDENT`] characters; the first word is kept even when it alone +/// is too long (the caller cuts it). +fn ascii_words(name: &str) -> Vec { + let mut kept: Vec = Vec::new(); + let mut len = 0; + for w in deunicode::deunicode(name).split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()) { + if !kept.is_empty() && len + w.len() > MAX_IDENT { + break; + } + len += w.len(); + kept.push(w.to_string()); + } + kept +} + +/// A C# identifier from a layer name: words joined as PascalCase (`pascal`) or camelCase, cut at +/// [`MAX_IDENT`] characters on a word boundary. A name left with nothing takes `kind`; a leading +/// digit gets a `_` prefix and a reserved word a `_` suffix (never `@`). +pub(crate) fn cs_ident(name: &str, pascal: bool, kind: &str) -> String { + let mut out = String::new(); + for (i, w) in ascii_words(name).iter().enumerate() { + let mut cs = w.chars(); + let Some(first) = cs.next() else { continue }; + // The first letter of each word is upper-case (the first word of camelCase lower-case); + // the rest keeps its case, so `mainCard` stays recognisable. + if i == 0 && !pascal { + out.extend(first.to_lowercase()); + } else { + out.extend(first.to_uppercase()); + } + out.push_str(cs.as_str()); + } + let mut out: String = out.chars().take(MAX_IDENT).collect(); + if out.is_empty() { + let k: String = kind.chars().filter(char::is_ascii_alphanumeric).collect(); + let mut cs = k.chars(); + out = match cs.next() { + Some(f) if pascal => f.to_uppercase().chain(cs).collect(), + Some(f) => f.to_lowercase().chain(cs).collect(), + None => "Layer".into(), + }; + } + if out.starts_with(|c: char| c.is_ascii_digit()) { + out.insert(0, '_'); + } + if CS_KEYWORDS.contains(&out.as_str()) { + out.push('_'); + } + out +} + +/// `base` made unique among `used` (C# names are case-sensitive): `Card`, `Card2`, `Card3`, …. +#[cfg_attr(not(test), allow(dead_code, reason = "names of component members (U3)"))] +pub(crate) fn cs_unique(base: &str, used: &mut BTreeSet) -> String { + let name = (1usize..) + .map(|k| if k == 1 { base.to_string() } else { format!("{base}{k}") }) + .find(|n| !used.contains(n)) + .unwrap_or_else(|| base.to_string()); + used.insert(name.clone()); + name +} + +/// The file name (without extension) of the image or vector asset of a layer: lowercase +/// `[a-z0-9_]`, starting with a letter, at most [`MAX_IDENT`] characters, unique among `used` +/// (`logo`, `logo_2`, `logo_3`, …). A name left with nothing takes `kind`. +pub(crate) fn asset_name(name: &str, kind: &str, used: &mut BTreeSet) -> String { + let mut base = ascii_words(name).iter().map(|w| w.to_ascii_lowercase()).collect::>().join("_"); + base = base.chars().take(MAX_IDENT).collect(); + let base = base.trim_end_matches('_').to_string(); + let base = if base.is_empty() { + let k: String = kind.to_ascii_lowercase().chars().filter(char::is_ascii_alphanumeric).collect(); + if k.is_empty() { "image".into() } else { k } + } else { + base + }; + let base = if base.starts_with(|c: char| c.is_ascii_digit()) { format!("img_{base}") } else { base }; + let name = + (1usize..).map(|k| if k == 1 { base.clone() } else { format!("{base}_{k}") }).find(|n| !used.contains(n)).unwrap_or_else(|| base.clone()); + used.insert(name.clone()); + name +} + +/// `Color.FromArgb(0xAA, 0xRR, 0xGG, 0xBB)` (needs `using Windows.UI;`). +pub(crate) fn cs_color(c: Color) -> String { + let [r, g, b, a] = c.to_rgba8(); + format!("Color.FromArgb(0x{a:02X}, 0x{r:02X}, 0x{g:02X}, 0x{b:02X})") +} + +/// A layer name for a comment line: one line, cut. +fn comment_name(name: &str) -> String { + let one = one_line(name); + let cut: String = one.chars().take(MAX_COMMENT).collect(); + if cut.chars().count() < one.chars().count() { format!("{cut}…") } else { cut } +} + +/// One element of the tree before it is written: comment lines above it, its constructor, the +/// chain of property calls (a call starting with `//` is a comment line) and its children. +struct Element { + lead: Vec, + ctor: String, + calls: Vec, + /// `Child` (one) or `Children` (several) and the child expressions, written two levels in. + kids: Option<(&'static str, Vec)>, +} + +impl Element { + fn new(ctor: &str) -> Self { + Element { lead: Vec::new(), ctor: ctor.to_string(), calls: Vec::new(), kids: None } + } + + fn call(&mut self, c: impl Into) { + self.calls.push(c.into()); + } + + fn note(&mut self, what: &str) { + self.calls.push(format!("// not mapped: {what}")); + } + + /// The element written at `depth`: a complete expression, no trailing newline. + fn write(&self, depth: usize) -> String { + let (pad, inner) = (uno_indent(depth), uno_indent(depth + 1)); + let mut out = String::new(); + for l in &self.lead { + out.push_str(&format!("{pad}{l}\n")); + } + out.push_str(&format!("{pad}{}", self.ctor)); + for c in &self.calls { + // A call of several lines is indented relative to its first. + out.push_str(&format!("\n{inner}{}", c.replace('\n', &format!("\n{inner}")))); + } + if let Some((method, kids)) = &self.kids { + out.push_str(&format!("\n{inner}.{method}(\n{})", kids.join(",\n"))); + } + out + } +} + +/// What a tree walk keeps between layers. +struct Gen<'a> { + ctx: &'a Ctx<'a>, + /// Asset names given out, so no two layers share a file. + assets: BTreeSet, +} + +/// Uno C# Markup for layer `id` and its subtree: a `UserControl` class whose content is the tree. pub(crate) fn uno(doc: &Document, id: NodeId) -> String { - let name = doc.node(id).map_or("Layer", |n| n.name.as_str()); - format!("// {name}: Uno C# Markup is not mapped yet\n") + let Some(root) = doc.node(id) else { return String::new() }; + // The tree sits three levels in: namespace member, constructor body, `Content(` argument. + let ctx = Ctx { base: 3, ..Ctx::new(doc, id) }; + let mut g = Gen { ctx: &ctx, assets: BTreeSet::new() }; + let body = g.layer(root, 3, None).unwrap_or_else(|| format!("{}new Border()", uno_indent(3))); + let mut out = String::new(); + let usings: Vec<&str> = [ + ("using Microsoft.UI.Text;", "FontWeights."), + ("using Windows.Foundation;", "new Rect("), + ("using Windows.UI;", "Color.FromArgb("), + ("using Windows.UI.Text;", "FontStyle."), + ] + .into_iter() + .filter(|(_, marker)| body.contains(marker)) + .map(|(u, _)| u) + .collect(); + for u in &usings { + out.push_str(u); + out.push('\n'); + } + if !usings.is_empty() { + out.push('\n'); + } + // A view named like a WinUI type (`Button`, `Border`) would hide it in the tree below. + let mut name = cs_ident(&root.name, true, "Layer"); + if !name.ends_with("View") { + name.push_str("View"); + } + out.push_str(&format!("// {}\nnamespace MyApp;\n\n", comment_name(&root.name))); + out.push_str(&format!("internal sealed partial class {name} : UserControl\n{{\n")); + out.push_str(&format!(" public {name}()\n {{\n this.Content(\n{body});\n }}\n}}\n")); + out +} + +impl Gen<'_> { + /// A layer and its subtree at `depth`, placed in a `Canvas` at `at`. `None` for a layer that + /// draws nothing. + fn layer(&mut self, n: &Node, depth: usize, at: Option<(f64, f64)>) -> Option { + if matches!(n.kind, NodeKind::Slice) { + return None; + } + if self.ctx.too_deep(depth) { + return Some(format!("{pad}// {} …\n{pad}new Border()", comment_name(&n.name), pad = uno_indent(depth))); + } + let e = match &n.kind { + NodeKind::Text(t) => self.text(n, t, depth, at), + NodeKind::Ellipse { start, sweep, inner } => self.ellipse(n, (*start, *sweep, *inner), at), + NodeKind::Rectangle | NodeKind::Group | NodeKind::Section { .. } => self.boxed(n, depth, at), + k if k.is_frame_like() => self.boxed(n, depth, at), + _ => self.asset(n, at), + }; + Some(e.write(depth)) + } + + /// A frame-like layer, group or rectangle: a `Border` with its fill, stroke and corners holding + /// a `Canvas` with the children at their offsets. With a stroke and children the border sits + /// behind the canvas in a `Grid`, since a `Border` pushes its content in by its thickness. + fn boxed(&mut self, n: &Node, depth: usize, at: Option<(f64, f64)>) -> Element { + let mut border = Element::new("new Border()"); + let sized = !matches!(n.kind, NodeKind::Group | NodeKind::Section { .. }); + self.paint_box(&mut border, n, sized); + let mut exprs: Vec = Vec::new(); + for k in self.ctx.kids(n).iter().take(MAX_CHILDREN) { + let Some(c) = self.ctx.doc.node(*k) else { continue }; + let [_, _, _, _, x, y] = c.transform.as_coeffs(); + exprs.extend(self.layer(c, depth + 4, Some((x, y)))); + } + let mut canvas = Element::new("new Canvas()"); + let has_kids = !exprs.is_empty(); + if has_kids { + canvas.kids = Some(("Children", exprs)); + } + let mut outer; + if has_kids && stroke_color(n).is_some() { + outer = Element::new("new Grid()"); + place(&mut outer, at); + size(&mut outer, n); + border.calls.retain(|c| !c.starts_with(".Width(") && !c.starts_with(".Height(")); + outer.kids = Some(("Children", vec![border.write(depth + 2), canvas.write(depth + 2)])); + common(&mut outer, n); + } else { + outer = border; + place(&mut outer, at); + if has_kids { + outer.kids = Some(("Child", vec![canvas.write(depth + 2)])); + } + common(&mut outer, n); + } + if n.clip && has_kids && n.corners.radii.iter().all(|r| *r <= 0.0) { + outer.call(format!(".Clip(new RectangleGeometry().Rect(new Rect(0, 0, {}, {})))", num(n.width), num(n.height))); + } + outer + } + + /// The fill, stroke and corners of a `Border`. + fn paint_box(&mut self, e: &mut Element, n: &Node, sized: bool) { + if sized { + size(e, n); + } + let visible: Vec<_> = n.fills.iter().filter(|p| p.visible).collect(); + match visible.first().map(|p| &p.kind) { + Some(PaintKind::Image(img)) => { + let name = asset_name(&n.name, "image", &mut self.assets); + let stretch = match img.scale_mode { + ImageScaleMode::Fit => "Uniform", + ImageScaleMode::Fill | ImageScaleMode::Crop | ImageScaleMode::Tile => "UniformToFill", + }; + e.call(format!(".Background(new ImageBrush().ImageSource(\"{ASSETS}/{name}.png\").Stretch(Stretch.{stretch}))")); + match img.scale_mode { + ImageScaleMode::Crop => e.note("image crop (drawn as fill)"), + ImageScaleMode::Tile => e.note("tiled image (drawn as fill)"), + ImageScaleMode::Fill | ImageScaleMode::Fit => {} + } + } + Some(PaintKind::Gradient(_)) => { + if let Some(c) = first_fill(n) { + e.call(format!(".Background({})", cs_color(c))); + } + e.note("gradient fill (its first stop colour is used)"); + } + Some(PaintKind::Pattern(_)) => e.note("pattern fill"), + Some(PaintKind::Solid { .. }) => { + if let Some(c) = first_fill(n) { + e.call(format!(".Background({})", cs_color(c))); + } + } + None => {} + } + if visible.len() > 1 { + e.note(&format!("{} more fills (only the first is drawn)", visible.len() - 1)); + } + if let Some(c) = stroke_color(n) { + e.call(format!(".BorderBrush({})", cs_color(c))); + match n.stroke.sides { + // Per-side weights are top, right, bottom, left; `Thickness` takes left first. + Some([t, r, b, l]) => e.call(format!(".BorderThickness(new Thickness({}, {}, {}, {}))", num(l), num(t), num(r), num(b))), + None => e.call(format!(".BorderThickness({})", num(n.stroke.weight))), + } + if n.stroke.align != StrokeAlign::Inside { + e.note("stroke outside or centred (a border is drawn inside)"); + } + } + let [tl, tr, br, bl] = n.corners.radii; + if n.corners.uniform().is_some() { + if tl > 0.0 { + e.call(format!(".CornerRadius({})", num(tl))); + } + } else { + e.call(format!(".CornerRadius(new CornerRadius({}, {}, {}, {}))", num(tl), num(tr), num(br), num(bl))); + } + if n.corners.smoothing > 0.0 && n.corners.radii.iter().any(|r| *r > 0.0) { + e.note("corner smoothing"); + } + } + + /// An ellipse: `Ellipse` with `Fill` and a centred `Stroke`. + fn ellipse(&mut self, n: &Node, (start, sweep, inner): (f64, f64, f64), at: Option<(f64, f64)>) -> Element { + let mut e = Element::new("new Ellipse()"); + place(&mut e, at); + size(&mut e, n); + if let Some(c) = first_fill(n) { + e.call(format!(".Fill({})", cs_color(c))); + } + if let Some(c) = stroke_color(n) { + e.call(format!(".Stroke({})", cs_color(c))); + e.call(format!(".StrokeThickness({})", num(n.stroke.weight))); + if n.stroke.align != StrokeAlign::Center { + e.note("stroke inside or outside (an ellipse stroke is centred)"); + } + } + if start != 0.0 || (sweep - std::f64::consts::TAU).abs() > 1e-6 || inner > 0.0 { + e.note("arc or ring (drawn as a full ellipse)"); + } + common(&mut e, n); + e + } + + /// A vector, shape or other layer without a counterpart: the image the app is to hold. + fn asset(&mut self, n: &Node, at: Option<(f64, f64)>) -> Element { + let name = asset_name(&n.name, n.kind.label(), &mut self.assets); + let mut e = Element::new("new Image()"); + e.lead.push(format!("// {} \"{}\": export it as an SVG to Assets/{name}.svg", n.kind.label(), comment_name(&n.name))); + place(&mut e, at); + e.call(format!(".Source(\"{ASSETS}/{name}.svg\")")); + size(&mut e, n); + e.call(".Stretch(Stretch.Uniform)"); + common(&mut e, n); + e + } + + /// Text: a `TextBlock`, in a `Grid` of the box's height when it is aligned to the middle or + /// bottom of a fixed box. + fn text(&mut self, n: &Node, t: &TextData, depth: usize, at: Option<(f64, f64)>) -> Element { + let fixed = matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Truncate); + let framed = fixed && t.align_v != TextAlignV::Top; + let mut tb = text_block(n, t, !framed); + if !framed { + place(&mut tb, at); + common(&mut tb, n); + return tb; + } + tb.call(format!(".VerticalAlignment(VerticalAlignment.{})", if t.align_v == TextAlignV::Middle { "Center" } else { "Bottom" })); + let mut g = Element::new("new Grid()"); + place(&mut g, at); + size(&mut g, n); + g.kids = Some(("Children", vec![tb.write(depth + 2)])); + common(&mut g, n); + g + } +} + +/// The `Canvas` offsets of a child at `at`. +fn place(e: &mut Element, at: Option<(f64, f64)>) { + if let Some((x, y)) = at { + // The offsets come first in the chain: they read as the element's address. + e.calls.insert(0, format!(".Canvas(left: {}, top: {})", num(x), num(y))); + } +} + +/// The layer's fixed width and height. +fn size(e: &mut Element, n: &Node) { + e.call(format!(".Width({})", num(n.width))); + e.call(format!(".Height({})", num(n.height))); +} + +/// What every layer shares: opacity, rotation, and the notes for what has no counterpart. +fn common(e: &mut Element, n: &Node) { + if n.opacity < 1.0 { + e.call(format!(".Opacity({})", num(f64::from(n.opacity)))); + } + // Rotation turns counter-clockwise about the top-left corner (the offsets given); a WinUI + // `RotateTransform` turns clockwise about the element's own origin. + let rot = figcraft_geom::rotation_degrees(n.transform); + if rot.abs() > 0.01 && rot.is_finite() { + e.call(format!(".RenderTransform(new RotateTransform().Angle({}))", num(-rot))); + } + if !matches!(n.blend, BlendMode::Normal | BlendMode::PassThrough) { + e.note(&format!("blend mode {}", n.blend.css())); + } + for fx in n.effects.iter().filter(|f| f.visible) { + e.note(match fx.kind { + EffectKind::DropShadow(_) => "drop shadow (needs Uno.Toolkit ShadowContainer)", + EffectKind::InnerShadow(_) => "inner shadow (needs Uno.Toolkit ShadowContainer)", + EffectKind::LayerBlur(_) => "layer blur", + EffectKind::BackgroundBlur(_) => "background blur", + EffectKind::Noise(_) => "noise", + EffectKind::Texture(_) => "texture", + EffectKind::Glass(_) => "glass", + }); + } + if n.is_mask { + e.note("mask"); + } +} + +/// `FontWeights.SemiBold` for a weight in hundreds (the nearest). +fn cs_weight(w: u16) -> &'static str { + match w { + 0..=150 => "Thin", + 151..=250 => "ExtraLight", + 251..=350 => "Light", + 351..=450 => "Normal", + 451..=550 => "Medium", + 551..=650 => "SemiBold", + 651..=750 => "Bold", + 751..=850 => "ExtraBold", + 851..=950 => "Black", + _ => "ExtraBlack", + } +} + +/// The colour of the first visible solid or gradient paint (a gradient's first stop). +fn paints_color(paints: &[figcraft_color::Paint]) -> Option { + paints.iter().filter(|p| p.visible).find_map(|p| match &p.kind { + PaintKind::Solid { color } => Some(color.with_alpha(color.a * p.opacity)), + PaintKind::Gradient(g) => g.sorted_stops().first().map(|s| s.color), + PaintKind::Image(_) | PaintKind::Pattern(_) => None, + }) +} + +/// `characters` as a string expression in `case`: the case is applied when the code runs, so the +/// string keeps the original text (and the app can translate it). +fn text_expr(characters: &str, case: TextCase) -> String { + let lit = cs_literal(characters); + match case { + TextCase::Original | TextCase::SmallCaps => lit, + TextCase::Upper => format!("{lit}.ToUpperInvariant()"), + TextCase::Lower => format!("{lit}.ToLowerInvariant()"), + TextCase::Title => format!("System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase({lit})"), + } +} + +/// The calls a `TextBlock` or `Run` takes for the parts of `s` that differ from `base` (all of +/// them without a base). `fill` is the colour the text is drawn in. +fn style_calls(e: &mut Element, s: &TextStyle, fill: Option, base: Option<(&TextStyle, Option)>) { + if !s.font_family.is_empty() && base.is_none_or(|(b, _)| b.font_family != s.font_family) { + e.call(format!(".FontFamily({})", cs_literal(&s.font_family))); + } + if base.is_none_or(|(b, _)| b.font_size != s.font_size) { + e.call(format!(".FontSize({})", num(s.font_size))); + } + if (base.is_none() && s.weight() != 400) || base.is_some_and(|(b, _)| b.weight() != s.weight()) { + e.call(format!(".FontWeight(FontWeights.{})", cs_weight(s.weight()))); + } + if (base.is_none() && s.italic()) || base.is_some_and(|(b, _)| b.italic() != s.italic()) { + e.call(format!(".FontStyle(FontStyle.{})", if s.italic() { "Italic" } else { "Normal" })); + } + if let Some(c) = fill + && base.is_none_or(|(_, f)| f != fill) + { + e.call(format!(".Foreground({})", cs_color(c))); + } + if base.is_none() { + match s.line_height { + LineHeight::Pixels(v) if v > 0.0 && v.is_finite() => e.call(format!(".LineHeight({})", num(v))), + LineHeight::Percent(p) if p > 0.0 && p.is_finite() && s.font_size > 0.0 => { + e.call(format!(".LineHeight({})", num(p / 100.0 * s.font_size))) + } + _ => {} + } + } + // `CharacterSpacing` is in thousandths of an em. + let spacing = |x: &TextStyle| match x.letter_spacing { + LetterSpacing::Pixels(v) if v.is_finite() && x.font_size > 0.0 => (v / x.font_size * 1000.0).round(), + LetterSpacing::Percent(p) if p.is_finite() => (p * 10.0).round(), + _ => 0.0, + }; + if base.is_none_or(|(b, _)| spacing(b) != spacing(s)) && (base.is_some() || spacing(s) != 0.0) { + e.call(format!(".CharacterSpacing({})", num(spacing(s)))); + } + if base.is_none_or(|(b, _)| b.decoration != s.decoration) { + match s.decoration { + TextDecoration::None if base.is_some() => e.call(".TextDecorations(Windows.UI.Text.TextDecorations.None)"), + TextDecoration::None => {} + TextDecoration::Underline => e.call(".TextDecorations(Windows.UI.Text.TextDecorations.Underline)"), + TextDecoration::Strikethrough => e.call(".TextDecorations(Windows.UI.Text.TextDecorations.Strikethrough)"), + } + } +} + +/// A `TextBlock` for a text layer. `with_height` sets the box's height when the text has a fixed +/// box (a text in a `Grid` of that height leaves it to the grid). +fn text_block(n: &Node, t: &TextData, with_height: bool) -> Element { + let mut e = Element::new("new TextBlock()"); + let s = &t.style; + let fill = first_fill(n); + // Text in one style is a `Text`; style runs make `Inlines` of `Run`s. + let runs: Vec<_> = t.runs.iter().filter(|r| r.start < r.end).collect(); + let chars: Vec = t.characters.chars().take(MAX_LITERAL * 10).collect(); + if runs.is_empty() || runs.len() > MAX_RUNS { + e.call(format!(".Text({})", text_expr(&t.characters, s.case))); + if !runs.is_empty() { + e.note("style runs (too many)"); + } + } else { + let mut pieces: Vec = Vec::new(); + let mut at = 0; + let mut run = |from: usize, to: usize, style: &TextStyle, fills: Option, plain: bool| { + let part: String = chars.get(from..to.min(chars.len())).unwrap_or_default().iter().collect(); + if part.is_empty() { + return; + } + let mut r = Element::new("new Run()"); + r.call(format!(".Text({})", text_expr(&part, style.case))); + if !plain { + style_calls(&mut r, style, fills, Some((s, fill))); + } + pieces.push(r.write(1)); + }; + for r in &runs { + let (start, end) = (r.start.max(at), r.end.min(chars.len())); + if start >= end { + continue; + } + run(at, start, s, fill, true); + let run_fill = r.style.fills.as_deref().and_then(paints_color).or(fill); + run(start, end, &r.style, run_fill, false); + at = end; + } + run(at, chars.len(), s, fill, true); + e.call(format!(".Inlines(\n{})", pieces.join(",\n"))); + } + style_calls(&mut e, s, fill, None); + match t.align_h { + TextAlignH::Left => {} + TextAlignH::Center => e.call(".TextAlignment(TextAlignment.Center)"), + TextAlignH::Right => e.call(".TextAlignment(TextAlignment.Right)"), + TextAlignH::Justified => e.call(".TextAlignment(TextAlignment.Justify)"), + } + match t.auto_resize { + TextAutoResize::WidthAndHeight => e.call(".TextWrapping(TextWrapping.NoWrap)"), + TextAutoResize::Height => { + e.call(format!(".Width({})", num(n.width))); + e.call(".TextWrapping(TextWrapping.Wrap)"); + } + TextAutoResize::None | TextAutoResize::Truncate => { + e.call(format!(".Width({})", num(n.width))); + if with_height { + e.call(format!(".Height({})", num(n.height))); + } + e.call(".TextWrapping(TextWrapping.Wrap)"); + } + } + if t.auto_resize == TextAutoResize::Truncate || (t.max_lines > 0 && t.auto_resize != TextAutoResize::WidthAndHeight) { + e.call(".TextTrimming(TextTrimming.CharacterEllipsis)"); + if t.max_lines > 0 { + e.call(format!(".MaxLines({})", t.max_lines)); + } + } + if s.case == TextCase::SmallCaps { + e.note("small caps"); + } + e } diff --git a/crates/engine/src/uno_codegen_tests.rs b/crates/engine/src/uno_codegen_tests.rs index e4c52db31..35e93b7ea 100644 --- a/crates/engine/src/uno_codegen_tests.rs +++ b/crates/engine/src/uno_codegen_tests.rs @@ -2,10 +2,11 @@ //! WinUI elements for a layer and its subtree. use crate::Session; -use crate::codegen::CodeLang; +use crate::codegen::{CodeLang, asset_name, cs_ident, cs_literal, cs_unique}; use crate::components::tests::{ex, idv}; use figcraft_doc::*; use serde_json::json; +use std::collections::BTreeSet; fn uno(s: &mut Session, id: NodeId) -> String { ex(s, "inspect.code", json!({"id": id, "language": "uno"}))["code"].as_str().unwrap_or_default().to_string() @@ -32,3 +33,304 @@ fn inspect_code_answers_in_uno() { assert_eq!(r["language"], "uno"); assert!(!uno(&mut s, f).is_empty()); } + +fn frame(s: &mut Session, name: &str, w: f64, h: f64) -> NodeId { + idv(&ex(s, "frame.create", json!({"x": 0, "y": 0, "width": w, "height": h, "name": name}))) +} + +fn set(s: &mut Session, id: NodeId, props: serde_json::Value) { + ex(s, "node.set", json!({"id": id, "props": props})); +} + +/// The body of the generated class: what sits inside `this.Content(` … `);`. +fn tree(code: &str) -> String { + let start = code.find("this.Content(\n").map_or(0, |i| i + "this.Content(\n".len()); + let end = code.rfind(");\n }\n}").unwrap_or(code.len()); + code.get(start..end).unwrap_or_default().to_string() +} + +#[test] +fn an_empty_frame_is_a_view_class_with_a_sized_border() { + let mut s = Session::new(); + let f = frame(&mut s, "Empty", 100.0, 50.0); + let expected = "using Windows.UI; + +// Empty +namespace MyApp; + +internal sealed partial class EmptyView : UserControl +{ + public EmptyView() + { + this.Content( + new Border() + .Width(100) + .Height(50) + .Background(Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF))); + } +} +"; + assert_eq!(uno(&mut s, f), expected); + // Deterministic: the same document gives the same code. + assert_eq!(uno(&mut s, f), uno(&mut s, f)); +} + +#[test] +fn a_frame_with_a_stroke_and_children_keeps_the_children_out_of_the_border() { + let mut s = Session::new(); + let f = frame(&mut s, "Login Screen", 200.0, 100.0); + set(&mut s, f, json!({"fill": "#112233", "stroke": "#FF0000", "strokeWeight": 3, "opacity": 0.5, "cornerRadius": 8})); + ex(&mut s, "shape.rectangle", json!({"x": 5, "y": 5, "width": 20, "height": 20, "parent": f, "props": {"name": "Box"}})); + let expected = "new Grid() + .Width(200) + .Height(100) + .Opacity(0.5) + .Children( + new Border() + .Background(Color.FromArgb(0xFF, 0x11, 0x22, 0x33)) + .BorderBrush(Color.FromArgb(0xFF, 0xFF, 0x00, 0x00)) + .BorderThickness(3) + .CornerRadius(8), + new Canvas() + .Children( + new Border() + .Canvas(left: 5, top: 5) + .Width(20) + .Height(20) + .Background(Color.FromArgb(0xFF, 0xD9, 0xD9, 0xD9))))"; + let code = uno(&mut s, f); + assert!(code.contains("internal sealed partial class LoginScreenView : UserControl"), "{code}"); + let body: String = tree(&code).lines().map(|l| format!("{}\n", l.get(12..).unwrap_or(l))).collect(); + assert_eq!(body.trim_end(), expected, "{code}"); +} + +#[test] +fn a_box_maps_its_stroke_sides_corners_opacity_rotation_and_what_it_cannot() { + let mut s = Session::new(); + let f = frame(&mut s, "Frame", 120.0, 80.0); + let r = idv(&ex(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 30, "parent": f, "props": {"name": "Box"}}))); + set(&mut s, r, json!({"fill": "#336699", "topLeftRadius": 4, "topRightRadius": 8, "bottomRightRadius": 12, "bottomLeftRadius": 16})); + let code = uno(&mut s, f); + assert!(code.contains(".CornerRadius(new CornerRadius(4, 8, 12, 16))"), "{code}"); + // Per-side stroke weights are top, right, bottom, left; a Thickness takes left first. + set(&mut s, r, json!({"stroke": "#000000", "strokeWeight": 1})); + set(&mut s, r, json!({"strokeTopWeight": 1, "strokeRightWeight": 2, "strokeBottomWeight": 3, "strokeLeftWeight": 4})); + let code = uno(&mut s, f); + assert!(code.contains(".BorderThickness(new Thickness(4, 1, 2, 3))"), "{code}"); + set(&mut s, r, json!({"opacity": 0.25, "rotation": 90, "strokeAlign": "outside"})); + let code = uno(&mut s, f); + assert!(code.contains(".Opacity(0.25)"), "{code}"); + assert!(code.contains(".RenderTransform(new RotateTransform().Angle(-90))"), "{code}"); + assert!(code.contains("// not mapped: stroke outside or centred"), "{code}"); +} + +#[test] +fn a_shadow_is_left_as_a_not_mapped_comment() { + let mut s = Session::new(); + let f = frame(&mut s, "Fx", 100.0, 100.0); + set(&mut s, f, json!({"effects": [{"type": "dropShadow", "color": "#00000040", "offset": [0, 4], "radius": 8}]})); + let code = uno(&mut s, f); + assert!(code.contains("// not mapped: drop shadow (needs Uno.Toolkit ShadowContainer)"), "{code}"); +} + +#[test] +fn an_ellipse_is_an_ellipse_with_a_centred_stroke() { + let mut s = Session::new(); + let f = frame(&mut s, "Dots", 100.0, 100.0); + ex( + &mut s, + "shape.ellipse", + json!({"x": 10, "y": 20, "width": 40, "height": 40, "parent": f, "props": {"name": "Dot", "fill": "#FF0000", "stroke": "#000000", "strokeWeight": 2, "strokeAlign": "center"}}), + ); + let code = uno(&mut s, f); + let expected = "new Ellipse() + .Canvas(left: 10, top: 20) + .Width(40) + .Height(40) + .Fill(Color.FromArgb(0xFF, 0xFF, 0x00, 0x00)) + .Stroke(Color.FromArgb(0xFF, 0x00, 0x00, 0x00)) + .StrokeThickness(2)"; + let indented = expected.lines().collect::>().join("\n "); + assert!(code.contains(&indented), "{code}"); +} + +#[test] +fn text_maps_its_style_and_box() { + let mut s = Session::new(); + let f = frame(&mut s, "Texts", 300.0, 200.0); + let t = idv(&ex(&mut s, "text.create", json!({"text": "Say \"hi\"\n\\", "x": 10, "y": 12, "parent": f, "props": {"name": "T"}}))); + set( + &mut s, + t, + json!({"fontFamily": "Inter", "fontSize": 16, "fontWeight": 600, "fontStyle": "Semi Bold Italic", "letterSpacing": 2, "lineHeight": "150%", "textDecoration": "underline", "textAlign": "center", "width": 150, "textAutoResize": "height", "fill": "#112233"}), + ); + let code = uno(&mut s, f); + assert!(code.contains("using Microsoft.UI.Text;"), "{code}"); + for line in [ + ".Canvas(left: 10, top: 12)", + ".Text(\"Say \\\"hi\\\"\\n\\\\\")", + ".FontFamily(\"Inter\")", + ".FontSize(16)", + ".FontWeight(FontWeights.SemiBold)", + ".FontStyle(FontStyle.Italic)", + ".Foreground(Color.FromArgb(0xFF, 0x11, 0x22, 0x33))", + ".LineHeight(24)", + ".CharacterSpacing(125)", + ".TextDecorations(Windows.UI.Text.TextDecorations.Underline)", + ".TextAlignment(TextAlignment.Center)", + ".Width(150)", + ".TextWrapping(TextWrapping.Wrap)", + ] { + assert!(code.contains(&format!("{line}\n")) || code.contains(&format!("{line})")), "{line} in {code}"); + } + // Auto height has a width but no height of its own. + assert!(!code.contains(".Height(") || code.matches(".Height(").count() == 1, "{code}"); + // A fixed box aligned to the middle sits in a grid of its height. + set(&mut s, t, json!({"textAutoResize": "none", "height": 60, "textAlignVertical": "middle"})); + let code = uno(&mut s, f); + assert!(code.contains("new Grid()") && code.contains(".VerticalAlignment(VerticalAlignment.Center)"), "{code}"); + // Truncation ends in an ellipsis. + set(&mut s, t, json!({"textAutoResize": "truncate", "textAlignVertical": "top"})); + assert!(uno(&mut s, f).contains(".TextTrimming(TextTrimming.CharacterEllipsis)")); +} + +#[test] +fn text_case_is_applied_when_the_code_runs() { + let mut s = Session::new(); + let f = frame(&mut s, "Cases", 300.0, 100.0); + let t = idv(&ex(&mut s, "text.create", json!({"text": "Hello", "x": 0, "y": 0, "parent": f, "props": {"name": "T"}}))); + for (case, expr) in [("upper", ".Text(\"Hello\".ToUpperInvariant())"), ("lower", ".Text(\"Hello\".ToLowerInvariant())")] { + set(&mut s, t, json!({"textCase": case})); + let code = uno(&mut s, f); + assert!(code.contains(expr), "{code}"); + } + set(&mut s, t, json!({"textCase": "title"})); + assert!(uno(&mut s, f).contains("TextInfo.ToTitleCase(\"Hello\")")); + set(&mut s, t, json!({"textCase": "smallCaps"})); + assert!(uno(&mut s, f).contains("// not mapped: small caps")); +} + +#[test] +fn mixed_styles_become_runs() { + let mut s = Session::new(); + let f = frame(&mut s, "Runs", 300.0, 100.0); + let t = idv(&ex( + &mut s, + "text.create", + json!({"text": "Plain bold end", "x": 0, "y": 0, "parent": f, "props": {"name": "T", "fontFamily": "Inter", "fontSize": 18}}), + )); + set(&mut s, t, json!({"fontWeight": 700, "start": 6, "end": 10})); + let code = uno(&mut s, f); + let expected = ".Inlines( + new Run() + .Text(\"Plain \"), + new Run() + .Text(\"bold\") + .FontWeight(FontWeights.Bold), + new Run() + .Text(\" end\"))"; + let indented = expected.lines().collect::>().join("\n "); + assert!(code.contains(&indented), "{code}"); + assert!(!code.contains(".Text(\"Plain bold end\")"), "{code}"); +} + +#[test] +fn vectors_are_svg_assets_with_unique_lowercase_names() { + let mut s = Session::new(); + let f = frame(&mut s, "Icons", 200.0, 100.0); + for x in [0, 50, 100] { + ex(&mut s, "node.create", json!({"type": "star", "parent": f, "name": "Star Icon", "x": x, "y": 0, "width": 40, "height": 40})); + } + let code = uno(&mut s, f); + for n in ["star_icon", "star_icon_2", "star_icon_3"] { + assert!(code.contains(&format!(".Source(\"ms-appx:///Assets/{n}.svg\")")), "{n} in {code}"); + assert!(code.contains(&format!("// Star \"Star Icon\": export it as an SVG to Assets/{n}.svg")), "{code}"); + } + assert!(code.contains(".Stretch(Stretch.Uniform)"), "{code}"); +} + +#[test] +fn an_image_fill_is_an_image_brush_on_a_png_asset() { + use base64::Engine as _; + let mut s = Session::new(); + let image = image::RgbaImage::from_fn(8, 4, |x, y| image::Rgba([x as u8, y as u8, 120, 255])); + let mut bytes = std::io::Cursor::new(Vec::new()); + image.write_to(&mut bytes, image::ImageFormat::Png).unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(bytes.into_inner()); + let img = idv(&ex(&mut s, "file.import", json!({"data": data, "name": "Foto Größe.png", "x": 0, "y": 0}))); + set(&mut s, img, json!({"name": "Foto Größe"})); + let code = uno(&mut s, img); + assert!( + code.contains(".Background(new ImageBrush().ImageSource(\"ms-appx:///Assets/foto_grosse.png\").Stretch(Stretch.UniformToFill))"), + "{code}" + ); +} + +#[test] +fn hidden_layers_and_deep_trees_are_left_out_or_summarised() { + let mut s = Session::new(); + let f = frame(&mut s, "Tree", 100.0, 100.0); + let hidden = idv(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10, "parent": f, "props": {"name": "Hidden"}}))); + set(&mut s, hidden, json!({"visible": false})); + assert!(!uno(&mut s, f).contains("Hidden")); + let mut parent = f; + for i in 0..20 { + parent = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50, "parent": parent, "name": format!("Level {i}")}))); + } + let code = uno(&mut s, f); + assert!(code.contains("// Level ") && code.contains(" …\n"), "{code}"); + assert!(code.lines().all(|l| l.len() < 400), "{code}"); +} + +#[test] +fn literals_are_escaped_never_interpolated() { + assert_eq!(cs_literal("a\"b\\c"), "\"a\\\"b\\\\c\""); + assert_eq!(cs_literal("line\r\n\ttab"), "\"line\\r\\n\\ttab\""); + assert_eq!(cs_literal("{x} $y\u{0}\u{2028}\u{85}"), "\"{x} $y\\u0000\\u2028\\u0085\""); + assert_eq!(cs_literal("é日本"), "\"é日本\""); + // Cut, not crashed, at 10,000 characters. + assert_eq!(cs_literal(&"x".repeat(20_000)).chars().count(), 10_002); +} + +#[test] +fn identifiers_are_c_sharp_names() { + assert_eq!(cs_ident("Login Screen", true, "Frame"), "LoginScreen"); + assert_eq!(cs_ident("main card", false, "Frame"), "mainCard"); + assert_eq!(cs_ident("mainCard / title-1", true, "Frame"), "MainCardTitle1"); + assert_eq!(cs_ident("кнопка", true, "Frame"), "Knopka"); + assert_eq!(cs_ident("3 cards", true, "Frame"), "_3Cards"); + assert_eq!(cs_ident("class", false, "Frame"), "class_"); + assert_eq!(cs_ident("???", true, "frame"), "Frame"); + assert_eq!(cs_ident("", false, "Text"), "text"); + assert!(cs_ident(&"word ".repeat(40), true, "Frame").chars().count() <= 40); + let mut used = BTreeSet::new(); + assert_eq!(cs_unique("Card", &mut used), "Card"); + assert_eq!(cs_unique("Card", &mut used), "Card2"); + assert_eq!(cs_unique("Card", &mut used), "Card3"); + assert_eq!(cs_unique("card", &mut used), "card"); +} + +#[test] +fn asset_names_are_lowercase_ascii_starting_with_a_letter_and_unique() { + let mut used = BTreeSet::new(); + assert_eq!(asset_name("Hero Image", "Rectangle", &mut used), "hero_image"); + assert_eq!(asset_name("hero image", "Rectangle", &mut used), "hero_image_2"); + assert_eq!(asset_name("HERO-IMAGE", "Rectangle", &mut used), "hero_image_3"); + assert_eq!(asset_name("Größe über Äpfel", "Vector", &mut used), "grosse_uber_apfel"); + assert_eq!(asset_name("로그인 화면", "Vector", &mut used), "rogeuin_hwamyeon"); + assert_eq!(asset_name("2x icon", "Vector", &mut used), "img_2x_icon"); + assert_eq!(asset_name("***", "Star", &mut used), "star"); + assert_eq!(asset_name("", "", &mut used), "image"); + let long = asset_name(&"segment ".repeat(20), "Vector", &mut used); + assert!(long.len() <= 40 && !long.ends_with('_') && long.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'), "{long}"); +} + +#[test] +fn instances_and_components_are_walked_as_frames() { + let mut s = Session::new(); + let f = frame(&mut s, "Card", 100.0, 50.0); + let c = idv(&ex(&mut s, "component.create", json!({"ids": [f]}))); + let code = uno(&mut s, c); + assert!(code.contains("internal sealed partial class CardView : UserControl"), "{code}"); + assert!(!code.contains("export default") && !code.contains("function "), "{code}"); +} diff --git a/docs/gaps.md b/docs/gaps.md index 66ac5bb9f..e088b4696 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -477,6 +477,10 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe - **Landed (2026-10-24):** files dropped on the canvas, the Pages list and the Assets panel no longer edit the design in Dev Mode (a dropped document still opens as a file of its own, and the Pages list only opens pages). +- **Landed (2026-11-10):** Uno Platform C# Markup for layers: `inspect.code {language: uno}` writes frames, groups, rectangles, + ellipses, text (also mixed styles) and image or vector assets as a fluent C# tree (a `Border` with a `Canvas` for the children at their + offsets, `TextBlock`, `Ellipse`, `Image`), fixed sizes. Still to do: auto layout (`AutoLayout` panels), variables as theme resources, + components, variants and code connect for Uno, a folder export that writes the asset files. - **Landed (2026-10-30):** `figcraft-cli connect publish [--mappings figcraft.connect.json] [--dry-run]` publishes a code repository's mappings to a design file, so code owners keep them with the code and publish them from CI ([cli.md](cli.md)). diff --git a/docs/mcp.md b/docs/mcp.md index c032b93ab..a67ae432e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1764,6 +1764,18 @@ permissions: without it nothing is downloaded); `plugin.directory.publish {path are snake_case, Dart enum members lowerCamel; names that would shadow framework types get one too, `Text` → `TextComponent`). `inspect.componentCode {id?, language?}` returns the parts: `{component, name, set, properties: [{name, param, type, default, value? (instances)}], definition, usage? (instances)}`. +- **Uno C# Markup:** `inspect.code {id, language: uno}` (aliases `csharp-markup`, `cs-markup`) writes the layer and its subtree as a + `UserControl` class (file-scoped `namespace MyApp;`, the class named after the layer plus `View`, internal) whose `this.Content(…)` is a + Uno C# Markup (`Uno.Extensions.Markup`) expression: a frame, group or rectangle is a `Border` with `Background`, `BorderBrush`, + `BorderThickness` (a `Thickness` for per-side strokes), `CornerRadius` (per corner when they differ), `Opacity` and a + `RenderTransform` for rotation, holding a `Canvas` whose children carry `.Canvas(left:, top:)`; with a stroke and children it is a + `Grid` with the border behind the canvas. Text is a `TextBlock` (`FontFamily`, `FontSize`, `FontWeight`, `FontStyle`, `Foreground`, + `LineHeight`, `CharacterSpacing` in thousandths of an em, `TextAlignment`, `TextWrapping`, `TextTrimming`, `MaxLines`, + `TextDecorations`; case is applied at run time; style runs are `Inlines` of `Run`s). Vectors and other shapes are an `Image` on + `ms-appx:///Assets/.svg`, image fills an `ImageBrush` on `.png` (names lowercase ASCII, unique in the snippet; the files + are not written). Everything has a fixed size. Shadows, blurs, blend modes, masks, gradients beyond the first stop, pattern fills, + stroke alignment other than inside, corner smoothing and arcs are `// not mapped: …` comments. Components and instances are written + as the frames they are; `inspect.componentCode` and code connect do not take `uno` yet. - **Code connect:** link a component (a variant links its set) to the code component it is built as, per language (`react`, `leptos`, `vue`, `swiftui`, `compose`, `arkui`, `flutter`): `codeConnect.set {id?, language?, importPath?, name?, template?}` (undoable; fields left out keep their value; the defaults are the generated diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f7f1d7054..fee73d720 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -626,7 +626,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th toolbar with flyouts and mode switcher, Design / Prototype / Inspect panels (Dev Mode: properties with their styles and variables, annotations with pinned properties and categories drawn as coloured callouts on the canvas (filtered by category), a ready-for-dev list, a focus view on one frame with previous / next, Compare changes since a frame - was marked ready (before / after side by side or overlaid, property-level diffs), CSS/HTML/React/Vue/Leptos/SwiftUI/Compose/ArkUI/Flutter + was marked ready (before / after side by side or overlaid, property-level diffs), CSS/HTML/React/Vue/Leptos/SwiftUI/Compose/ArkUI/Flutter/Uno C# Markup code where components take their properties as parameters and instances are calls, components connected to their code components showing the real snippet, read-only plugins), colour picker (HSB square, hue/alpha, hex, gradient stops, image fills), main menu generated from the catalog, From a2926ee8ea55bb4b26d270259152e514f3ecc9bc Mon Sep 17 00:00:00 2001 From: Andrej Skvorc Date: Tue, 10 Nov 2026 10:19:08 +0100 Subject: [PATCH 16/48] M6: contributors: add own entry for andrejskvorc --- contributors/people.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 34f849ed7..0f7eb6aed 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -118,3 +118,7 @@ real_name = "Ashok Ram" [people.GiovanniBot] sync_github_name = true + +[people.andrejskvorc] +real_name = "Andrej Skvorc" +sync_github_name = true From d63aa8a9b7a80e860a8d189d89b0eccf21c3aaf9 Mon Sep 17 00:00:00 2001 From: Andrej Skvorc Date: Thu, 12 Nov 2026 22:13:13 +0100 Subject: [PATCH 17/48] M6: Uno auto layout: AutoLayout panels A frame with horizontal or vertical auto layout is a Toolkit AutoLayout that takes the box itself: orientation, spacing, padding less the stroke weight, primary and counter axis alignment, space between. Space around and evenly and baseline alignment are notes. Frames without auto layout keep the Canvas, with one warning per view that counts them. --- crates/engine/src/dev/codegen/uno.rs | 158 ++++++++++++++++++++++--- crates/engine/src/uno_codegen_tests.rs | 144 +++++++++++++++++++++- 2 files changed, 283 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/dev/codegen/uno.rs b/crates/engine/src/dev/codegen/uno.rs index 14d06050b..939a9b56e 100644 --- a/crates/engine/src/dev/codegen/uno.rs +++ b/crates/engine/src/dev/codegen/uno.rs @@ -7,8 +7,8 @@ use std::collections::BTreeSet; use figcraft_color::{BlendMode, Color, ImageScaleMode, PaintKind}; use figcraft_doc::{ - Document, EffectKind, LetterSpacing, LineHeight, Node, NodeId, NodeKind, StrokeAlign, TextAlignH, TextAlignV, TextAutoResize, TextCase, TextData, - TextDecoration, TextStyle, + AutoLayout, CrossAlign, Document, EffectKind, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, StrokeAlign, TextAlignH, + TextAlignV, TextAutoResize, TextCase, TextData, TextDecoration, TextStyle, }; use super::swift::one_line; @@ -269,11 +269,21 @@ impl Element { } } +/// Where a child sits in its parent: at an offset in a `Canvas`, or wherever the parent's flow +/// (an `AutoLayout`) puts it. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Place { + Flow, + At(f64, f64), +} + /// What a tree walk keeps between layers. struct Gen<'a> { ctx: &'a Ctx<'a>, /// Asset names given out, so no two layers share a file. assets: BTreeSet, + /// Frames written as a `Canvas` for lack of auto layout (one warning per view says how many). + free_frames: usize, } /// Uno C# Markup for layer `id` and its subtree: a `UserControl` class whose content is the tree. @@ -281,14 +291,24 @@ pub(crate) fn uno(doc: &Document, id: NodeId) -> String { let Some(root) = doc.node(id) else { return String::new() }; // The tree sits three levels in: namespace member, constructor body, `Content(` argument. let ctx = Ctx { base: 3, ..Ctx::new(doc, id) }; - let mut g = Gen { ctx: &ctx, assets: BTreeSet::new() }; - let body = g.layer(root, 3, None).unwrap_or_else(|| format!("{}new Border()", uno_indent(3))); + let mut g = Gen { ctx: &ctx, assets: BTreeSet::new(), free_frames: 0 }; + let mut body = g.layer(root, 3, Place::Flow).unwrap_or_else(|| format!("{}new Border()", uno_indent(3))); + if g.free_frames > 0 { + // One warning per view, above everything else written for the root layer. + let (count, verb) = if g.free_frames == 1 { + ("1 frame has".to_string(), "its children are") + } else { + (format!("{} frames have", g.free_frames), "children are") + }; + body = format!("{}// warning: {count} no auto layout: {verb} positioned absolutely and do not adapt to size.\n{body}", uno_indent(3)); + } let mut out = String::new(); let usings: Vec<&str> = [ ("using Microsoft.UI.Text;", "FontWeights."), ("using Windows.Foundation;", "new Rect("), ("using Windows.UI;", "Color.FromArgb("), ("using Windows.UI.Text;", "FontStyle."), + ("using Uno.Toolkit.UI;", "new AutoLayout("), ] .into_iter() .filter(|(_, marker)| body.contains(marker)) @@ -313,9 +333,9 @@ pub(crate) fn uno(doc: &Document, id: NodeId) -> String { } impl Gen<'_> { - /// A layer and its subtree at `depth`, placed in a `Canvas` at `at`. `None` for a layer that - /// draws nothing. - fn layer(&mut self, n: &Node, depth: usize, at: Option<(f64, f64)>) -> Option { + /// A layer and its subtree at `depth`, placed in its parent as `at` says. `None` for a layer + /// that draws nothing. + fn layer(&mut self, n: &Node, depth: usize, at: Place) -> Option { if matches!(n.kind, NodeKind::Slice) { return None; } @@ -332,10 +352,72 @@ impl Gen<'_> { Some(e.write(depth)) } - /// A frame-like layer, group or rectangle: a `Border` with its fill, stroke and corners holding - /// a `Canvas` with the children at their offsets. With a stroke and children the border sits - /// behind the canvas in a `Grid`, since a `Border` pushes its content in by its thickness. - fn boxed(&mut self, n: &Node, depth: usize, at: Option<(f64, f64)>) -> Element { + /// A frame-like layer, group or rectangle. Horizontal and vertical auto layout is an + /// `AutoLayout`; anything else is a `Border` holding a `Canvas` with the children at their + /// offsets. + fn boxed(&mut self, n: &Node, depth: usize, at: Place) -> Element { + match n.layout.as_ref() { + Some(l) if matches!(l.mode, LayoutMode::Horizontal | LayoutMode::Vertical) && !matches!(n.kind, NodeKind::Rectangle) => { + self.auto_layout(n, l, depth, at) + } + _ => self.canvas_box(n, depth, at), + } + } + + /// A frame with horizontal or vertical auto layout: an `AutoLayout` that takes the box + /// (fill, border, corners) itself. A `Border` pushes its content in by its thickness, so + /// the padding is written less the stroke weight, as FigCraft's layout ignores strokes (unless + /// they are included). Where that would be negative the border sits behind the layout in a + /// `Grid`, as for a frame without auto layout. + fn auto_layout(&mut self, n: &Node, l: &AutoLayout, depth: usize, at: Place) -> Element { + let [pt, pr, pb, pl] = l.padding; + let weights = match (stroke_color(n), n.stroke.sides) { + (None, _) => [0.0; 4], + (Some(_), Some(s)) => s, + (Some(_), None) => [n.stroke.weight; 4], + }; + let weights = if l.strokes_included { [0.0; 4] } else { weights }; + let pad = [pt - weights[0], pr - weights[1], pb - weights[2], pl - weights[3]]; + let behind = pad.iter().any(|p| *p < 0.0); + let mut line = Element::new("new AutoLayout()"); + let mut exprs: Vec = Vec::new(); + for k in self.ctx.kids(n).iter().take(MAX_CHILDREN) { + let Some(c) = self.ctx.doc.node(*k) else { continue }; + exprs.extend(self.layer(c, depth + if behind { 4 } else { 2 }, Place::Flow)); + } + if !exprs.is_empty() { + line.kids = Some(("Children", exprs)); + } + let mut outer; + if behind { + // The layout inside keeps the whole padding; the border is drawn behind it. + let mut border = Element::new("new Border()"); + self.paint_box(&mut border, n, false); + layout_calls(&mut line, l, [pt, pr, pb, pl]); + outer = Element::new("new Grid()"); + place(&mut outer, at); + size(&mut outer, n); + outer.kids = Some(("Children", vec![border.write(depth + 2), line.write(depth + 2)])); + common(&mut outer, n); + } else { + outer = line; + place(&mut outer, at); + size(&mut outer, n); + self.paint_box(&mut outer, n, false); + layout_calls(&mut outer, l, pad); + common(&mut outer, n); + } + if n.clip && n.corners.radii.iter().all(|r| *r <= 0.0) && !n.children.is_empty() { + outer.call(format!(".Clip(new RectangleGeometry().Rect(new Rect(0, 0, {}, {})))", num(n.width), num(n.height))); + } + outer + } + + /// A frame-like layer, group or rectangle without a layout of its own to map: a `Border` + /// with its fill, stroke and corners holding a `Canvas` with the children at their offsets. + /// With a stroke and children the border sits behind the canvas in a `Grid`, since a `Border` + /// pushes its content in by its thickness. + fn canvas_box(&mut self, n: &Node, depth: usize, at: Place) -> Element { let mut border = Element::new("new Border()"); let sized = !matches!(n.kind, NodeKind::Group | NodeKind::Section { .. }); self.paint_box(&mut border, n, sized); @@ -343,12 +425,15 @@ impl Gen<'_> { for k in self.ctx.kids(n).iter().take(MAX_CHILDREN) { let Some(c) = self.ctx.doc.node(*k) else { continue }; let [_, _, _, _, x, y] = c.transform.as_coeffs(); - exprs.extend(self.layer(c, depth + 4, Some((x, y)))); + exprs.extend(self.layer(c, depth + 4, Place::At(x, y))); } let mut canvas = Element::new("new Canvas()"); let has_kids = !exprs.is_empty(); if has_kids { canvas.kids = Some(("Children", exprs)); + if n.layout.is_none() { + self.free_frames += 1; + } } let mut outer; if has_kids && stroke_color(n).is_some() { @@ -366,6 +451,9 @@ impl Gen<'_> { } common(&mut outer, n); } + if n.layout.as_ref().is_some_and(|l| l.mode == LayoutMode::Grid) { + outer.note("grid auto layout (children are positioned absolutely)"); + } if n.clip && has_kids && n.corners.radii.iter().all(|r| *r <= 0.0) { outer.call(format!(".Clip(new RectangleGeometry().Rect(new Rect(0, 0, {}, {})))", num(n.width), num(n.height))); } @@ -434,7 +522,7 @@ impl Gen<'_> { } /// An ellipse: `Ellipse` with `Fill` and a centred `Stroke`. - fn ellipse(&mut self, n: &Node, (start, sweep, inner): (f64, f64, f64), at: Option<(f64, f64)>) -> Element { + fn ellipse(&mut self, n: &Node, (start, sweep, inner): (f64, f64, f64), at: Place) -> Element { let mut e = Element::new("new Ellipse()"); place(&mut e, at); size(&mut e, n); @@ -456,7 +544,7 @@ impl Gen<'_> { } /// A vector, shape or other layer without a counterpart: the image the app is to hold. - fn asset(&mut self, n: &Node, at: Option<(f64, f64)>) -> Element { + fn asset(&mut self, n: &Node, at: Place) -> Element { let name = asset_name(&n.name, n.kind.label(), &mut self.assets); let mut e = Element::new("new Image()"); e.lead.push(format!("// {} \"{}\": export it as an SVG to Assets/{name}.svg", n.kind.label(), comment_name(&n.name))); @@ -470,7 +558,7 @@ impl Gen<'_> { /// Text: a `TextBlock`, in a `Grid` of the box's height when it is aligned to the middle or /// bottom of a fixed box. - fn text(&mut self, n: &Node, t: &TextData, depth: usize, at: Option<(f64, f64)>) -> Element { + fn text(&mut self, n: &Node, t: &TextData, depth: usize, at: Place) -> Element { let fixed = matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Truncate); let framed = fixed && t.align_v != TextAlignV::Top; let mut tb = text_block(n, t, !framed); @@ -489,14 +577,48 @@ impl Gen<'_> { } } -/// The `Canvas` offsets of a child at `at`. -fn place(e: &mut Element, at: Option<(f64, f64)>) { - if let Some((x, y)) = at { +/// The `Canvas` offsets of a child at `at`; a child in a flow carries nothing. +fn place(e: &mut Element, at: Place) { + if let Place::At(x, y) = at { // The offsets come first in the chain: they read as the element's address. e.calls.insert(0, format!(".Canvas(left: {}, top: {})", num(x), num(y))); } } +/// The calls an `AutoLayout` takes for its orientation, gap, padding (`pad` is top, right, +/// bottom, left as written) and alignment. +fn layout_calls(e: &mut Element, l: &AutoLayout, pad: [f64; 4]) { + e.call(format!(".Orientation(Orientation.{})", if l.mode == LayoutMode::Vertical { "Vertical" } else { "Horizontal" })); + // The space distributions make the gaps themselves. + if l.gap != 0.0 && !l.main_align.is_auto_gap() { + e.call(format!(".Spacing({})", num(l.gap))); + } + let [t, r, b, lf] = pad; + if [t, r, b, lf].iter().any(|p| *p != 0.0) { + if t == r && r == b && b == lf { + e.call(format!(".Padding({})", num(t))); + } else { + e.call(format!(".Padding({}, {}, {}, {})", num(lf), num(t), num(r), num(b))); + } + } + match l.main_align { + MainAlign::Min => {} + MainAlign::Center => e.call(".PrimaryAxisAlignment(AutoLayoutAlignment.Center)"), + MainAlign::Max => e.call(".PrimaryAxisAlignment(AutoLayoutAlignment.End)"), + MainAlign::SpaceBetween => e.call(".Justify(AutoLayoutJustify.SpaceBetween)"), + MainAlign::SpaceAround | MainAlign::SpaceEvenly => { + e.call(".Justify(AutoLayoutJustify.SpaceBetween)"); + e.note("space around/evenly exported as space between"); + } + } + match l.cross_align { + CrossAlign::Min => {} + CrossAlign::Center => e.call(".CounterAxisAlignment(AutoLayoutAlignment.Center)"), + CrossAlign::Max => e.call(".CounterAxisAlignment(AutoLayoutAlignment.End)"), + CrossAlign::Baseline => e.note("baseline alignment (children are aligned to the start)"), + } +} + /// The layer's fixed width and height. fn size(e: &mut Element, n: &Node) { e.call(format!(".Width({})", num(n.width))); diff --git a/crates/engine/src/uno_codegen_tests.rs b/crates/engine/src/uno_codegen_tests.rs index 35e93b7ea..e1a578a62 100644 --- a/crates/engine/src/uno_codegen_tests.rs +++ b/crates/engine/src/uno_codegen_tests.rs @@ -81,7 +81,8 @@ fn a_frame_with_a_stroke_and_children_keeps_the_children_out_of_the_border() { let f = frame(&mut s, "Login Screen", 200.0, 100.0); set(&mut s, f, json!({"fill": "#112233", "stroke": "#FF0000", "strokeWeight": 3, "opacity": 0.5, "cornerRadius": 8})); ex(&mut s, "shape.rectangle", json!({"x": 5, "y": 5, "width": 20, "height": 20, "parent": f, "props": {"name": "Box"}})); - let expected = "new Grid() + let expected = "// warning: 1 frame has no auto layout: its children are positioned absolutely and do not adapt to size. +new Grid() .Width(200) .Height(100) .Opacity(0.5) @@ -334,3 +335,144 @@ fn instances_and_components_are_walked_as_frames() { assert!(code.contains("internal sealed partial class CardView : UserControl"), "{code}"); assert!(!code.contains("export default") && !code.contains("function "), "{code}"); } + +/// The body of a view with the class shell and its indent taken off. +fn body(code: &str) -> String { + tree(code).lines().map(|l| format!("{}\n", l.get(12..).unwrap_or(l))).collect::().trim_end().to_string() +} + +fn rect(s: &mut Session, parent: NodeId, w: f64, h: f64, name: &str) -> NodeId { + idv(&ex(s, "shape.rectangle", json!({"parent": parent, "x": 0, "y": 0, "width": w, "height": h, "props": {"name": name, "fill": "#FF0000"}}))) +} + +/// A frame with auto layout and one rectangle child. +fn row(s: &mut Session, props: serde_json::Value) -> NodeId { + let f = frame(s, "Row", 200.0, 100.0); + let mut all = json!({"layout": "horizontal", "padding": 0, "gap": 0, "fills": [], "sizingH": "fixed", "sizingV": "fixed"}); + if let (Some(all), serde_json::Value::Object(extra)) = (all.as_object_mut(), props) { + all.extend(extra); + } + set(s, f, all); + rect(s, f, 20.0, 20.0, "A"); + f +} + +#[test] +fn a_row_is_an_auto_layout_with_its_box_gap_padding_and_alignment() { + let mut s = Session::new(); + let f = row( + &mut s, + json!({"fills": ["#112233"], "gap": 12, "padding": [7, 15, 7, 15], "mainAlign": "center", "crossAlign": "center", "cornerRadius": 8}), + ); + rect(&mut s, f, 20.0, 20.0, "B"); + let code = uno(&mut s, f); + assert!(code.starts_with("using Windows.UI;\nusing Uno.Toolkit.UI;\n") || code.contains("using Uno.Toolkit.UI;"), "{code}"); + let expected = "new AutoLayout() + .Width(200) + .Height(100) + .Background(Color.FromArgb(0xFF, 0x11, 0x22, 0x33)) + .CornerRadius(8) + .Orientation(Orientation.Horizontal) + .Spacing(12) + .Padding(15, 7, 15, 7) + .PrimaryAxisAlignment(AutoLayoutAlignment.Center) + .CounterAxisAlignment(AutoLayoutAlignment.Center) + .Children( + new Border() + .Width(20) + .Height(20) + .Background(Color.FromArgb(0xFF, 0xFF, 0x00, 0x00)), + new Border() + .Width(20) + .Height(20) + .Background(Color.FromArgb(0xFF, 0xFF, 0x00, 0x00)))"; + assert_eq!(body(&code), expected, "{code}"); + // A frame with auto layout is not a frame without one: no warning. + assert!(!code.contains("// warning"), "{code}"); +} + +#[test] +fn a_column_has_a_vertical_orientation_and_a_uniform_padding_is_one_number() { + let mut s = Session::new(); + let f = row(&mut s, json!({"layout": "vertical", "padding": 8, "gap": 0})); + let code = uno(&mut s, f); + assert!(code.contains(".Orientation(Orientation.Vertical)\n"), "{code}"); + assert!(code.contains(".Padding(8)\n"), "{code}"); + assert!(!code.contains(".Spacing("), "no gap, no spacing: {code}"); + set(&mut s, f, json!({"padding": 0})); + assert!(!uno(&mut s, f).contains(".Padding(")); +} + +#[test] +fn main_and_cross_alignment_map_with_notes_for_what_the_toolkit_lacks() { + let mut s = Session::new(); + let f = row(&mut s, json!({"gap": 5})); + for (main, line) in [("max", ".PrimaryAxisAlignment(AutoLayoutAlignment.End)"), ("spaceBetween", ".Justify(AutoLayoutJustify.SpaceBetween)")] { + set(&mut s, f, json!({"mainAlign": main})); + let code = uno(&mut s, f); + assert!(code.contains(line), "{main}: {code}"); + assert!(!code.contains("// not mapped"), "{main}: {code}"); + } + // The distributions make the gaps: the gap value is not written. + assert!(!uno(&mut s, f).contains(".Spacing(")); + for main in ["spaceAround", "spaceEvenly"] { + set(&mut s, f, json!({"mainAlign": main})); + let code = uno(&mut s, f); + assert!( + code.contains(".Justify(AutoLayoutJustify.SpaceBetween)") + && code.contains("// not mapped: space around/evenly exported as space between"), + "{code}" + ); + } + set(&mut s, f, json!({"mainAlign": "min", "crossAlign": "max"})); + assert!(uno(&mut s, f).contains(".CounterAxisAlignment(AutoLayoutAlignment.End)")); + set(&mut s, f, json!({"crossAlign": "baseline"})); + let code = uno(&mut s, f); + assert!(!code.contains("CounterAxisAlignment") && code.contains("// not mapped: baseline alignment"), "{code}"); +} + +#[test] +fn the_stroke_weight_comes_off_the_padding_unless_strokes_are_included() { + let mut s = Session::new(); + let f = row(&mut s, json!({"padding": 10, "stroke": "#0000FF", "strokeWeight": 4, "strokeAlign": "inside", "strokesIncluded": false})); + let code = uno(&mut s, f); + assert!(code.contains(".BorderThickness(4)") && code.contains(".Padding(6)\n"), "{code}"); + assert!(!code.contains("new Grid()"), "{code}"); + set(&mut s, f, json!({"strokesIncluded": true})); + assert!(uno(&mut s, f).contains(".Padding(10)\n")); + // A stroke thicker than the padding on a side: the border sits behind the layout. + set(&mut s, f, json!({"strokesIncluded": false, "padding": 2})); + let code = uno(&mut s, f); + assert!(code.contains("new Grid()") && code.contains("new Border()") && code.contains(".Padding(2)\n"), "{code}"); + let (grid, layout) = (code.find("new Grid()"), code.find("new AutoLayout()")); + assert!(grid < layout, "{code}"); + assert!(!code[layout.unwrap_or(0)..].contains(".BorderThickness("), "{code}"); +} + +#[test] +fn frames_without_auto_layout_get_one_warning_per_view_with_their_count() { + let mut s = Session::new(); + let outer = frame(&mut s, "Free", 200.0, 200.0); + for name in ["One", "Two"] { + let inner = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50, "parent": outer, "name": name}))); + rect(&mut s, inner, 10.0, 10.0, "R"); + } + let code = uno(&mut s, outer); + assert_eq!(code.matches("// warning:").count(), 1, "{code}"); + assert!(code.contains("// warning: 3 frames have no auto layout: children are positioned absolutely and do not adapt to size."), "{code}"); + // An empty frame has no children to place: nothing to warn about. + let empty = frame(&mut s, "Empty2", 10.0, 10.0); + assert!(!uno(&mut s, empty).contains("// warning")); +} + +#[test] +fn nested_auto_layouts_carry_no_canvas_offsets() { + let mut s = Session::new(); + let outer = row(&mut s, json!({"layout": "vertical"})); + let inner = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50, "parent": outer, "name": "Inner"}))); + set(&mut s, inner, json!({"layout": "horizontal", "padding": 3, "gap": 2})); + rect(&mut s, inner, 5.0, 5.0, "C"); + let code = uno(&mut s, outer); + assert_eq!(code.matches("new AutoLayout()").count(), 2, "{code}"); + assert!(!code.contains(".Canvas("), "{code}"); +} From 1c3924a978b7d51c66c0a0ca24fc06d6e7935fb9 Mon Sep 17 00:00:00 2001 From: Andrej Skvorc Date: Fri, 13 Nov 2026 17:37:39 +0100 Subject: [PATCH 18/48] M6: Uno code: add children with Children.Add and Child = Fluent .Children(...) and .Child(...) double the load time with every level of nesting. Each element is now a local with fluent property setters; its children are added with Children.Add(x) or Child = x, and the view sets Content = root. A test pins that no output has .Children( or .Child(. --- crates/engine/src/dev/codegen/uno.rs | 140 ++++++++++++++-------- crates/engine/src/uno_codegen_tests.rs | 154 ++++++++++++++++--------- 2 files changed, 196 insertions(+), 98 deletions(-) diff --git a/crates/engine/src/dev/codegen/uno.rs b/crates/engine/src/dev/codegen/uno.rs index 939a9b56e..6dd876bd7 100644 --- a/crates/engine/src/dev/codegen/uno.rs +++ b/crates/engine/src/dev/codegen/uno.rs @@ -184,7 +184,6 @@ pub(crate) fn cs_ident(name: &str, pascal: bool, kind: &str) -> String { } /// `base` made unique among `used` (C# names are case-sensitive): `Card`, `Card2`, `Card3`, …. -#[cfg_attr(not(test), allow(dead_code, reason = "names of component members (U3)"))] pub(crate) fn cs_unique(base: &str, used: &mut BTreeSet) -> String { let name = (1usize..) .map(|k| if k == 1 { base.to_string() } else { format!("{base}{k}") }) @@ -227,19 +226,23 @@ fn comment_name(name: &str) -> String { if cut.chars().count() < one.chars().count() { format!("{cut}…") } else { cut } } -/// One element of the tree before it is written: comment lines above it, its constructor, the -/// chain of property calls (a call starting with `//` is a comment line) and its children. +/// One element of the tree before it is written: comment lines above it, the local it is held +/// in, its constructor, the chain of property calls (a call starting with `//` is a comment +/// line) and its children. Children are added with `Children.Add(x)` or `Child = x`, never with +/// the fluent `.Children(…)` / `.Child(…)`, whose load time doubles with every level of nesting. struct Element { lead: Vec, + var: String, ctor: String, calls: Vec, - /// `Child` (one) or `Children` (several) and the child expressions, written two levels in. - kids: Option<(&'static str, Vec)>, + /// `Child` (a single child, assigned) or `Children` (added one by one), and the children. + adds: &'static str, + kids: Vec, } impl Element { fn new(ctor: &str) -> Self { - Element { lead: Vec::new(), ctor: ctor.to_string(), calls: Vec::new(), kids: None } + Element { lead: Vec::new(), var: String::new(), ctor: ctor.to_string(), calls: Vec::new(), adds: "Children", kids: Vec::new() } } fn call(&mut self, c: impl Into) { @@ -250,23 +253,46 @@ impl Element { self.calls.push(format!("// not mapped: {what}")); } - /// The element written at `depth`: a complete expression, no trailing newline. - fn write(&self, depth: usize) -> String { + /// The constructor and the chain at `depth`, as an expression without a trailing newline. + fn expr(&self, depth: usize) -> String { let (pad, inner) = (uno_indent(depth), uno_indent(depth + 1)); - let mut out = String::new(); - for l in &self.lead { - out.push_str(&format!("{pad}{l}\n")); - } - out.push_str(&format!("{pad}{}", self.ctor)); + let mut out = format!("{pad}{}", self.ctor); for c in &self.calls { // A call of several lines is indented relative to its first. out.push_str(&format!("\n{inner}{}", c.replace('\n', &format!("\n{inner}")))); } - if let Some((method, kids)) = &self.kids { - out.push_str(&format!("\n{inner}.{method}(\n{})", kids.join(",\n"))); - } out } + + /// The statements for this element and its subtree at `depth`: its comment lines, the + /// declaration of its local, then each child's statements followed by the line that adds it. + fn write(&self, depth: usize, out: &mut String) { + let (pad, inner) = (uno_indent(depth), uno_indent(depth + 1)); + for l in &self.lead { + out.push_str(&format!("{pad}{l}\n")); + } + out.push_str(&format!("{pad}var {} = {}", self.var, self.ctor)); + // The semicolon ends the last call, not a `// not mapped` comment after it. + let last = self.calls.iter().rposition(|c| !c.starts_with("//")); + if last.is_none() { + out.push(';'); + } + for (i, c) in self.calls.iter().enumerate() { + out.push_str(&format!("\n{inner}{}", c.replace('\n', &format!("\n{inner}")))); + if last == Some(i) { + out.push(';'); + } + } + out.push('\n'); + for k in &self.kids { + k.write(depth, out); + if self.adds == "Child" { + out.push_str(&format!("{pad}{}.Child = {};\n", self.var, k.var)); + } else { + out.push_str(&format!("{pad}{}.Children.Add({});\n", self.var, k.var)); + } + } + } } /// Where a child sits in its parent: at an offset in a `Canvas`, or wherever the parent's flow @@ -284,15 +310,23 @@ struct Gen<'a> { assets: BTreeSet, /// Frames written as a `Canvas` for lack of auto layout (one warning per view says how many). free_frames: usize, + /// The names of the locals given out. + names: BTreeSet, } /// Uno C# Markup for layer `id` and its subtree: a `UserControl` class whose content is the tree. pub(crate) fn uno(doc: &Document, id: NodeId) -> String { let Some(root) = doc.node(id) else { return String::new() }; - // The tree sits three levels in: namespace member, constructor body, `Content(` argument. - let ctx = Ctx { base: 3, ..Ctx::new(doc, id) }; - let mut g = Gen { ctx: &ctx, assets: BTreeSet::new(), free_frames: 0 }; - let mut body = g.layer(root, 3, Place::Flow).unwrap_or_else(|| format!("{}new Border()", uno_indent(3))); + let ctx = Ctx::new(doc, id); + let mut g = Gen { ctx: &ctx, assets: BTreeSet::new(), free_frames: 0, names: BTreeSet::new() }; + let mut top = match g.layer(root, 0, Place::Flow) { + Some(e) => e, + None => { + let mut e = Element::new("new Border()"); + e.var = "root".into(); + e + } + }; if g.free_frames > 0 { // One warning per view, above everything else written for the root layer. let (count, verb) = if g.free_frames == 1 { @@ -300,8 +334,12 @@ pub(crate) fn uno(doc: &Document, id: NodeId) -> String { } else { (format!("{} frames have", g.free_frames), "children are") }; - body = format!("{}// warning: {count} no auto layout: {verb} positioned absolutely and do not adapt to size.\n{body}", uno_indent(3)); + top.lead.insert(0, format!("// warning: {count} no auto layout: {verb} positioned absolutely and do not adapt to size.")); } + // The statements sit two levels in: namespace member, constructor body. + let mut body = String::new(); + top.write(2, &mut body); + body.push_str(&format!("{}Content = {};\n", uno_indent(2), top.var)); let mut out = String::new(); let usings: Vec<&str> = [ ("using Microsoft.UI.Text;", "FontWeights."), @@ -328,28 +366,40 @@ pub(crate) fn uno(doc: &Document, id: NodeId) -> String { } out.push_str(&format!("// {}\nnamespace MyApp;\n\n", comment_name(&root.name))); out.push_str(&format!("internal sealed partial class {name} : UserControl\n{{\n")); - out.push_str(&format!(" public {name}()\n {{\n this.Content(\n{body});\n }}\n}}\n")); + out.push_str(&format!(" public {name}()\n {{\n{body} }}\n}}\n")); out } impl Gen<'_> { - /// A layer and its subtree at `depth`, placed in its parent as `at` says. `None` for a layer - /// that draws nothing. - fn layer(&mut self, n: &Node, depth: usize, at: Place) -> Option { + /// A local name from a layer name, unique in the view (`card`, `card2`, …). + fn fresh(&mut self, name: &str, kind: &str) -> String { + let base = cs_ident(name, false, kind); + cs_unique(&base, &mut self.names) + } + + /// A layer and its subtree at `depth` (levels of nesting), placed in its parent as `at` says. + /// `None` for a layer that draws nothing. + fn layer(&mut self, n: &Node, depth: usize, at: Place) -> Option { if matches!(n.kind, NodeKind::Slice) { return None; } + // The parent's name comes before its children's. + let var = self.fresh(&n.name, n.kind.label()); if self.ctx.too_deep(depth) { - return Some(format!("{pad}// {} …\n{pad}new Border()", comment_name(&n.name), pad = uno_indent(depth))); + let mut e = Element::new("new Border()"); + e.lead.push(format!("// {} …", comment_name(&n.name))); + e.var = var; + return Some(e); } - let e = match &n.kind { - NodeKind::Text(t) => self.text(n, t, depth, at), + let mut e = match &n.kind { + NodeKind::Text(t) => self.text(n, t, at), NodeKind::Ellipse { start, sweep, inner } => self.ellipse(n, (*start, *sweep, *inner), at), NodeKind::Rectangle | NodeKind::Group | NodeKind::Section { .. } => self.boxed(n, depth, at), k if k.is_frame_like() => self.boxed(n, depth, at), _ => self.asset(n, at), }; - Some(e.write(depth)) + e.var = var; + Some(e) } /// A frame-like layer, group or rectangle. Horizontal and vertical auto layout is an @@ -380,13 +430,9 @@ impl Gen<'_> { let pad = [pt - weights[0], pr - weights[1], pb - weights[2], pl - weights[3]]; let behind = pad.iter().any(|p| *p < 0.0); let mut line = Element::new("new AutoLayout()"); - let mut exprs: Vec = Vec::new(); for k in self.ctx.kids(n).iter().take(MAX_CHILDREN) { let Some(c) = self.ctx.doc.node(*k) else { continue }; - exprs.extend(self.layer(c, depth + if behind { 4 } else { 2 }, Place::Flow)); - } - if !exprs.is_empty() { - line.kids = Some(("Children", exprs)); + line.kids.extend(self.layer(c, depth + 1, Place::Flow)); } let mut outer; if behind { @@ -397,7 +443,9 @@ impl Gen<'_> { outer = Element::new("new Grid()"); place(&mut outer, at); size(&mut outer, n); - outer.kids = Some(("Children", vec![border.write(depth + 2), line.write(depth + 2)])); + border.var = self.fresh(&format!("{} border", n.name), "border"); + line.var = self.fresh(&format!("{} layout", n.name), "layout"); + outer.kids = vec![border, line]; common(&mut outer, n); } else { outer = line; @@ -421,16 +469,15 @@ impl Gen<'_> { let mut border = Element::new("new Border()"); let sized = !matches!(n.kind, NodeKind::Group | NodeKind::Section { .. }); self.paint_box(&mut border, n, sized); - let mut exprs: Vec = Vec::new(); + let mut canvas = Element::new("new Canvas()"); for k in self.ctx.kids(n).iter().take(MAX_CHILDREN) { let Some(c) = self.ctx.doc.node(*k) else { continue }; let [_, _, _, _, x, y] = c.transform.as_coeffs(); - exprs.extend(self.layer(c, depth + 4, Place::At(x, y))); + canvas.kids.extend(self.layer(c, depth + 1, Place::At(x, y))); } - let mut canvas = Element::new("new Canvas()"); - let has_kids = !exprs.is_empty(); + let has_kids = !canvas.kids.is_empty(); if has_kids { - canvas.kids = Some(("Children", exprs)); + canvas.var = self.fresh(&format!("{} canvas", n.name), "canvas"); if n.layout.is_none() { self.free_frames += 1; } @@ -441,13 +488,15 @@ impl Gen<'_> { place(&mut outer, at); size(&mut outer, n); border.calls.retain(|c| !c.starts_with(".Width(") && !c.starts_with(".Height(")); - outer.kids = Some(("Children", vec![border.write(depth + 2), canvas.write(depth + 2)])); + border.var = self.fresh(&format!("{} border", n.name), "border"); + outer.kids = vec![border, canvas]; common(&mut outer, n); } else { outer = border; place(&mut outer, at); if has_kids { - outer.kids = Some(("Child", vec![canvas.write(depth + 2)])); + outer.adds = "Child"; + outer.kids = vec![canvas]; } common(&mut outer, n); } @@ -558,7 +607,7 @@ impl Gen<'_> { /// Text: a `TextBlock`, in a `Grid` of the box's height when it is aligned to the middle or /// bottom of a fixed box. - fn text(&mut self, n: &Node, t: &TextData, depth: usize, at: Place) -> Element { + fn text(&mut self, n: &Node, t: &TextData, at: Place) -> Element { let fixed = matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Truncate); let framed = fixed && t.align_v != TextAlignV::Top; let mut tb = text_block(n, t, !framed); @@ -571,7 +620,8 @@ impl Gen<'_> { let mut g = Element::new("new Grid()"); place(&mut g, at); size(&mut g, n); - g.kids = Some(("Children", vec![tb.write(depth + 2)])); + tb.var = self.fresh(&format!("{} text", n.name), "text"); + g.kids = vec![tb]; common(&mut g, n); g } @@ -767,7 +817,7 @@ fn text_block(n: &Node, t: &TextData, with_height: bool) -> Element { if !plain { style_calls(&mut r, style, fills, Some((s, fill))); } - pieces.push(r.write(1)); + pieces.push(r.expr(1)); }; for r in &runs { let (start, end) = (r.start.max(at), r.end.min(chars.len())); diff --git a/crates/engine/src/uno_codegen_tests.rs b/crates/engine/src/uno_codegen_tests.rs index e1a578a62..088cc9576 100644 --- a/crates/engine/src/uno_codegen_tests.rs +++ b/crates/engine/src/uno_codegen_tests.rs @@ -42,13 +42,31 @@ fn set(s: &mut Session, id: NodeId, props: serde_json::Value) { ex(s, "node.set", json!({"id": id, "props": props})); } -/// The body of the generated class: what sits inside `this.Content(` … `);`. +/// The statements of the generated constructor, as written (eight spaces of indent): what sits +/// between `public XView()` `{` and its closing brace. fn tree(code: &str) -> String { - let start = code.find("this.Content(\n").map_or(0, |i| i + "this.Content(\n".len()); - let end = code.rfind(");\n }\n}").unwrap_or(code.len()); + let start = code.find(" {\n").map_or(0, |i| i + " {\n".len()); + let end = code.rfind(" }\n}").unwrap_or(code.len()); code.get(start..end).unwrap_or_default().to_string() } +/// [`tree`] with the indent taken off. +fn body(code: &str) -> String { + tree(code).lines().map(|l| format!("{}\n", l.get(8..).unwrap_or(l))).collect::().trim_end().to_string() +} + +/// Whether `block` (lines, indent and a closing `;` ignored) appears in `code` as consecutive lines. +fn has_block(code: &str, block: &str) -> bool { + let norm = |t: &str| t.lines().map(|l| l.trim().trim_end_matches(';').to_string()).collect::>(); + let (c, b) = (norm(code), norm(block)); + !b.is_empty() && c.windows(b.len()).any(|w| w == b.as_slice()) +} + +/// Whether one line of `code` is exactly `call` (a closing `;` ignored). +fn has_call(code: &str, call: &str) -> bool { + has_block(code, call) +} + #[test] fn an_empty_frame_is_a_view_class_with_a_sized_border() { let mut s = Session::new(); @@ -62,11 +80,11 @@ internal sealed partial class EmptyView : UserControl { public EmptyView() { - this.Content( - new Border() - .Width(100) - .Height(50) - .Background(Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF))); + var empty = new Border() + .Width(100) + .Height(50) + .Background(Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF)); + Content = empty; } } "; @@ -82,27 +100,28 @@ fn a_frame_with_a_stroke_and_children_keeps_the_children_out_of_the_border() { set(&mut s, f, json!({"fill": "#112233", "stroke": "#FF0000", "strokeWeight": 3, "opacity": 0.5, "cornerRadius": 8})); ex(&mut s, "shape.rectangle", json!({"x": 5, "y": 5, "width": 20, "height": 20, "parent": f, "props": {"name": "Box"}})); let expected = "// warning: 1 frame has no auto layout: its children are positioned absolutely and do not adapt to size. -new Grid() +var loginScreen = new Grid() .Width(200) .Height(100) - .Opacity(0.5) - .Children( - new Border() - .Background(Color.FromArgb(0xFF, 0x11, 0x22, 0x33)) - .BorderBrush(Color.FromArgb(0xFF, 0xFF, 0x00, 0x00)) - .BorderThickness(3) - .CornerRadius(8), - new Canvas() - .Children( - new Border() - .Canvas(left: 5, top: 5) - .Width(20) - .Height(20) - .Background(Color.FromArgb(0xFF, 0xD9, 0xD9, 0xD9))))"; + .Opacity(0.5); +var loginScreenBorder = new Border() + .Background(Color.FromArgb(0xFF, 0x11, 0x22, 0x33)) + .BorderBrush(Color.FromArgb(0xFF, 0xFF, 0x00, 0x00)) + .BorderThickness(3) + .CornerRadius(8); +loginScreen.Children.Add(loginScreenBorder); +var loginScreenCanvas = new Canvas(); +var box = new Border() + .Canvas(left: 5, top: 5) + .Width(20) + .Height(20) + .Background(Color.FromArgb(0xFF, 0xD9, 0xD9, 0xD9)); +loginScreenCanvas.Children.Add(box); +loginScreen.Children.Add(loginScreenCanvas); +Content = loginScreen;"; let code = uno(&mut s, f); assert!(code.contains("internal sealed partial class LoginScreenView : UserControl"), "{code}"); - let body: String = tree(&code).lines().map(|l| format!("{}\n", l.get(12..).unwrap_or(l))).collect(); - assert_eq!(body.trim_end(), expected, "{code}"); + assert_eq!(body(&code), expected, "{code}"); } #[test] @@ -144,15 +163,14 @@ fn an_ellipse_is_an_ellipse_with_a_centred_stroke() { json!({"x": 10, "y": 20, "width": 40, "height": 40, "parent": f, "props": {"name": "Dot", "fill": "#FF0000", "stroke": "#000000", "strokeWeight": 2, "strokeAlign": "center"}}), ); let code = uno(&mut s, f); - let expected = "new Ellipse() + let expected = "var dot = new Ellipse() .Canvas(left: 10, top: 20) .Width(40) .Height(40) .Fill(Color.FromArgb(0xFF, 0xFF, 0x00, 0x00)) .Stroke(Color.FromArgb(0xFF, 0x00, 0x00, 0x00)) - .StrokeThickness(2)"; - let indented = expected.lines().collect::>().join("\n "); - assert!(code.contains(&indented), "{code}"); + .StrokeThickness(2);"; + assert!(has_block(&code, expected), "{code}"); } #[test] @@ -182,7 +200,7 @@ fn text_maps_its_style_and_box() { ".Width(150)", ".TextWrapping(TextWrapping.Wrap)", ] { - assert!(code.contains(&format!("{line}\n")) || code.contains(&format!("{line})")), "{line} in {code}"); + assert!(has_call(&code, line) || code.contains(&format!("{line})")), "{line} in {code}"); } // Auto height has a width but no height of its own. assert!(!code.contains(".Height(") || code.matches(".Height(").count() == 1, "{code}"); @@ -230,8 +248,7 @@ fn mixed_styles_become_runs() { .FontWeight(FontWeights.Bold), new Run() .Text(\" end\"))"; - let indented = expected.lines().collect::>().join("\n "); - assert!(code.contains(&indented), "{code}"); + assert!(has_block(&code, expected), "{code}"); assert!(!code.contains(".Text(\"Plain bold end\")"), "{code}"); } @@ -336,11 +353,6 @@ fn instances_and_components_are_walked_as_frames() { assert!(!code.contains("export default") && !code.contains("function "), "{code}"); } -/// The body of a view with the class shell and its indent taken off. -fn body(code: &str) -> String { - tree(code).lines().map(|l| format!("{}\n", l.get(12..).unwrap_or(l))).collect::().trim_end().to_string() -} - fn rect(s: &mut Session, parent: NodeId, w: f64, h: f64, name: &str) -> NodeId { idv(&ex(s, "shape.rectangle", json!({"parent": parent, "x": 0, "y": 0, "width": w, "height": h, "props": {"name": name, "fill": "#FF0000"}}))) } @@ -367,7 +379,7 @@ fn a_row_is_an_auto_layout_with_its_box_gap_padding_and_alignment() { rect(&mut s, f, 20.0, 20.0, "B"); let code = uno(&mut s, f); assert!(code.starts_with("using Windows.UI;\nusing Uno.Toolkit.UI;\n") || code.contains("using Uno.Toolkit.UI;"), "{code}"); - let expected = "new AutoLayout() + let expected = "var row = new AutoLayout() .Width(200) .Height(100) .Background(Color.FromArgb(0xFF, 0x11, 0x22, 0x33)) @@ -376,16 +388,18 @@ fn a_row_is_an_auto_layout_with_its_box_gap_padding_and_alignment() { .Spacing(12) .Padding(15, 7, 15, 7) .PrimaryAxisAlignment(AutoLayoutAlignment.Center) - .CounterAxisAlignment(AutoLayoutAlignment.Center) - .Children( - new Border() - .Width(20) - .Height(20) - .Background(Color.FromArgb(0xFF, 0xFF, 0x00, 0x00)), - new Border() - .Width(20) - .Height(20) - .Background(Color.FromArgb(0xFF, 0xFF, 0x00, 0x00)))"; + .CounterAxisAlignment(AutoLayoutAlignment.Center); +var a = new Border() + .Width(20) + .Height(20) + .Background(Color.FromArgb(0xFF, 0xFF, 0x00, 0x00)); +row.Children.Add(a); +var b = new Border() + .Width(20) + .Height(20) + .Background(Color.FromArgb(0xFF, 0xFF, 0x00, 0x00)); +row.Children.Add(b); +Content = row;"; assert_eq!(body(&code), expected, "{code}"); // A frame with auto layout is not a frame without one: no warning. assert!(!code.contains("// warning"), "{code}"); @@ -396,8 +410,8 @@ fn a_column_has_a_vertical_orientation_and_a_uniform_padding_is_one_number() { let mut s = Session::new(); let f = row(&mut s, json!({"layout": "vertical", "padding": 8, "gap": 0})); let code = uno(&mut s, f); - assert!(code.contains(".Orientation(Orientation.Vertical)\n"), "{code}"); - assert!(code.contains(".Padding(8)\n"), "{code}"); + assert!(has_call(&code, ".Orientation(Orientation.Vertical)"), "{code}"); + assert!(has_call(&code, ".Padding(8)"), "{code}"); assert!(!code.contains(".Spacing("), "no gap, no spacing: {code}"); set(&mut s, f, json!({"padding": 0})); assert!(!uno(&mut s, f).contains(".Padding(")); @@ -436,14 +450,14 @@ fn the_stroke_weight_comes_off_the_padding_unless_strokes_are_included() { let mut s = Session::new(); let f = row(&mut s, json!({"padding": 10, "stroke": "#0000FF", "strokeWeight": 4, "strokeAlign": "inside", "strokesIncluded": false})); let code = uno(&mut s, f); - assert!(code.contains(".BorderThickness(4)") && code.contains(".Padding(6)\n"), "{code}"); + assert!(code.contains(".BorderThickness(4)") && has_call(&code, ".Padding(6)"), "{code}"); assert!(!code.contains("new Grid()"), "{code}"); set(&mut s, f, json!({"strokesIncluded": true})); - assert!(uno(&mut s, f).contains(".Padding(10)\n")); + assert!(has_call(&uno(&mut s, f), ".Padding(10)")); // A stroke thicker than the padding on a side: the border sits behind the layout. set(&mut s, f, json!({"strokesIncluded": false, "padding": 2})); let code = uno(&mut s, f); - assert!(code.contains("new Grid()") && code.contains("new Border()") && code.contains(".Padding(2)\n"), "{code}"); + assert!(code.contains("new Grid()") && code.contains("new Border()") && has_call(&code, ".Padding(2)"), "{code}"); let (grid, layout) = (code.find("new Grid()"), code.find("new AutoLayout()")); assert!(grid < layout, "{code}"); assert!(!code[layout.unwrap_or(0)..].contains(".BorderThickness("), "{code}"); @@ -476,3 +490,37 @@ fn nested_auto_layouts_carry_no_canvas_offsets() { assert_eq!(code.matches("new AutoLayout()").count(), 2, "{code}"); assert!(!code.contains(".Canvas("), "{code}"); } + +#[test] +fn children_are_added_never_chained() { + // Fluent `.Children(…)` / `.Child(…)` doubles the load time with every level of nesting, so + // containers are locals and their children are added one by one. + let mut s = Session::new(); + let outer = frame(&mut s, "Outer", 300.0, 300.0); + set(&mut s, outer, json!({"stroke": "#000000", "strokeWeight": 2})); + let inner = idv(&ex(&mut s, "frame.create", json!({"x": 5, "y": 5, "width": 100, "height": 100, "parent": outer, "name": "Inner"}))); + set(&mut s, inner, json!({"layout": "vertical", "padding": 4, "gap": 3, "stroke": "#FF0000", "strokeWeight": 9, "strokesIncluded": false})); + rect(&mut s, inner, 10.0, 10.0, "R"); + let t = idv(&ex(&mut s, "text.create", json!({"text": "Hi", "x": 0, "y": 0, "parent": outer, "props": {"name": "T"}}))); + set(&mut s, t, json!({"textAutoResize": "none", "width": 50, "height": 40, "textAlignVertical": "middle"})); + let mut parent = outer; + for i in 0..6 { + parent = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50, "parent": parent, "name": format!("Level {i}")}))); + } + let code = uno(&mut s, outer); + assert!(!code.contains(".Children(") && !code.contains(".Child("), "{code}"); + assert!(code.contains(".Children.Add(") && code.contains(".Child = "), "{code}"); + // A single child of a border is assigned. + let lone = frame(&mut s, "Lone", 20.0, 20.0); + rect(&mut s, lone, 5.0, 5.0, "X"); + let code = uno(&mut s, lone); + assert!(!code.contains(".Child(") && !code.contains(".Children("), "{code}"); + // Names of locals are unique C# identifiers, the parent's before its children's. + let twins = frame(&mut s, "Card", 50.0, 50.0); + rect(&mut s, twins, 5.0, 5.0, "Card"); + rect(&mut s, twins, 5.0, 5.0, "class"); + let code = uno(&mut s, twins); + for decl in ["var card = ", "var card2 = ", "var class_ = "] { + assert_eq!(code.matches(decl).count(), 1, "{decl} in {code}"); + } +} From 457a7bec60c112183f8ee5dbe2a10ae8383ed225 Mon Sep 17 00:00:00 2001 From: Andrej Skvorc Date: Fri, 13 Nov 2026 17:49:30 +0100 Subject: [PATCH 19/48] M6: Uno auto layout: sizing, absolute children, z-order A child sizes per axis in its AutoLayout parent: fixed writes the length, hug writes none, fill stretches with the attached AutoLayout call; min and max lengths go on the child. Text hugs (one line), fills (wraps) or is fixed. A child that ignores the layout is independent at its offset, and a hugging parent with such a child is written at its size. reverse_z paints with descending Canvas.ZIndex and keeps the order. --- crates/engine/src/dev/codegen/uno.rs | 183 ++++++++++++++++++------- crates/engine/src/uno_codegen_tests.rs | 154 +++++++++++++++++++++ 2 files changed, 290 insertions(+), 47 deletions(-) diff --git a/crates/engine/src/dev/codegen/uno.rs b/crates/engine/src/dev/codegen/uno.rs index 6dd876bd7..4bc6b6799 100644 --- a/crates/engine/src/dev/codegen/uno.rs +++ b/crates/engine/src/dev/codegen/uno.rs @@ -7,8 +7,8 @@ use std::collections::BTreeSet; use figcraft_color::{BlendMode, Color, ImageScaleMode, PaintKind}; use figcraft_doc::{ - AutoLayout, CrossAlign, Document, EffectKind, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, StrokeAlign, TextAlignH, - TextAlignV, TextAutoResize, TextCase, TextData, TextDecoration, TextStyle, + AutoLayout, CrossAlign, Document, EffectKind, HConstraint, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, Sizing, + StrokeAlign, TextAlignH, TextAlignV, TextAutoResize, TextCase, TextData, TextDecoration, TextStyle, VConstraint, }; use super::swift::one_line; @@ -295,12 +295,15 @@ impl Element { } } -/// Where a child sits in its parent: at an offset in a `Canvas`, or wherever the parent's flow -/// (an `AutoLayout`) puts it. +/// Where a child sits in its parent: nowhere in particular (the root), at an offset in a +/// `Canvas`, in the flow of an `AutoLayout` (`z` is its paint order when the parent paints the first +/// child on top), or over an `AutoLayout` at an offset that ignores it. #[derive(Clone, Copy, Debug, PartialEq)] enum Place { Flow, At(f64, f64), + Line { vertical: bool, z: Option }, + Independent { x: f64, y: f64, z: Option }, } /// What a tree walk keeps between layers. @@ -430,28 +433,49 @@ impl Gen<'_> { let pad = [pt - weights[0], pr - weights[1], pb - weights[2], pl - weights[3]]; let behind = pad.iter().any(|p| *p < 0.0); let mut line = Element::new("new AutoLayout()"); - for k in self.ctx.kids(n).iter().take(MAX_CHILDREN) { + let kids = self.ctx.kids(n); + let vertical = l.mode == LayoutMode::Vertical; + let mut absolute = false; + for (i, k) in kids.iter().enumerate().take(MAX_CHILDREN) { let Some(c) = self.ctx.doc.node(*k) else { continue }; - line.kids.extend(self.layer(c, depth + 1, Place::Flow)); + // "First on top": the paint order descends, the order of the children stays. + let z = l.reverse_z.then_some(kids.len() - i); + let place = if c.child_layout.absolute { + absolute = true; + let [_, _, _, _, x, y] = c.transform.as_coeffs(); + Place::Independent { x, y, z } + } else { + Place::Line { vertical, z } + }; + line.kids.extend(self.layer(c, depth + 1, place)); } + // The Toolkit grows a hugging layout to cover a child that ignores it; FigCraft's does not. + let (aw, ah) = axes(n, at); + let force = (absolute && aw == Sizing::Hug, absolute && ah == Sizing::Hug); + let size = |e: &mut Element| { + dims(e, n, if force.0 { Sizing::Fixed } else { aw }, if force.1 { Sizing::Fixed } else { ah }); + if force.0 || force.1 { + e.note("hug size fixed: an absolute child would enlarge it"); + } + }; let mut outer; if behind { // The layout inside keeps the whole padding; the border is drawn behind it. let mut border = Element::new("new Border()"); - self.paint_box(&mut border, n, false); + self.paint_box(&mut border, n, false, at); layout_calls(&mut line, l, [pt, pr, pb, pl]); outer = Element::new("new Grid()"); - place(&mut outer, at); - size(&mut outer, n); + place(&mut outer, n, at); + size(&mut outer); border.var = self.fresh(&format!("{} border", n.name), "border"); line.var = self.fresh(&format!("{} layout", n.name), "layout"); outer.kids = vec![border, line]; common(&mut outer, n); } else { outer = line; - place(&mut outer, at); - size(&mut outer, n); - self.paint_box(&mut outer, n, false); + place(&mut outer, n, at); + size(&mut outer); + self.paint_box(&mut outer, n, false, at); layout_calls(&mut outer, l, pad); common(&mut outer, n); } @@ -468,7 +492,7 @@ impl Gen<'_> { fn canvas_box(&mut self, n: &Node, depth: usize, at: Place) -> Element { let mut border = Element::new("new Border()"); let sized = !matches!(n.kind, NodeKind::Group | NodeKind::Section { .. }); - self.paint_box(&mut border, n, sized); + self.paint_box(&mut border, n, sized, at); let mut canvas = Element::new("new Canvas()"); for k in self.ctx.kids(n).iter().take(MAX_CHILDREN) { let Some(c) = self.ctx.doc.node(*k) else { continue }; @@ -485,15 +509,15 @@ impl Gen<'_> { let mut outer; if has_kids && stroke_color(n).is_some() { outer = Element::new("new Grid()"); - place(&mut outer, at); - size(&mut outer, n); + place(&mut outer, n, at); + size(&mut outer, n, at); border.calls.retain(|c| !c.starts_with(".Width(") && !c.starts_with(".Height(")); border.var = self.fresh(&format!("{} border", n.name), "border"); outer.kids = vec![border, canvas]; common(&mut outer, n); } else { outer = border; - place(&mut outer, at); + place(&mut outer, n, at); if has_kids { outer.adds = "Child"; outer.kids = vec![canvas]; @@ -510,9 +534,9 @@ impl Gen<'_> { } /// The fill, stroke and corners of a `Border`. - fn paint_box(&mut self, e: &mut Element, n: &Node, sized: bool) { + fn paint_box(&mut self, e: &mut Element, n: &Node, sized: bool, at: Place) { if sized { - size(e, n); + size(e, n, at); } let visible: Vec<_> = n.fills.iter().filter(|p| p.visible).collect(); match visible.first().map(|p| &p.kind) { @@ -573,8 +597,8 @@ impl Gen<'_> { /// An ellipse: `Ellipse` with `Fill` and a centred `Stroke`. fn ellipse(&mut self, n: &Node, (start, sweep, inner): (f64, f64, f64), at: Place) -> Element { let mut e = Element::new("new Ellipse()"); - place(&mut e, at); - size(&mut e, n); + place(&mut e, n, at); + size(&mut e, n, at); if let Some(c) = first_fill(n) { e.call(format!(".Fill({})", cs_color(c))); } @@ -597,9 +621,9 @@ impl Gen<'_> { let name = asset_name(&n.name, n.kind.label(), &mut self.assets); let mut e = Element::new("new Image()"); e.lead.push(format!("// {} \"{}\": export it as an SVG to Assets/{name}.svg", n.kind.label(), comment_name(&n.name))); - place(&mut e, at); + place(&mut e, n, at); e.call(format!(".Source(\"{ASSETS}/{name}.svg\")")); - size(&mut e, n); + size(&mut e, n, at); e.call(".Stretch(Stretch.Uniform)"); common(&mut e, n); e @@ -610,16 +634,16 @@ impl Gen<'_> { fn text(&mut self, n: &Node, t: &TextData, at: Place) -> Element { let fixed = matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Truncate); let framed = fixed && t.align_v != TextAlignV::Top; - let mut tb = text_block(n, t, !framed); + let mut tb = text_block(n, t, !framed, line_axes(n, at)); if !framed { - place(&mut tb, at); + place(&mut tb, n, at); common(&mut tb, n); return tb; } tb.call(format!(".VerticalAlignment(VerticalAlignment.{})", if t.align_v == TextAlignV::Middle { "Center" } else { "Bottom" })); let mut g = Element::new("new Grid()"); - place(&mut g, at); - size(&mut g, n); + place(&mut g, n, at); + size(&mut g, n, at); tb.var = self.fresh(&format!("{} text", n.name), "text"); g.kids = vec![tb]; common(&mut g, n); @@ -627,12 +651,65 @@ impl Gen<'_> { } } -/// The `Canvas` offsets of a child at `at`; a child in a flow carries nothing. -fn place(e: &mut Element, at: Place) { - if let Place::At(x, y) = at { - // The offsets come first in the chain: they read as the element's address. - e.calls.insert(0, format!(".Canvas(left: {}, top: {})", num(x), num(y))); +/// The calls that address a child in its parent, first in its chain: the `Canvas` offsets, or +/// the attached `AutoLayout` call (fill on an axis, or independent of the layout), the paint +/// order and the size limits. +fn place(e: &mut Element, n: &Node, at: Place) { + let mut lead: Vec = Vec::new(); + let z = |z: Option, lead: &mut Vec| { + if let Some(z) = z { + lead.push(format!(".Canvas(zIndex: {z})")); + } + }; + match at { + Place::Flow => {} + // The offsets read as the element's address. + Place::At(x, y) => lead.push(format!(".Canvas(left: {}, top: {})", num(x), num(y))), + Place::Line { vertical, z: order } => { + let cl = &n.child_layout; + let (primary, counter) = if vertical { (cl.sizing_v, cl.sizing_h) } else { (cl.sizing_h, cl.sizing_v) }; + let mut args: Vec<&str> = Vec::new(); + if primary == Sizing::Fill { + args.push("primaryAlignment: AutoLayoutPrimaryAlignment.Stretch"); + } + if counter == Sizing::Fill { + args.push("counterAlignment: AutoLayoutAlignment.Stretch"); + } + if !args.is_empty() { + lead.push(format!(".AutoLayout({})", args.join(", "))); + } + z(order, &mut lead); + for (name, v) in [("MinWidth", cl.min_w), ("MaxWidth", cl.max_w), ("MinHeight", cl.min_h), ("MaxHeight", cl.max_h)] { + if let Some(v) = v.filter(|v| v.is_finite()) { + lead.push(format!(".{name}({})", num(v))); + } + } + } + Place::Independent { x, y, z: order } => { + lead.push(".AutoLayout(isIndependentLayout: true)".into()); + z(order, &mut lead); + lead.push(".HorizontalAlignment(HorizontalAlignment.Left)".into()); + lead.push(".VerticalAlignment(VerticalAlignment.Top)".into()); + lead.push(format!(".Margin({}, {}, 0, 0)", num(x), num(y))); + if n.constraints.horizontal != HConstraint::Left || n.constraints.vertical != VConstraint::Top { + e.note("constraints (the child stays at its top-left offset)"); + } + } } + e.calls.splice(0..0, lead); +} + +/// How a child sizes on each axis in its parent: fixed everywhere but in an auto layout flow. +fn axes(n: &Node, at: Place) -> (Sizing, Sizing) { + match at { + Place::Line { .. } => (n.child_layout.sizing_h, n.child_layout.sizing_v), + _ => (Sizing::Fixed, Sizing::Fixed), + } +} + +/// [`axes`] for a text in a flow (outside one a text sizes itself from its resize mode). +fn line_axes(n: &Node, at: Place) -> Option<(Sizing, Sizing)> { + matches!(at, Place::Line { .. }).then(|| axes(n, at)) } /// The calls an `AutoLayout` takes for its orientation, gap, padding (`pad` is top, right, @@ -669,10 +746,20 @@ fn layout_calls(e: &mut Element, l: &AutoLayout, pad: [f64; 4]) { } } -/// The layer's fixed width and height. -fn size(e: &mut Element, n: &Node) { - e.call(format!(".Width({})", num(n.width))); - e.call(format!(".Height({})", num(n.height))); +/// The layer's width and height on the axes where it is fixed (a hugging axis takes its size +/// from the content, a filling one from the parent). +fn size(e: &mut Element, n: &Node, at: Place) { + let (w, h) = axes(n, at); + dims(e, n, w, h); +} + +fn dims(e: &mut Element, n: &Node, w: Sizing, h: Sizing) { + if w == Sizing::Fixed { + e.call(format!(".Width({})", num(n.width))); + } + if h == Sizing::Fixed { + e.call(format!(".Height({})", num(n.height))); + } } /// What every layer shares: opacity, rotation, and the notes for what has no counterpart. @@ -792,7 +879,7 @@ fn style_calls(e: &mut Element, s: &TextStyle, fill: Option, base: Option /// A `TextBlock` for a text layer. `with_height` sets the box's height when the text has a fixed /// box (a text in a `Grid` of that height leaves it to the grid). -fn text_block(n: &Node, t: &TextData, with_height: bool) -> Element { +fn text_block(n: &Node, t: &TextData, with_height: bool, axes: Option<(Sizing, Sizing)>) -> Element { let mut e = Element::new("new TextBlock()"); let s = &t.style; let fill = first_fill(n); @@ -839,20 +926,22 @@ fn text_block(n: &Node, t: &TextData, with_height: bool) -> Element { TextAlignH::Right => e.call(".TextAlignment(TextAlignment.Right)"), TextAlignH::Justified => e.call(".TextAlignment(TextAlignment.Justify)"), } - match t.auto_resize { - TextAutoResize::WidthAndHeight => e.call(".TextWrapping(TextWrapping.NoWrap)"), - TextAutoResize::Height => { + // In a flow the text takes its width from the sizing: hugging is one line, filling wraps at + // the parent's width, fixed is the box's width. + let one_line = t.auto_resize == TextAutoResize::WidthAndHeight; + // Outside a flow the resize mode says it. + let (width, tall) = axes.unwrap_or((if one_line { Sizing::Hug } else { Sizing::Fixed }, Sizing::Fixed)); + match width { + Sizing::Hug => e.call(".TextWrapping(TextWrapping.NoWrap)"), + Sizing::Fill => e.call(".TextWrapping(TextWrapping.Wrap)"), + Sizing::Fixed => { e.call(format!(".Width({})", num(n.width))); - e.call(".TextWrapping(TextWrapping.Wrap)"); - } - TextAutoResize::None | TextAutoResize::Truncate => { - e.call(format!(".Width({})", num(n.width))); - if with_height { - e.call(format!(".Height({})", num(n.height))); - } - e.call(".TextWrapping(TextWrapping.Wrap)"); + e.call(format!(".TextWrapping(TextWrapping.{})", if one_line { "NoWrap" } else { "Wrap" })); } } + if tall == Sizing::Fixed && with_height && matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Truncate) { + e.call(format!(".Height({})", num(n.height))); + } if t.auto_resize == TextAutoResize::Truncate || (t.max_lines > 0 && t.auto_resize != TextAutoResize::WidthAndHeight) { e.call(".TextTrimming(TextTrimming.CharacterEllipsis)"); if t.max_lines > 0 { diff --git a/crates/engine/src/uno_codegen_tests.rs b/crates/engine/src/uno_codegen_tests.rs index 088cc9576..361547d41 100644 --- a/crates/engine/src/uno_codegen_tests.rs +++ b/crates/engine/src/uno_codegen_tests.rs @@ -524,3 +524,157 @@ fn children_are_added_never_chained() { assert_eq!(code.matches(decl).count(), 1, "{decl} in {code}"); } } + +/// The calls of the local `var`, in order, without indent or the closing `;`. +fn chain(code: &str, var: &str) -> Vec { + let head = format!("var {var} = "); + let mut out = Vec::new(); + let mut lines = code.lines().skip_while(|l| !l.trim_start().starts_with(&head)); + let Some(first) = lines.next() else { return out }; + let mut done = first.trim_end().ends_with(';'); + for l in lines { + // A `// not mapped` comment may follow the call that ends the statement. + if done && !l.trim_start().starts_with("//") { + break; + } + done = done || l.trim_end().ends_with(';'); + out.push(l.trim().trim_end_matches(';').to_string()); + } + out +} + +fn first_child(s: &Session, f: NodeId) -> NodeId { + s.doc().ok().and_then(|d| d.node(f)).and_then(|n| n.children.first().copied()).unwrap_or(f) +} + +#[test] +fn fill_stretches_on_the_axis_it_fills_and_fixed_keeps_its_size() { + let mut s = Session::new(); + let f = row(&mut s, json!({})); + let a = first_child(&s, f); + let has = |c: &[String], p: &str| c.iter().any(|l| l.starts_with(p)); + // Horizontal parent: width is the primary axis, height the counter axis. + set(&mut s, a, json!({"sizingH": "fill"})); + let code = uno(&mut s, f); + let kid = chain(&code, "a"); + assert_eq!(kid[0], ".AutoLayout(primaryAlignment: AutoLayoutPrimaryAlignment.Stretch)", "{code}"); + assert!(!has(&kid, ".Width(") && has(&kid, ".Height("), "{code}"); + set(&mut s, a, json!({"sizingV": "fill"})); + let kid = chain(&uno(&mut s, f), "a"); + assert_eq!(kid[0], ".AutoLayout(primaryAlignment: AutoLayoutPrimaryAlignment.Stretch, counterAlignment: AutoLayoutAlignment.Stretch)"); + assert!(!has(&kid, ".Width(") && !has(&kid, ".Height(")); + // In a column the axes swap. + set(&mut s, f, json!({"layout": "vertical"})); + set(&mut s, a, json!({"sizingH": "fixed"})); + let kid = chain(&uno(&mut s, f), "a"); + assert_eq!(kid[0], ".AutoLayout(primaryAlignment: AutoLayoutPrimaryAlignment.Stretch)"); + assert!(has(&kid, ".Width(")); + set(&mut s, a, json!({"sizingH": "fill", "sizingV": "fixed"})); + assert_eq!(chain(&uno(&mut s, f), "a")[0], ".AutoLayout(counterAlignment: AutoLayoutAlignment.Stretch)"); +} + +#[test] +fn a_hugging_frame_has_no_size_of_its_own_and_the_root_keeps_its_size() { + let mut s = Session::new(); + let outer = row(&mut s, json!({"layout": "vertical", "sizingH": "hug", "sizingV": "hug"})); + let inner = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50, "parent": outer, "name": "Inner"}))); + set(&mut s, inner, json!({"layout": "horizontal", "padding": 3, "gap": 2, "sizingH": "hug", "sizingV": "hug"})); + rect(&mut s, inner, 5.0, 5.0, "C"); + let code = uno(&mut s, outer); + let has = |c: &[String], p: &str| c.iter().any(|l| l.starts_with(p)); + let root = chain(&code, "row"); + assert!(has(&root, ".Width(") && has(&root, ".Height("), "the root keeps its size: {code}"); + let nested = chain(&code, "inner"); + assert!(!has(&nested, ".Width(") && !has(&nested, ".Height("), "{code}"); +} + +#[test] +fn min_and_max_sizes_go_on_the_child() { + let mut s = Session::new(); + let f = row(&mut s, json!({})); + let a = first_child(&s, f); + set(&mut s, a, json!({"sizingH": "fill", "minWidth": 40, "maxWidth": 120, "minHeight": 10, "maxHeight": 30})); + let code = uno(&mut s, f); + for line in [".MinWidth(40)", ".MaxWidth(120)", ".MinHeight(10)", ".MaxHeight(30)"] { + assert!(chain(&code, "a").contains(&line.to_string()), "{line} in {code}"); + } +} + +#[test] +fn text_in_a_flow_hugs_fills_or_is_fixed() { + let mut s = Session::new(); + let f = row(&mut s, json!({})); + let t = idv(&ex(&mut s, "text.create", json!({"text": "Hello", "x": 0, "y": 0, "parent": f, "props": {"name": "T"}}))); + let calls = |s: &mut Session| chain(&uno(s, f), "t"); + let has = |c: &[String], p: &str| c.iter().any(|l| l.starts_with(p)); + set(&mut s, t, json!({"textAutoResize": "widthAndHeight", "sizingH": "hug", "sizingV": "hug"})); + let c = calls(&mut s); + assert!(c.contains(&".TextWrapping(TextWrapping.NoWrap)".to_string()), "{c:?}"); + assert!(!has(&c, ".Width(") && !has(&c, ".Height("), "{c:?}"); + set(&mut s, t, json!({"textAutoResize": "height", "sizingH": "fill"})); + let c = calls(&mut s); + assert_eq!(c.first().map(String::as_str), Some(".AutoLayout(primaryAlignment: AutoLayoutPrimaryAlignment.Stretch)"), "{c:?}"); + assert!(c.contains(&".TextWrapping(TextWrapping.Wrap)".to_string()) && !has(&c, ".Width("), "{c:?}"); + set(&mut s, t, json!({"textAutoResize": "height", "sizingH": "fixed", "width": 90})); + let c = calls(&mut s); + assert!(c.contains(&".Width(90)".to_string()) && c.contains(&".TextWrapping(TextWrapping.Wrap)".to_string()), "{c:?}"); +} + +#[test] +fn an_absolute_child_ignores_the_layout_and_keeps_its_offsets() { + let mut s = Session::new(); + let f = row(&mut s, json!({"padding": 10})); + let b = rect(&mut s, f, 12.0, 12.0, "Badge"); + set(&mut s, b, json!({"absolute": true, "x": 30, "y": 40})); + let code = uno(&mut s, f); + let expected = [ + ".AutoLayout(isIndependentLayout: true)", + ".HorizontalAlignment(HorizontalAlignment.Left)", + ".VerticalAlignment(VerticalAlignment.Top)", + ".Margin(30, 40, 0, 0)", + ".Width(12)", + ".Height(12)", + ]; + assert_eq!(chain(&code, "badge")[..6], expected, "{code}"); + // A top-left child needs no note; another constraint does, and the offsets stay. + assert!(!code.contains("// not mapped: constraints"), "{code}"); + set(&mut s, b, json!({"constraints": {"horizontal": "right"}})); + let code = uno(&mut s, f); + assert!(chain(&code, "badge").iter().any(|l| l == "// not mapped: constraints (the child stays at its top-left offset)"), "{code}"); + assert!(chain(&code, "badge").contains(&".Margin(30, 40, 0, 0)".to_string()), "{code}"); +} + +#[test] +fn a_hugging_parent_with_an_absolute_child_is_written_at_its_size() { + let mut s = Session::new(); + let outer = row(&mut s, json!({"layout": "vertical"})); + let hug = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 60, "height": 40, "parent": outer, "name": "Hug"}))); + set(&mut s, hug, json!({"layout": "horizontal", "padding": 0, "gap": 0, "sizingH": "hug", "sizingV": "hug"})); + rect(&mut s, hug, 60.0, 40.0, "Body"); + let code = uno(&mut s, outer); + assert!(!code.contains("hug size fixed"), "{code}"); + let badge = rect(&mut s, hug, 8.0, 8.0, "Badge"); + set(&mut s, badge, json!({"absolute": true, "x": 50, "y": -4})); + let code = uno(&mut s, outer); + let c = chain(&code, "hug"); + assert!(c.contains(&"// not mapped: hug size fixed: an absolute child would enlarge it".to_string()), "{code}"); + assert!(c.contains(&".Width(60)".to_string()) && c.contains(&".Height(40)".to_string()), "{code}"); +} + +#[test] +fn first_on_top_paints_in_descending_order_without_reordering() { + let mut s = Session::new(); + let f = row(&mut s, json!({"gap": -10})); + rect(&mut s, f, 20.0, 20.0, "B"); + rect(&mut s, f, 20.0, 20.0, "C"); + let plain = uno(&mut s, f); + assert!(!plain.contains("zIndex") && !plain.contains("IsReverseZIndex"), "{plain}"); + set(&mut s, f, json!({"reverseZ": true})); + let code = uno(&mut s, f); + for (var, z) in [("a", 3), ("b", 2), ("c", 1)] { + assert!(chain(&code, var).contains(&format!(".Canvas(zIndex: {z})")), "{var} in {code}"); + } + // The order of the children is unchanged. + assert!(code.find("var a = ") < code.find("var b = ") && code.find("var b = ") < code.find("var c = "), "{code}"); + assert!(!code.contains("IsReverseZIndex"), "{code}"); +} From 9217f27cd8fc0c693ce23839f4179c1312b86cd3 Mon Sep 17 00:00:00 2001 From: Andrej Skvorc Date: Fri, 13 Nov 2026 18:06:47 +0100 Subject: [PATCH 20/48] M6: Uno auto layout: grid mode and wrap note A frame with grid auto layout is a WinUI Grid: column and row definitions (pixels, Auto, whole-number stars), column and row spacing, padding less the stroke weight, and each child in the cell FigCraft's layout gives it, with spans and the alignment in the cell. Fractional stars are scaled to whole numbers or rounded with a note, at most 64 tracks per axis are written, and a wrapping layout is one line with a note. --- crates/engine/src/dev/codegen/uno.rs | 251 ++++++++++++++++++++++--- crates/engine/src/uno_codegen_tests.rs | 117 ++++++++++++ 2 files changed, 339 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/dev/codegen/uno.rs b/crates/engine/src/dev/codegen/uno.rs index 4bc6b6799..c626c9471 100644 --- a/crates/engine/src/dev/codegen/uno.rs +++ b/crates/engine/src/dev/codegen/uno.rs @@ -7,8 +7,8 @@ use std::collections::BTreeSet; use figcraft_color::{BlendMode, Color, ImageScaleMode, PaintKind}; use figcraft_doc::{ - AutoLayout, CrossAlign, Document, EffectKind, HConstraint, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, Sizing, - StrokeAlign, TextAlignH, TextAlignV, TextAutoResize, TextCase, TextData, TextDecoration, TextStyle, VConstraint, + AutoLayout, CellAlign, CrossAlign, Document, EffectKind, HConstraint, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, + Sizing, StrokeAlign, TextAlignH, TextAlignV, TextAutoResize, TextCase, TextData, TextDecoration, TextStyle, VConstraint, }; use super::swift::one_line; @@ -297,13 +297,35 @@ impl Element { /// Where a child sits in its parent: nowhere in particular (the root), at an offset in a /// `Canvas`, in the flow of an `AutoLayout` (`z` is its paint order when the parent paints the first -/// child on top), or over an `AutoLayout` at an offset that ignores it. +/// child on top), over an `AutoLayout` at an offset that ignores it, or in a cell of a `Grid`. #[derive(Clone, Copy, Debug, PartialEq)] enum Place { Flow, At(f64, f64), - Line { vertical: bool, z: Option }, - Independent { x: f64, y: f64, z: Option }, + Line { + vertical: bool, + z: Option, + }, + Independent { + x: f64, + y: f64, + z: Option, + }, + /// In a cell of a `Grid`: row, column, spans and the alignment in the cell. + Cell { + row: usize, + column: usize, + row_span: usize, + column_span: usize, + align: (CellAlign, CellAlign), + }, + /// Over a `Grid`, across all its cells, at an offset that ignores it. + Overlay { + x: f64, + y: f64, + rows: usize, + columns: usize, + }, } /// What a tree walk keeps between layers. @@ -405,19 +427,17 @@ impl Gen<'_> { Some(e) } - /// A frame-like layer, group or rectangle. Horizontal and vertical auto layout is an - /// `AutoLayout`; anything else is a `Border` holding a `Canvas` with the children at their - /// offsets. + /// A frame-like layer, group or rectangle. Auto layout is an `AutoLayout` (horizontal, + /// vertical) or a `Grid` (grid mode); anything else is a `Border` holding a `Canvas` with the + /// children at their offsets. fn boxed(&mut self, n: &Node, depth: usize, at: Place) -> Element { match n.layout.as_ref() { - Some(l) if matches!(l.mode, LayoutMode::Horizontal | LayoutMode::Vertical) && !matches!(n.kind, NodeKind::Rectangle) => { - self.auto_layout(n, l, depth, at) - } + Some(l) if !matches!(n.kind, NodeKind::Rectangle) => self.auto_layout(n, l, depth, at), _ => self.canvas_box(n, depth, at), } } - /// A frame with horizontal or vertical auto layout: an `AutoLayout` that takes the box + /// A frame with auto layout: an `AutoLayout` (or, in grid mode, a `Grid`) that takes the box /// (fill, border, corners) itself. A `Border` pushes its content in by its thickness, so /// the padding is written less the stroke weight, as FigCraft's layout ignores strokes (unless /// they are included). Where that would be negative the border sits behind the layout in a @@ -432,18 +452,59 @@ impl Gen<'_> { let weights = if l.strokes_included { [0.0; 4] } else { weights }; let pad = [pt - weights[0], pr - weights[1], pb - weights[2], pl - weights[3]]; let behind = pad.iter().any(|p| *p < 0.0); - let mut line = Element::new("new AutoLayout()"); + let grid = l.mode == LayoutMode::Grid; + let mut line = Element::new(if grid { "new Grid()" } else { "new AutoLayout()" }); let kids = self.ctx.kids(n); let vertical = l.mode == LayoutMode::Vertical; let mut absolute = false; + // Grid mode: where FigCraft's own layout puts each child. + let (cells, rows) = + if grid { figcraft_layout::grid_place(self.ctx.doc, l, &figcraft_layout::flow_children(self.ctx.doc, n.id)) } else { (Vec::new(), 0) }; + let tracks = GridTracks::new(l, rows); + let frame_align = ( + match l.main_align { + MainAlign::Center => CellAlign::Center, + MainAlign::Max => CellAlign::Max, + _ => CellAlign::Min, + }, + match l.cross_align { + CrossAlign::Center => CellAlign::Center, + CrossAlign::Max => CellAlign::Max, + _ => CellAlign::Min, + }, + ); for (i, k) in kids.iter().enumerate().take(MAX_CHILDREN) { let Some(c) = self.ctx.doc.node(*k) else { continue }; // "First on top": the paint order descends, the order of the children stays. - let z = l.reverse_z.then_some(kids.len() - i); + let z = (l.reverse_z && !grid).then_some(kids.len() - i); let place = if c.child_layout.absolute { absolute = true; let [_, _, _, _, x, y] = c.transform.as_coeffs(); - Place::Independent { x, y, z } + if grid { + // Against the grid's padded box, the offsets are the frame's less the padding. + Place::Overlay { + x: x - if behind { pl } else { pad[3] }, + y: y - if behind { pt } else { pad[0] }, + rows: tracks.rows, + columns: tracks.columns, + } + } else { + Place::Independent { x, y, z } + } + } else if grid { + match cells.iter().find(|cell| cell.id == *k) { + Some(cell) => { + let (cl, cr) = (cell.column.min(tracks.columns - 1), cell.row.min(tracks.rows - 1)); + Place::Cell { + row: cr, + column: cl, + row_span: cell.row_span.min(tracks.rows - cr), + column_span: cell.column_span.min(tracks.columns - cl), + align: (c.child_layout.grid_align_h.unwrap_or(frame_align.0), c.child_layout.grid_align_v.unwrap_or(frame_align.1)), + } + } + None => Place::Flow, + } } else { Place::Line { vertical, z } }; @@ -463,7 +524,11 @@ impl Gen<'_> { // The layout inside keeps the whole padding; the border is drawn behind it. let mut border = Element::new("new Border()"); self.paint_box(&mut border, n, false, at); - layout_calls(&mut line, l, [pt, pr, pb, pl]); + if grid { + grid_calls(&mut line, l, &tracks, [pt, pr, pb, pl]); + } else { + layout_calls(&mut line, l, [pt, pr, pb, pl]); + } outer = Element::new("new Grid()"); place(&mut outer, n, at); size(&mut outer); @@ -476,7 +541,11 @@ impl Gen<'_> { place(&mut outer, n, at); size(&mut outer); self.paint_box(&mut outer, n, false, at); - layout_calls(&mut outer, l, pad); + if grid { + grid_calls(&mut outer, l, &tracks, pad); + } else { + layout_calls(&mut outer, l, pad); + } common(&mut outer, n); } if n.clip && n.corners.radii.iter().all(|r| *r <= 0.0) && !n.children.is_empty() { @@ -524,9 +593,6 @@ impl Gen<'_> { } common(&mut outer, n); } - if n.layout.as_ref().is_some_and(|l| l.mode == LayoutMode::Grid) { - outer.note("grid auto layout (children are positioned absolutely)"); - } if n.clip && has_kids && n.corners.radii.iter().all(|r| *r <= 0.0) { outer.call(format!(".Clip(new RectangleGeometry().Rect(new Rect(0, 0, {}, {})))", num(n.width), num(n.height))); } @@ -685,6 +751,32 @@ fn place(e: &mut Element, n: &Node, at: Place) { } } } + Place::Cell { row, column, row_span, column_span, align } => { + let mut args = format!("row: {row}, column: {column}"); + if row_span > 1 { + args.push_str(&format!(", rowSpan: {row_span}")); + } + if column_span > 1 { + args.push_str(&format!(", columnSpan: {column_span}")); + } + lead.push(format!(".Grid({args})")); + cell_alignment(n, align, &mut lead); + let cl = &n.child_layout; + for (name, v) in [("MinWidth", cl.min_w), ("MaxWidth", cl.max_w), ("MinHeight", cl.min_h), ("MaxHeight", cl.max_h)] { + if let Some(v) = v.filter(|v| v.is_finite()) { + lead.push(format!(".{name}({})", num(v))); + } + } + } + Place::Overlay { x, y, rows, columns } => { + lead.push(format!(".Grid(row: 0, column: 0, rowSpan: {rows}, columnSpan: {columns})")); + lead.push(".HorizontalAlignment(HorizontalAlignment.Left)".into()); + lead.push(".VerticalAlignment(VerticalAlignment.Top)".into()); + lead.push(format!(".Margin({}, {}, 0, 0)", num(x), num(y))); + if n.constraints.horizontal != HConstraint::Left || n.constraints.vertical != VConstraint::Top { + e.note("constraints (the child stays at its top-left offset)"); + } + } Place::Independent { x, y, z: order } => { lead.push(".AutoLayout(isIndependentLayout: true)".into()); z(order, &mut lead); @@ -699,17 +791,122 @@ fn place(e: &mut Element, n: &Node, at: Place) { e.calls.splice(0..0, lead); } +/// The sizes of a cell child's alignment: a filling axis stretches (the cell's default), any +/// other aligns in its cell. +fn cell_alignment(n: &Node, align: (CellAlign, CellAlign), lead: &mut Vec) { + let cl = &n.child_layout; + if cl.sizing_h != Sizing::Fill { + let a = match align.0 { + CellAlign::Min => "Left", + CellAlign::Center => "Center", + CellAlign::Max => "Right", + }; + lead.push(format!(".HorizontalAlignment(HorizontalAlignment.{a})")); + } + if cl.sizing_v != Sizing::Fill { + let a = match align.1 { + CellAlign::Min => "Top", + CellAlign::Center => "Center", + CellAlign::Max => "Bottom", + }; + lead.push(format!(".VerticalAlignment(VerticalAlignment.{a})")); + } +} + /// How a child sizes on each axis in its parent: fixed everywhere but in an auto layout flow. fn axes(n: &Node, at: Place) -> (Sizing, Sizing) { match at { - Place::Line { .. } => (n.child_layout.sizing_h, n.child_layout.sizing_v), + Place::Line { .. } | Place::Cell { .. } => (n.child_layout.sizing_h, n.child_layout.sizing_v), _ => (Sizing::Fixed, Sizing::Fixed), } } /// [`axes`] for a text in a flow (outside one a text sizes itself from its resize mode). fn line_axes(n: &Node, at: Place) -> Option<(Sizing, Sizing)> { - matches!(at, Place::Line { .. }).then(|| axes(n, at)) + matches!(at, Place::Line { .. } | Place::Cell { .. }).then(|| axes(n, at)) +} + +/// The tracks a grid frame is written with: how many of each, and what had to be cut or rounded. +struct GridTracks { + columns: usize, + rows: usize, + cut: bool, +} + +/// Most tracks written per axis. +const MAX_WRITTEN_TRACKS: usize = 64; + +impl GridTracks { + fn new(l: &AutoLayout, rows: usize) -> Self { + let (columns, rows) = ((l.grid_columns as usize).max(1), rows.max(1)); + GridTracks { + columns: columns.min(MAX_WRITTEN_TRACKS), + rows: rows.min(MAX_WRITTEN_TRACKS), + cut: columns > MAX_WRITTEN_TRACKS || rows > MAX_WRITTEN_TRACKS, + } + } +} + +/// A `ColumnDefinitions` / `RowDefinitions` string for `count` tracks: fixed ones in pixels, hugging +/// ones `Auto`, filling ones as stars. Uno ignores fractional stars, so the shares of an axis are +/// scaled by the smallest factor up to 100 that makes them whole; the flag says they could not be +/// and were rounded. A track missing from `specs` fills one share. +fn track_string(specs: &[figcraft_doc::GridTrack], count: usize) -> (String, bool) { + let spec = |i: usize| specs.get(i).copied().unwrap_or_default(); + let share = |t: figcraft_doc::GridTrack| if t.value.is_finite() { t.value.clamp(0.0, 1e6) } else { 0.0 }; + let shares: Vec = (0..count).map(&spec).filter(|t| t.sizing == Sizing::Fill).map(share).collect(); + let whole = |k: f64| shares.iter().all(|f| (f * k - (f * k).round()).abs() < 1e-6); + let factor = (1..=100).map(f64::from).find(|k| whole(*k)); + let k = factor.unwrap_or(1.0); + let out: Vec = (0..count) + .map(|i| { + let t = spec(i); + match t.sizing { + Sizing::Fixed => num(share(t)), + Sizing::Hug => "Auto".to_string(), + Sizing::Fill => format!("{}*", num((share(t) * k).round().max(if factor.is_some() { 0.0 } else { 1.0 }))), + } + }) + .collect(); + (out.join(","), factor.is_none()) +} + +/// The calls a `Grid` takes for its tracks, spacing and padding. In grid mode FigCraft's `gap` is +/// the space between columns and `cross_gap` between rows (`layout_grid` reads them as `gx`, `gy`), +/// and the main and cross alignment are the children's default alignment in their cell. +fn grid_calls(e: &mut Element, l: &AutoLayout, t: &GridTracks, pad: [f64; 4]) { + let (columns, rounded_c) = track_string(&l.column_tracks, t.columns); + let (rows, rounded_r) = track_string(&l.row_tracks, t.rows); + e.call(format!(".ColumnDefinitions({})", cs_literal(&columns))); + e.call(format!(".RowDefinitions({})", cs_literal(&rows))); + if l.gap > 0.0 { + e.call(format!(".ColumnSpacing({})", num(l.gap))); + } + if l.cross_gap > 0.0 { + e.call(format!(".RowSpacing({})", num(l.cross_gap))); + } + padding_call(e, pad); + if rounded_c || rounded_r { + e.note("fractional grid track sizes (rounded to whole stars)"); + } + if t.cut { + e.note(&format!("more than {MAX_WRITTEN_TRACKS} grid tracks (only {MAX_WRITTEN_TRACKS} per axis are written)")); + } + if l.reverse_z { + e.note("first child on top (a grid paints its children in order)"); + } +} + +/// `Padding` from top, right, bottom, left: one number when equal, nothing when zero. +fn padding_call(e: &mut Element, pad: [f64; 4]) { + let [t, r, b, lf] = pad; + if pad.iter().any(|p| *p != 0.0) { + if t == r && r == b && b == lf { + e.call(format!(".Padding({})", num(t))); + } else { + e.call(format!(".Padding({}, {}, {}, {})", num(lf), num(t), num(r), num(b))); + } + } } /// The calls an `AutoLayout` takes for its orientation, gap, padding (`pad` is top, right, @@ -720,13 +917,9 @@ fn layout_calls(e: &mut Element, l: &AutoLayout, pad: [f64; 4]) { if l.gap != 0.0 && !l.main_align.is_auto_gap() { e.call(format!(".Spacing({})", num(l.gap))); } - let [t, r, b, lf] = pad; - if [t, r, b, lf].iter().any(|p| *p != 0.0) { - if t == r && r == b && b == lf { - e.call(format!(".Padding({})", num(t))); - } else { - e.call(format!(".Padding({}, {}, {}, {})", num(lf), num(t), num(r), num(b))); - } + padding_call(e, pad); + if l.wrap { + e.note("wrap (FlexPanel needs Uno.Toolkit 10; one line written)"); } match l.main_align { MainAlign::Min => {} diff --git a/crates/engine/src/uno_codegen_tests.rs b/crates/engine/src/uno_codegen_tests.rs index 361547d41..37bc4b19c 100644 --- a/crates/engine/src/uno_codegen_tests.rs +++ b/crates/engine/src/uno_codegen_tests.rs @@ -678,3 +678,120 @@ fn first_on_top_paints_in_descending_order_without_reordering() { assert!(code.find("var a = ") < code.find("var b = ") && code.find("var b = ") < code.find("var c = "), "{code}"); assert!(!code.contains("IsReverseZIndex"), "{code}"); } + +/// A grid frame of 300 × 200 with no padding and no fill. +fn grid(s: &mut Session, props: serde_json::Value) -> NodeId { + let f = frame(s, "Table", 300.0, 200.0); + let mut all = json!({"layout": "grid", "padding": 0, "gap": 0, "crossGap": 0, "fills": [], "sizingH": "fixed", "sizingV": "fixed"}); + if let (Some(all), serde_json::Value::Object(extra)) = (all.as_object_mut(), props) { + all.extend(extra); + } + set(s, f, all); + f +} + +#[test] +fn a_grid_frame_is_a_grid_with_tracks_spacing_and_cells_from_the_layout_crate() { + let mut s = Session::new(); + let g = grid(&mut s, json!({"columnTracks": [120, "auto", "1fr", "2fr"], "rowTracks": ["auto", "1fr"], "gap": 16, "crossGap": 8, "padding": 4})); + let kids: Vec = ["A", "B", "C", "D", "E"].iter().map(|n| rect(&mut s, g, 20.0, 20.0, n)).collect(); + set(&mut s, kids[1], json!({"gridColumnSpan": 2})); + set(&mut s, kids[4], json!({"gridColumn": 3, "gridRow": 1})); + let code = uno(&mut s, g); + let root = chain(&code, "table"); + for call in [".ColumnDefinitions(\"120,Auto,1*,2*\")", ".RowDefinitions(\"Auto,1*\")", ".ColumnSpacing(16)", ".RowSpacing(8)", ".Padding(4)"] { + assert!(root.contains(&call.to_string()), "{call} in {code}"); + } + assert!(!code.contains("new AutoLayout()") && !code.contains("// not mapped"), "{code}"); + // Every child sits in the cell FigCraft's own layout gives it. + let doc = s.doc().unwrap(); + let (cells, _) = figcraft_layout::grid_place(doc, doc.node(g).unwrap().layout.as_ref().unwrap(), &kids); + for (cell, name) in cells.iter().zip(["a", "b", "c", "d", "e"]) { + let mut want = format!(".Grid(row: {}, column: {}", cell.row, cell.column); + if cell.row_span > 1 { + want.push_str(&format!(", rowSpan: {}", cell.row_span)); + } + if cell.column_span > 1 { + want.push_str(&format!(", columnSpan: {}", cell.column_span)); + } + want.push(')'); + assert_eq!(chain(&code, name)[0], want, "{name} in {code}"); + } + assert!(chain(&code, "b")[0].contains("columnSpan: 2"), "{code}"); + assert_eq!(chain(&code, "e")[0], ".Grid(row: 1, column: 3)", "{code}"); + // The cell alignment is written, since a fixed size would otherwise be centred. + assert!(chain(&code, "a").contains(&".HorizontalAlignment(HorizontalAlignment.Left)".to_string()), "{code}"); +} + +#[test] +fn fractional_stars_are_scaled_to_whole_numbers_or_rounded_with_a_note() { + let mut s = Session::new(); + let g = grid(&mut s, json!({"columnTracks": ["1.5fr", "1fr", "0.5fr"], "rowTracks": ["fill"]})); + rect(&mut s, g, 20.0, 20.0, "A"); + let code = uno(&mut s, g); + assert!(chain(&code, "table").contains(&".ColumnDefinitions(\"3*,2*,1*\")".to_string()), "{code}"); + assert!(!code.contains("// not mapped"), "{code}"); + set(&mut s, g, json!({"columnTracks": ["1.3333fr", "1fr"]})); + let code = uno(&mut s, g); + assert!(chain(&code, "table").contains(&".ColumnDefinitions(\"1*,1*\")".to_string()), "{code}"); + assert!(code.contains("// not mapped: fractional grid track sizes"), "{code}"); +} + +#[test] +fn a_grid_writes_at_most_sixty_four_tracks_per_axis() { + let mut s = Session::new(); + let tracks: Vec = (0..70).map(|_| json!("1fr")).collect(); + let g = grid(&mut s, json!({ "columnTracks": tracks })); + for i in 0..3 { + rect(&mut s, g, 5.0, 5.0, &format!("R{i}")); + } + let code = uno(&mut s, g); + let defs = chain(&code, "table").into_iter().find(|l| l.starts_with(".ColumnDefinitions(")).unwrap_or_default(); + assert_eq!(defs.matches('*').count(), 64, "{defs}"); + assert!(code.contains("// not mapped: more than 64 grid tracks"), "{code}"); +} + +#[test] +fn grid_children_align_in_their_cell_and_a_filling_one_stretches() { + let mut s = Session::new(); + let g = grid(&mut s, json!({"columnTracks": ["1fr", "1fr"], "rowTracks": ["1fr"], "mainAlign": "center", "crossAlign": "max"})); + let a = rect(&mut s, g, 20.0, 20.0, "A"); + let b = rect(&mut s, g, 20.0, 20.0, "B"); + set(&mut s, a, json!({"gridAlignH": "max", "gridAlignV": "min"})); + set(&mut s, b, json!({"sizingH": "fill", "sizingV": "fill"})); + let code = uno(&mut s, g); + let (ka, kb) = (chain(&code, "a"), chain(&code, "b")); + assert!(ka.contains(&".HorizontalAlignment(HorizontalAlignment.Right)".to_string()), "{code}"); + assert!(ka.contains(&".VerticalAlignment(VerticalAlignment.Top)".to_string()), "{code}"); + assert!(!kb.iter().any(|l| l.starts_with(".HorizontalAlignment") || l.starts_with(".VerticalAlignment") || l.starts_with(".Width(")), "{code}"); + // With no alignment of its own a child takes the frame's. + let c = rect(&mut s, g, 20.0, 20.0, "C"); + let _ = c; + let code = uno(&mut s, g); + assert!(chain(&code, "c").contains(&".HorizontalAlignment(HorizontalAlignment.Center)".to_string()), "{code}"); + assert!(chain(&code, "c").contains(&".VerticalAlignment(VerticalAlignment.Bottom)".to_string()), "{code}"); +} + +#[test] +fn an_absolute_child_of_a_grid_spans_all_cells_at_its_offset_inside_the_padding() { + let mut s = Session::new(); + let g = grid(&mut s, json!({"columnTracks": ["1fr", "1fr"], "rowTracks": ["1fr"], "padding": 10})); + rect(&mut s, g, 20.0, 20.0, "A"); + let badge = rect(&mut s, g, 12.0, 12.0, "Badge"); + set(&mut s, badge, json!({"absolute": true, "x": 30, "y": 40})); + let code = uno(&mut s, g); + let c = chain(&code, "badge"); + assert_eq!(c[0], ".Grid(row: 0, column: 0, rowSpan: 1, columnSpan: 2)", "{code}"); + assert!(c.contains(&".Margin(20, 30, 0, 0)".to_string()), "{code}"); +} + +#[test] +fn wrapping_is_one_line_and_a_note() { + let mut s = Session::new(); + let f = row(&mut s, json!({"wrap": true})); + let code = uno(&mut s, f); + assert!(code.contains("// not mapped: wrap (FlexPanel needs Uno.Toolkit 10; one line written)"), "{code}"); + assert!(code.contains("new AutoLayout()"), "{code}"); + set(&mut s, f, json!({"wrap": false})); + assert!(!uno(&mut s, f).contains("wrap (FlexPanel")); +} From 7429df2c13f79b0442f3ff51e11bcc1c4b06029d Mon Sep 17 00:00:00 2001 From: Andrej Skvorc Date: Sat, 14 Nov 2026 08:19:22 +0100 Subject: [PATCH 21/48] M6: Uno text: half-leading for explicit line heights An explicit line height puts half the leading above the first line in FigCraft and all of it below in Uno. Text moves down by h = (L - (ascent + descent) / upem * size) / 2 from the face FigCraft draws with: a top padding with a negative bottom margin in a panel (merged with an independent child's margin), the offset in a Canvas. A line height below the font's natural height and a family that is not installed are notes. --- crates/engine/src/dev/codegen/uno.rs | 83 +++++++++++++++++++++++++- crates/engine/src/uno_codegen_tests.rs | 79 +++++++++++++++++++++++- 2 files changed, 158 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/dev/codegen/uno.rs b/crates/engine/src/dev/codegen/uno.rs index c626c9471..230c85370 100644 --- a/crates/engine/src/dev/codegen/uno.rs +++ b/crates/engine/src/dev/codegen/uno.rs @@ -696,16 +696,25 @@ impl Gen<'_> { } /// Text: a `TextBlock`, in a `Grid` of the box's height when it is aligned to the middle or - /// bottom of a fixed box. + /// bottom of a fixed box. An explicit line height puts half the leading above the first line in + /// FigCraft and all of it below in Uno, so the text is moved down by the half-leading. fn text(&mut self, n: &Node, t: &TextData, at: Place) -> Element { let fixed = matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Truncate); let framed = fixed && t.align_v != TextAlignV::Top; let mut tb = text_block(n, t, !framed, line_axes(n, at)); + let leading = leading(&t.style); + // In a `Canvas` the offset takes the shift; anywhere else the recipe below does. + let at_text = match (leading, at) { + (Leading::Shift(h), Place::At(x, y)) if !framed => Place::At(x, y + h), + _ => at, + }; if !framed { - place(&mut tb, n, at); + place(&mut tb, n, at_text); + leading_calls(&mut tb, leading, !matches!(at_text, Place::At(..))); common(&mut tb, n); return tb; } + leading_calls(&mut tb, leading, true); tb.call(format!(".VerticalAlignment(VerticalAlignment.{})", if t.align_v == TextAlignV::Middle { "Center" } else { "Bottom" })); let mut g = Element::new("new Grid()"); place(&mut g, n, at); @@ -909,6 +918,76 @@ fn padding_call(e: &mut Element, pad: [f64; 4]) { } } +/// What an explicit line height asks of a text. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Leading { + /// An automatic line height, or one so close to the font's own that there is nothing to move. + None, + /// The text moves down by the half-leading (pixels). + Shift(f64), + /// The line height is below the font's natural height. + Tight, + /// The font family is not installed where the code is written, so its metrics are unknown. + NoFont, +} + +/// The half-leading of a text style: `h = (L - (ascent + descent) / upem * size) / 2` for the +/// explicit line height `L`, from the face FigCraft itself draws with. The number depends on the +/// fonts installed where `inspect.code` runs. `find_face` falls back to the default face, so +/// `has_family` tells whether the family is really here. +fn leading(s: &TextStyle) -> Leading { + let size = s.font_size; + if !size.is_finite() || size <= 0.0 { + return Leading::None; + } + let l = match s.line_height { + LineHeight::Pixels(v) if v > 0.0 && v.is_finite() => v, + LineHeight::Percent(p) if p > 0.0 && p.is_finite() => p / 100.0 * size, + _ => return Leading::None, + }; + if !figcraft_text::has_family(&s.font_family) { + return Leading::NoFont; + } + let Some(face) = figcraft_text::find_face(&s.font_family, &s.font_style) else { return Leading::NoFont }; + if face.upem <= 0.0 || !face.upem.is_finite() { + return Leading::NoFont; + } + let h = (l - (face.ascent + face.descent) / face.upem * size) / 2.0; + if !h.is_finite() || h.abs() < 0.5 { + Leading::None + } else if h < 0.0 { + // Uno never draws a line closer than the font's natural height (`BlockLineHeight` was tried + // for this and is left to a harness check), so the case is noted, not mapped. + Leading::Tight + } else { + Leading::Shift(h) + } +} + +/// The calls (or note) a [`Leading`] needs. `flow`: the text sits in a panel, where the shift is a +/// top padding with a negative bottom margin that gives the room back (the box keeps its height +/// and the last line is not cut); an existing margin (an independent child's offsets) is merged. +fn leading_calls(e: &mut Element, leading: Leading, flow: bool) { + match leading { + Leading::None => {} + Leading::Tight => e.note("line height below the font's natural height is not reproduced in Uno"), + Leading::NoFont => e.note("line height shift (the font is not installed here, so its metrics are unknown)"), + Leading::Shift(h) if flow => { + e.call(format!(".Padding(0, {}, 0, 0)", num(h))); + match e.calls.iter().position(|c| c.starts_with(".Margin(") && c.ends_with(", 0, 0)")) { + Some(i) => { + if let Some(c) = e.calls.get_mut(i) { + let head = c.trim_end_matches(", 0, 0)").to_string(); + *c = format!("{head}, 0, {})", num(-h)); + } + } + None => e.call(format!(".Margin(0, 0, 0, {})", num(-h))), + } + } + Leading::Shift(_) => {} + } +} + /// The calls an `AutoLayout` takes for its orientation, gap, padding (`pad` is top, right, /// bottom, left as written) and alignment. fn layout_calls(e: &mut Element, l: &AutoLayout, pad: [f64; 4]) { diff --git a/crates/engine/src/uno_codegen_tests.rs b/crates/engine/src/uno_codegen_tests.rs index 37bc4b19c..fd4b7dd91 100644 --- a/crates/engine/src/uno_codegen_tests.rs +++ b/crates/engine/src/uno_codegen_tests.rs @@ -181,14 +181,14 @@ fn text_maps_its_style_and_box() { set( &mut s, t, - json!({"fontFamily": "Inter", "fontSize": 16, "fontWeight": 600, "fontStyle": "Semi Bold Italic", "letterSpacing": 2, "lineHeight": "150%", "textDecoration": "underline", "textAlign": "center", "width": 150, "textAutoResize": "height", "fill": "#112233"}), + json!({"fontFamily": "Zzyzx Test Family", "fontSize": 16, "fontWeight": 600, "fontStyle": "Semi Bold Italic", "letterSpacing": 2, "lineHeight": "150%", "textDecoration": "underline", "textAlign": "center", "width": 150, "textAutoResize": "height", "fill": "#112233"}), ); let code = uno(&mut s, f); assert!(code.contains("using Microsoft.UI.Text;"), "{code}"); for line in [ ".Canvas(left: 10, top: 12)", ".Text(\"Say \\\"hi\\\"\\n\\\\\")", - ".FontFamily(\"Inter\")", + ".FontFamily(\"Zzyzx Test Family\")", ".FontSize(16)", ".FontWeight(FontWeights.SemiBold)", ".FontStyle(FontStyle.Italic)", @@ -795,3 +795,78 @@ fn wrapping_is_one_line_and_a_note() { set(&mut s, f, json!({"wrap": false})); assert!(!uno(&mut s, f).contains("wrap (FlexPanel")); } + +/// A text in `parent` with an explicit pixel line height, in the first installed family (any, as the +/// formula is checked against the face the code itself asks for). `None` when no font is installed. +fn spaced_text(s: &mut Session, parent: NodeId, line_height: f64) -> Option<(NodeId, f64)> { + // The fonts of the machine; a face that exists nearly everywhere is preferred. + figcraft_text::scan_system_fonts(); + let family = ["DejaVu Sans", "Liberation Sans", "Arial"].into_iter().find(|f| figcraft_text::has_family(f)).map(str::to_string); + let family = family.or_else(|| figcraft_text::family_names().into_iter().next())?; + let t = idv(&ex(s, "text.create", json!({"text": "One\nTwo\nThree", "x": 7, "y": 9, "parent": parent, "props": {"name": "Para"}}))); + set(s, t, json!({"fontFamily": family, "fontSize": 20, "lineHeight": line_height, "textAutoResize": "widthAndHeight"})); + let style = match &s.doc().ok()?.node(t)?.kind { + NodeKind::Text(td) => td.style.clone(), + _ => return None, + }; + let face = figcraft_text::find_face(&style.font_family, &style.font_style)?; + Some((t, (line_height - (face.ascent + face.descent) / face.upem * 20.0) / 2.0)) +} + +#[test] +fn half_leading_moves_text_down_with_padding_in_a_flow_and_the_offset_in_a_canvas() { + use crate::codegen::num; + let mut s = Session::new(); + let col = row(&mut s, json!({"layout": "vertical"})); + let Some((_, h)) = spaced_text(&mut s, col, 60.0) else { return }; + assert!(h > 0.5, "60 px lines are looser than any 20 px font"); + let code = uno(&mut s, col); + let c = chain(&code, "para"); + assert!(c.contains(&".LineHeight(60)".to_string()), "{code}"); + assert!(c.contains(&format!(".Padding(0, {}, 0, 0)", num(h))), "{c:?}"); + assert!(c.contains(&format!(".Margin(0, 0, 0, {})", num(-h))), "{c:?}"); + assert!(!c.iter().any(|l| l.starts_with(".Height(")), "never a height of n lines: {c:?}"); + // In a canvas the offset takes the shift and there is no padding. + let free = frame(&mut s, "Free", 200.0, 200.0); + let (_, h) = spaced_text(&mut s, free, 60.0).unwrap_or((free, 0.0)); + let code = uno(&mut s, free); + let c = chain(&code, "para"); + assert_eq!(c[0], format!(".Canvas(left: 7, top: {})", num(9.0 + h)), "{c:?}"); + assert!(!c.iter().any(|l| l.starts_with(".Padding(") || l.starts_with(".Margin(")), "{c:?}"); +} + +#[test] +fn half_leading_merges_with_the_margin_of_an_independent_child() { + use crate::codegen::num; + let mut s = Session::new(); + let col = row(&mut s, json!({"layout": "vertical"})); + let Some((t, h)) = spaced_text(&mut s, col, 60.0) else { return }; + set(&mut s, t, json!({"absolute": true, "x": 30, "y": 40})); + let c = chain(&uno(&mut s, col), "para"); + assert!(c.contains(&format!(".Margin(30, 40, 0, {})", num(-h))), "{c:?}"); + assert_eq!(c.iter().filter(|l| l.starts_with(".Margin(")).count(), 1, "{c:?}"); +} + +#[test] +fn a_line_height_below_the_font_is_noted_and_an_automatic_one_needs_nothing() { + let mut s = Session::new(); + let col = row(&mut s, json!({"layout": "vertical"})); + let Some((t, _)) = spaced_text(&mut s, col, 1.0) else { return }; + let c = chain(&uno(&mut s, col), "para"); + assert!(c.contains(&"// not mapped: line height below the font's natural height is not reproduced in Uno".to_string()), "{c:?}"); + assert!(!c.iter().any(|l| l.starts_with(".Padding(") || l.starts_with(".Margin(")), "{c:?}"); + set(&mut s, t, json!({"lineHeight": "auto"})); + let c = chain(&uno(&mut s, col), "para"); + assert!(!c.iter().any(|l| l.starts_with(".Padding(") || l.starts_with(".Margin(") || l.starts_with("//")), "{c:?}"); +} + +#[test] +fn a_font_that_is_not_installed_gets_no_shift_and_a_note() { + let mut s = Session::new(); + let col = row(&mut s, json!({"layout": "vertical"})); + let t = idv(&ex(&mut s, "text.create", json!({"text": "Hi", "x": 0, "y": 0, "parent": col, "props": {"name": "Para"}}))); + set(&mut s, t, json!({"fontFamily": "Nonexistent Family Zzyzx", "fontSize": 20, "lineHeight": 60})); + let c = chain(&uno(&mut s, col), "para"); + assert!(c.iter().any(|l| l.starts_with("// not mapped: line height shift")), "{c:?}"); + assert!(!c.iter().any(|l| l.starts_with(".Padding(") || l.starts_with(".Margin(")), "{c:?}"); +} From fe7b9d0495c3f28d2ff79e1e4a58d56a5695138f Mon Sep 17 00:00:00 2001 From: Andrej Skvorc Date: Sat, 14 Nov 2026 08:35:31 +0100 Subject: [PATCH 22/48] M6: Uno vectors as Path and docs for the layer code card Vectors, booleans and shapes are a Microsoft.UI.Xaml.Shapes.Path with path data from the node's outline (F1 non-zero, F0 even-odd, at most 5,000 elements), one solid fill and one solid stroke; stroke inside or outside is a note. Gradients, several paints, effects and over-cap outlines fall back to a PNG Image. Docs: parity, MCP, gaps, ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/dev/codegen.rs | 2 +- crates/engine/src/dev/codegen/uno.rs | 72 ++++++++++++- crates/engine/src/uno_codegen_tests.rs | 141 ++++++++++++++++++++++--- docs/gaps.md | 8 +- docs/mcp.md | 38 +++++-- 6 files changed, 229 insertions(+), 33 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 1a62ea0c0..c57998246 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-14 | minor | M6: Uno C# Markup code, auto layout and vectors (ours): a frame with horizontal or vertical auto layout is a Toolkit `AutoLayout` that takes the box itself (`Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`) with `Orientation`, `Spacing`, `Padding` (less the stroke weight unless strokes are included; where that goes negative the border sits behind the layout in a `Grid`), `PrimaryAxisAlignment`, `CounterAxisAlignment` and `Justify`; children are sized per axis (fixed writes the length, hug none, fill stretches with the attached `AutoLayout` call, min and max lengths on the child), text hugs, fills or is fixed, a child that ignores the layout is independent at its offset (a hugging parent with one is written at its size), and `reverse_z` paints with descending `Canvas.ZIndex`; grid mode is a `Grid` with `ColumnDefinitions` / `RowDefinitions` (pixels, `Auto`, whole-number stars), `ColumnSpacing` / `RowSpacing`, children in the cell the layout crate gives them (`.Grid(row:, column:, rowSpan:, columnSpan:)`) aligned in it; wrap is one line with a note; frames without auto layout keep the `Canvas` with one warning per view that counts them; an explicit line height moves the text down by the half-leading of the face FigCraft draws with (a top padding with a negative bottom margin in a panel, the offset in a `Canvas`; the number depends on the fonts installed where `inspect.code` runs; a line height below the font's natural height is a note); vectors, booleans and shapes are a `Microsoft.UI.Xaml.Shapes.Path` with path data (`F1` non-zero, `F0` even-odd; at most 5,000 elements), one solid fill and one solid stroke, falling back to a PNG `Image` for gradients, several paints, effects and over the cap; containers are locals and children go in with `Children.Add(x)` / `Child = x`, since fluent `.Children(…)` doubles the load time with every level of nesting. Numbers unchanged (the incumbent has no such target). | | 2026-11-10 | minor | M6: Uno Platform C# Markup code (ours; the incumbent generates CSS, iOS and Android only): `inspect.code {language: uno}` (aliases `csharp-markup`, `cs-markup`) writes a `UserControl` class whose content is a fluent C# Markup tree for a layer: a frame, group or rectangle is a `Border` (fill as `Color.FromArgb`, border brush and thickness, per-side thickness, per-corner radius, opacity, rotation) holding a `Canvas` with the children at their offsets (a stroke and children put the border behind the canvas in a `Grid`, so the stroke does not push the children in), an ellipse is an `Ellipse`, text is a `TextBlock` (family, size, weight, italic, colour, line height, character spacing, alignment, wrapping, trimming and max lines from the auto resize mode, decoration, case applied when the code runs, mixed styles as `Run`s) and vectors and other shapes are an `Image` on an SVG asset (`ms-appx:///Assets/.svg`, a lowercase ASCII name unique in the snippet) with a comment to export it; image fills are an `ImageBrush` on a PNG asset. Fixed sizes everywhere; auto layout, variables, components and the project export are later steps. Shadows, blurs, blend modes, gradients beyond the first stop, masks and corner smoothing stay as `// not mapped: …` comments in the chain. Not offered for code connect or component code yet. Headline numbers unchanged. | | 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged | | 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/crates/engine/src/dev/codegen.rs b/crates/engine/src/dev/codegen.rs index e62b1ab82..861260f14 100644 --- a/crates/engine/src/dev/codegen.rs +++ b/crates/engine/src/dev/codegen.rs @@ -39,7 +39,7 @@ pub(crate) use html::{Markup, Names, class_name}; pub(crate) use swift::swift; pub(crate) use uno::uno; #[cfg(test)] -pub(crate) use uno::{asset_name, cs_ident, cs_literal, cs_unique}; +pub(crate) use uno::{asset_name, cs_ident, cs_literal, cs_unique, path_data}; pub fn specs() -> Vec { vec![spec!( diff --git a/crates/engine/src/dev/codegen/uno.rs b/crates/engine/src/dev/codegen/uno.rs index 230c85370..7ee5b1aa9 100644 --- a/crates/engine/src/dev/codegen/uno.rs +++ b/crates/engine/src/dev/codegen/uno.rs @@ -682,19 +682,56 @@ impl Gen<'_> { e } - /// A vector, shape or other layer without a counterpart: the image the app is to hold. + /// A vector, shape or other layer without a counterpart: a `Path` with the outline as path + /// data, which takes the theme's colours; or, when the layer is more than one plain fill and + /// one plain stroke, the image the app is to hold. fn asset(&mut self, n: &Node, at: Place) -> Element { + if let Some(e) = self.path(n, at) { + return e; + } let name = asset_name(&n.name, n.kind.label(), &mut self.assets); let mut e = Element::new("new Image()"); - e.lead.push(format!("// {} \"{}\": export it as an SVG to Assets/{name}.svg", n.kind.label(), comment_name(&n.name))); + e.lead.push(format!("// {} \"{}\": export it as a PNG to Assets/{name}.png", n.kind.label(), comment_name(&n.name))); place(&mut e, n, at); - e.call(format!(".Source(\"{ASSETS}/{name}.svg\")")); + e.call(format!(".Source(\"{ASSETS}/{name}.png\")")); size(&mut e, n, at); e.call(".Stretch(Stretch.Uniform)"); common(&mut e, n); e } + /// The layer's outline as a `Microsoft.UI.Xaml.Shapes.Path` (written in full: the implicit + /// usings bring in `System.IO`, whose `Path` clashes), with at most one solid fill and one solid + /// stroke. `None` when the layer needs the image: a gradient, image or pattern paint, several + /// fills or strokes, effects, no outline, or an outline past [`MAX_PATH_ELEMENTS`]. + fn path(&mut self, n: &Node, at: Place) -> Option { + let fills: Vec<_> = n.fills.iter().filter(|p| p.visible).collect(); + let strokes: Vec<_> = n.strokes.iter().filter(|p| p.visible).collect(); + let plain = |ps: &[&figcraft_color::Paint]| ps.iter().all(|p| matches!(p.kind, PaintKind::Solid { .. })); + if fills.len() > 1 || strokes.len() > 1 || !plain(&fills) || !plain(&strokes) || n.effects.iter().any(|f| f.visible) { + return None; + } + let (outline, rule) = figcraft_render::node_outline(self.ctx.doc, n)?; + let data = path_data(&outline, rule)?; + let mut e = Element::new("new Microsoft.UI.Xaml.Shapes.Path()"); + place(&mut e, n, at); + e.call(format!(".Data({})", cs_literal(&data))); + if let Some(c) = first_fill(n) { + e.call(format!(".Fill({})", cs_color(c))); + } + if let Some(c) = stroke_color(n) { + e.call(format!(".Stroke({})", cs_color(c))); + e.call(format!(".StrokeThickness({})", num(n.stroke.weight))); + if n.stroke.align != StrokeAlign::Center { + // A `Path` stroke is centred on the outline. + e.note("stroke inside or outside (drawn centred)"); + } + } + size(&mut e, n, at); + common(&mut e, n); + Some(e) + } + /// Text: a `TextBlock`, in a `Grid` of the box's height when it is aligned to the middle or /// bottom of a fixed box. An explicit line height puts half the leading above the first line in /// FigCraft and all of it below in Uno, so the text is moved down by the half-leading. @@ -988,6 +1025,35 @@ fn leading_calls(e: &mut Element, leading: Leading, flow: bool) { } } +/// Most elements (moves, lines, curves, closes) of an outline written as path data. +const MAX_PATH_ELEMENTS: usize = 5_000; + +/// An outline as the path mini-language of `Path.Data`: a fill rule (`F1` non-zero, `F0` even-odd) +/// then `M x y`, `L x y`, `Q cx cy x y`, `C c1x c1y c2x c2y x y` and `Z`, numbers through [`num`]. +/// `None` for an empty outline, one with a coordinate that is not finite, or one past +/// [`MAX_PATH_ELEMENTS`]. +pub(crate) fn path_data(path: &figcraft_geom::BezPath, rule: figcraft_render::FillRule) -> Option { + use figcraft_geom::kurbo::PathEl; + let els = path.elements(); + if els.is_empty() || els.len() > MAX_PATH_ELEMENTS { + return None; + } + let pt = |p: figcraft_geom::Point| (p.x.is_finite() && p.y.is_finite()).then(|| format!("{} {}", num(p.x), num(p.y))); + let mut out = String::from(if rule == figcraft_render::FillRule::EvenOdd { "F0" } else { "F1" }); + for el in els { + let part = match *el { + PathEl::MoveTo(p) => format!("M {}", pt(p)?), + PathEl::LineTo(p) => format!("L {}", pt(p)?), + PathEl::QuadTo(c, p) => format!("Q {} {}", pt(c)?, pt(p)?), + PathEl::CurveTo(c1, c2, p) => format!("C {} {} {}", pt(c1)?, pt(c2)?, pt(p)?), + PathEl::ClosePath => "Z".to_string(), + }; + out.push(' '); + out.push_str(&part); + } + Some(out) +} + /// The calls an `AutoLayout` takes for its orientation, gap, padding (`pad` is top, right, /// bottom, left as written) and alignment. fn layout_calls(e: &mut Element, l: &AutoLayout, pad: [f64; 4]) { diff --git a/crates/engine/src/uno_codegen_tests.rs b/crates/engine/src/uno_codegen_tests.rs index fd4b7dd91..daebf5125 100644 --- a/crates/engine/src/uno_codegen_tests.rs +++ b/crates/engine/src/uno_codegen_tests.rs @@ -252,21 +252,6 @@ fn mixed_styles_become_runs() { assert!(!code.contains(".Text(\"Plain bold end\")"), "{code}"); } -#[test] -fn vectors_are_svg_assets_with_unique_lowercase_names() { - let mut s = Session::new(); - let f = frame(&mut s, "Icons", 200.0, 100.0); - for x in [0, 50, 100] { - ex(&mut s, "node.create", json!({"type": "star", "parent": f, "name": "Star Icon", "x": x, "y": 0, "width": 40, "height": 40})); - } - let code = uno(&mut s, f); - for n in ["star_icon", "star_icon_2", "star_icon_3"] { - assert!(code.contains(&format!(".Source(\"ms-appx:///Assets/{n}.svg\")")), "{n} in {code}"); - assert!(code.contains(&format!("// Star \"Star Icon\": export it as an SVG to Assets/{n}.svg")), "{code}"); - } - assert!(code.contains(".Stretch(Stretch.Uniform)"), "{code}"); -} - #[test] fn an_image_fill_is_an_image_brush_on_a_png_asset() { use base64::Engine as _; @@ -870,3 +855,129 @@ fn a_font_that_is_not_installed_gets_no_shift_and_a_note() { assert!(c.iter().any(|l| l.starts_with("// not mapped: line height shift")), "{c:?}"); assert!(!c.iter().any(|l| l.starts_with(".Padding(") || l.starts_with(".Margin(")), "{c:?}"); } + +#[test] +fn path_data_writes_moves_lines_curves_and_closes_with_the_fill_rule() { + use crate::codegen::path_data; + use figcraft_geom::BezPath; + use figcraft_render::FillRule; + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((24.0, 0.0)); + p.quad_to((30.5, 6.25), (24.0, 12.0)); + p.curve_to((20.0, 20.0), (4.0, 20.125), (0.0, 12.0)); + p.close_path(); + assert_eq!(path_data(&p, FillRule::Winding).as_deref(), Some("F1 M 0 0 L 24 0 Q 30.5 6.25 24 12 C 20 20 4 20.13 0 12 Z")); + assert!(path_data(&p, FillRule::EvenOdd).is_some_and(|d| d.starts_with("F0 M 0 0"))); + // An open path has no Z; a second subpath starts with its own M. + let mut open = BezPath::new(); + open.move_to((1.0, 2.0)); + open.line_to((3.0, 4.0)); + open.move_to((5.0, 6.0)); + open.line_to((7.0, 8.0)); + assert_eq!(path_data(&open, FillRule::Winding).as_deref(), Some("F1 M 1 2 L 3 4 M 5 6 L 7 8")); +} + +#[test] +fn path_data_refuses_empty_non_finite_and_huge_outlines() { + use crate::codegen::path_data; + use figcraft_geom::BezPath; + use figcraft_render::FillRule; + assert!(path_data(&BezPath::new(), FillRule::Winding).is_none()); + let mut bad = BezPath::new(); + bad.move_to((0.0, 0.0)); + bad.line_to((f64::NAN, 1.0)); + assert!(path_data(&bad, FillRule::Winding).is_none()); + let mut inf = BezPath::new(); + inf.move_to((0.0, f64::INFINITY)); + assert!(path_data(&inf, FillRule::Winding).is_none()); + let mut huge = BezPath::new(); + huge.move_to((0.0, 0.0)); + for i in 0..5_000 { + huge.line_to((f64::from(i), 1.0)); + } + assert!(path_data(&huge, FillRule::Winding).is_none(), "5,001 elements are past the cap"); + let mut ok = BezPath::new(); + ok.move_to((0.0, 0.0)); + for i in 0..4_999 { + ok.line_to((f64::from(i), 1.0)); + } + assert!(path_data(&ok, FillRule::Winding).is_some()); +} + +#[test] +fn a_star_is_a_path_with_its_fill_and_size_and_no_asset() { + let mut s = Session::new(); + let f = frame(&mut s, "Icons", 100.0, 100.0); + let star = + idv(&ex(&mut s, "node.create", json!({"type": "star", "parent": f, "name": "Star Icon", "x": 10, "y": 20, "width": 40, "height": 40}))); + set(&mut s, star, json!({"fill": "#141414"})); + let code = uno(&mut s, f); + let c = chain(&code, "starIcon"); + assert_eq!(c.first().map(String::as_str), Some(".Canvas(left: 10, top: 20)"), "{code}"); + let data = c.iter().find(|l| l.starts_with(".Data(\"F1 M ")).cloned().unwrap_or_default(); + assert!(data.ends_with(" Z\")") && data.contains(" L "), "{c:?}"); + assert!(c.contains(&".Fill(Color.FromArgb(0xFF, 0x14, 0x14, 0x14))".to_string()), "{c:?}"); + assert!(c.contains(&".Width(40)".to_string()) && c.contains(&".Height(40)".to_string()), "{c:?}"); + assert!(code.contains("var starIcon = new Microsoft.UI.Xaml.Shapes.Path()"), "{code}"); + assert!(!code.contains("Assets/") && !code.contains(".svg") && !code.contains("new Image()"), "{code}"); +} + +#[test] +fn a_boolean_result_and_an_even_odd_outline_are_paths_too() { + let mut s = Session::new(); + let f = frame(&mut s, "Shapes", 200.0, 100.0); + let a = idv(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40, "parent": f, "props": {"name": "A"}}))); + let b = idv(&ex(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40, "parent": f, "props": {"name": "B"}}))); + let u = idv(&ex(&mut s, "bool.union", json!({"ids": [a, b]}))); + set(&mut s, u, json!({"name": "Union", "fill": "#00FF00"})); + let code = uno(&mut s, f); + let c = chain(&code, "union"); + assert!(c.iter().any(|l| l.starts_with(".Data(\"F") && l.contains(" M ")), "{code}"); + // A boolean's result is even-odd; a star is non-zero. + assert!(c.iter().any(|l| l.starts_with(".Data(\"F0 ")), "{c:?}"); + assert!(!code.contains("export it as"), "{code}"); +} + +#[test] +fn a_stroked_vector_has_a_centred_stroke_and_a_note_for_inside_or_outside() { + let mut s = Session::new(); + let f = frame(&mut s, "Strokes", 100.0, 100.0); + let v = idv(&ex(&mut s, "node.create", json!({"type": "star", "parent": f, "name": "Line Star", "x": 0, "y": 0, "width": 30, "height": 30}))); + set(&mut s, v, json!({"fill": "#FF0000", "stroke": "#0000FF", "strokeWeight": 2, "strokeAlign": "center"})); + let c = chain(&uno(&mut s, f), "lineStar"); + assert!(c.contains(&".Stroke(Color.FromArgb(0xFF, 0x00, 0x00, 0xFF))".to_string()) && c.contains(&".StrokeThickness(2)".to_string()), "{c:?}"); + assert!(!c.iter().any(|l| l.starts_with("//")), "{c:?}"); + set(&mut s, v, json!({"strokeAlign": "inside"})); + let c = chain(&uno(&mut s, f), "lineStar"); + assert!(c.contains(&"// not mapped: stroke inside or outside (drawn centred)".to_string()), "{c:?}"); +} + +#[test] +fn vectors_that_a_path_cannot_draw_are_png_assets_with_unique_lowercase_names() { + let mut s = Session::new(); + let f = frame(&mut s, "Icons", 300.0, 100.0); + let gradient = json!({"type": "gradient", "kind": "linear", + "stops": [{"position": 0, "color": {"r": 1, "g": 0, "b": 0, "a": 1}}, {"position": 1, "color": {"r": 0, "g": 0, "b": 1, "a": 1}}], + "from": [0, 0.5], "to": [1, 0.5]}); + let mut ids = Vec::new(); + for x in [0, 50, 100, 150] { + ids.push(idv(&ex( + &mut s, + "node.create", + json!({"type": "star", "parent": f, "name": "Star Icon", "x": x, "y": 0, "width": 40, "height": 40}), + ))); + } + set(&mut s, ids[0], json!({"fills": [gradient]})); + set(&mut s, ids[1], json!({"fills": ["#FF0000", "#00FF00"]})); + set(&mut s, ids[2], json!({"effects": [{"type": "dropShadow", "color": "#00000040", "offset": [0, 4], "radius": 8}]})); + let code = uno(&mut s, f); + for n in ["star_icon", "star_icon_2", "star_icon_3"] { + assert!(code.contains(&format!(".Source(\"ms-appx:///Assets/{n}.png\")")), "{n} in {code}"); + assert!(code.contains(&format!("// Star \"Star Icon\": export it as a PNG to Assets/{n}.png")), "{code}"); + } + assert!(code.contains(".Stretch(Stretch.Uniform)"), "{code}"); + // The fourth is plain: a path, and it takes no asset name. + assert_eq!(code.matches("new Microsoft.UI.Xaml.Shapes.Path()").count(), 1, "{code}"); + assert!(!code.contains("star_icon_4") && !code.contains(".svg"), "{code}"); +} diff --git a/docs/gaps.md b/docs/gaps.md index e088b4696..06565a9ed 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -477,9 +477,11 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe - **Landed (2026-10-24):** files dropped on the canvas, the Pages list and the Assets panel no longer edit the design in Dev Mode (a dropped document still opens as a file of its own, and the Pages list only opens pages). -- **Landed (2026-11-10):** Uno Platform C# Markup for layers: `inspect.code {language: uno}` writes frames, groups, rectangles, - ellipses, text (also mixed styles) and image or vector assets as a fluent C# tree (a `Border` with a `Canvas` for the children at their - offsets, `TextBlock`, `Ellipse`, `Image`), fixed sizes. Still to do: auto layout (`AutoLayout` panels), variables as theme resources, +- **Landed (2026-11-14):** Uno Platform C# Markup for layers: `inspect.code {language: uno}` writes frames with horizontal, vertical or + grid auto layout (`AutoLayout`, `Grid`; sizing per axis, absolute children, first-on-top order), frames without auto layout + (`Border` with a `Canvas`, one warning per view), groups, rectangles, ellipses, text (also mixed styles, with the half-leading of + explicit line heights), vectors and booleans as `Path` data, and PNG assets for what a path cannot draw. Children are added with + `Children.Add` / `Child =`. Still to do: wrapping layouts (`FlexPanel`, needs Uno Toolkit 10), variables as theme resources, components, variants and code connect for Uno, a folder export that writes the asset files. - **Landed (2026-10-30):** `figcraft-cli connect publish [--mappings figcraft.connect.json] [--dry-run]` publishes a code repository's mappings to a design file, so diff --git a/docs/mcp.md b/docs/mcp.md index a67ae432e..18070e2d7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1765,17 +1765,33 @@ permissions: without it nothing is downloaded); `plugin.directory.publish {path {id?, language?}` returns the parts: `{component, name, set, properties: [{name, param, type, default, value? (instances)}], definition, usage? (instances)}`. - **Uno C# Markup:** `inspect.code {id, language: uno}` (aliases `csharp-markup`, `cs-markup`) writes the layer and its subtree as a - `UserControl` class (file-scoped `namespace MyApp;`, the class named after the layer plus `View`, internal) whose `this.Content(…)` is a - Uno C# Markup (`Uno.Extensions.Markup`) expression: a frame, group or rectangle is a `Border` with `Background`, `BorderBrush`, - `BorderThickness` (a `Thickness` for per-side strokes), `CornerRadius` (per corner when they differ), `Opacity` and a - `RenderTransform` for rotation, holding a `Canvas` whose children carry `.Canvas(left:, top:)`; with a stroke and children it is a - `Grid` with the border behind the canvas. Text is a `TextBlock` (`FontFamily`, `FontSize`, `FontWeight`, `FontStyle`, `Foreground`, - `LineHeight`, `CharacterSpacing` in thousandths of an em, `TextAlignment`, `TextWrapping`, `TextTrimming`, `MaxLines`, - `TextDecorations`; case is applied at run time; style runs are `Inlines` of `Run`s). Vectors and other shapes are an `Image` on - `ms-appx:///Assets/.svg`, image fills an `ImageBrush` on `.png` (names lowercase ASCII, unique in the snippet; the files - are not written). Everything has a fixed size. Shadows, blurs, blend modes, masks, gradients beyond the first stop, pattern fills, - stroke alignment other than inside, corner smoothing and arcs are `// not mapped: …` comments. Components and instances are written - as the frames they are; `inspect.componentCode` and code connect do not take `uno` yet. + `UserControl` class (file-scoped `namespace MyApp;`, the class named after the layer plus `View`, internal) whose constructor builds the + tree with Uno C# Markup (`Uno.Extensions.Markup`) and ends with `Content = root;`. Each element is a local with fluent property setters; + its children are added with `parent.Children.Add(child)` or `parent.Child = child`, never the fluent `.Children(…)` / `.Child(…)`, + whose load time doubles with every level of nesting. A frame with horizontal or vertical auto layout is a Toolkit `AutoLayout` that takes + the box itself (`Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`, `Opacity`) with `Orientation`, `Spacing`, `Padding` (less + the stroke weight unless the layout includes strokes; where a side would go negative the border sits behind the layout in a `Grid`), + `PrimaryAxisAlignment`, `CounterAxisAlignment` and `Justify`; space around and evenly are written as space between, baseline alignment + and a wrapping layout are `// not mapped: …` notes (a wrapping layout is one line). Children are sized per axis: fixed writes `Width` / + `Height`, hug writes none, fill stretches with `.AutoLayout(primaryAlignment:, counterAlignment:)`, `MinWidth` / `MaxWidth` / `MinHeight` + / `MaxHeight` go on the child; a child that ignores the layout is `.AutoLayout(isIndependentLayout: true)` at its offset as a `Margin` + (a hugging parent with one is written at its current size), and "first on top" is a descending `.Canvas(zIndex: n)`. A grid is a `Grid` + with `ColumnDefinitions` / `RowDefinitions` (pixels, `Auto`, whole-number stars: fractional shares are scaled up to a factor of 100 or + rounded with a note; at most 64 tracks per axis), `ColumnSpacing` (the layout's gap) and `RowSpacing` (its cross gap), and each child in + its cell with `.Grid(row:, column:, rowSpan:, columnSpan:)` and its alignment in the cell. A frame without auto layout, a group or a + rectangle is a `Border` holding a `Canvas` whose children carry `.Canvas(left:, top:)`, with a stroke and children a `Grid` with the + border behind; one `// warning:` comment above the root counts such frames. Text is a `TextBlock` (`FontFamily`, `FontSize`, + `FontWeight`, `FontStyle`, `Foreground`, `LineHeight`, `CharacterSpacing` in thousandths of an em, `TextAlignment`, `TextWrapping`, + `TextTrimming`, `MaxLines`, `TextDecorations`; case is applied at run time; style runs are `Inlines` of `Run`s); an explicit line height + moves it down by the half-leading `(L - (ascent + descent) / upem * size) / 2` of the face FigCraft draws with (a top padding and a + negative bottom margin in a panel, the offset in a `Canvas`), so the code depends on the fonts installed where `inspect.code` runs; + with the family missing, or a line height below the font's natural height, it is a note. Vectors, booleans and shapes are a + `Microsoft.UI.Xaml.Shapes.Path` with `Data("F1 M …")` (`F1` non-zero, `F0` even-odd; at most 5,000 elements), one solid `Fill` and one + solid `Stroke`; gradients, several fills or strokes, effects and bigger outlines are an `Image` on `ms-appx:///Assets/.png` with a + comment to export it. Image fills are an `ImageBrush` on `.png` (names lowercase ASCII, unique in the snippet; the files are not + written). Shadows, blurs, blend modes, masks, gradients beyond the first stop, pattern fills, stroke alignment other than inside, + corner smoothing and arcs are `// not mapped: …` comments. Components and instances are written as the frames they are; + `inspect.componentCode` and code connect do not take `uno` yet. - **Code connect:** link a component (a variant links its set) to the code component it is built as, per language (`react`, `leptos`, `vue`, `swiftui`, `compose`, `arkui`, `flutter`): `codeConnect.set {id?, language?, importPath?, name?, template?}` (undoable; fields left out keep their value; the defaults are the generated From 7e28fb9efc65161146fdd109809f826c3b4c0f44 Mon Sep 17 00:00:00 2001 From: Andrej Skvorc Date: Sat, 14 Nov 2026 08:46:52 +0100 Subject: [PATCH 23/48] M6: Uno code: layer names as anchor comments Every layer's name is the last comment line directly above the statement that creates its outermost element, below any warning line, so a plugin that post-processes the code can pair elements with layers. Not-mapped notes stay in the chain below the constructor. Hidden layers and slices write nothing. --- crates/engine/src/dev/codegen/uno.rs | 4 ++ crates/engine/src/uno_codegen_tests.rs | 65 +++++++++++++++++++++++++- 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/dev/codegen/uno.rs b/crates/engine/src/dev/codegen/uno.rs index 7ee5b1aa9..1f083853f 100644 --- a/crates/engine/src/dev/codegen/uno.rs +++ b/crates/engine/src/dev/codegen/uno.rs @@ -424,6 +424,10 @@ impl Gen<'_> { _ => self.asset(n, at), }; e.var = var; + // The layer's name is the last comment line above the statement that creates its outermost + // element, below any `// warning:` line: the plugin that post-processes the code pairs + // elements with layers by it. `// not mapped:` lines sit in the chain, below the constructor. + e.lead.push(format!("// {}", comment_name(&n.name))); Some(e) } diff --git a/crates/engine/src/uno_codegen_tests.rs b/crates/engine/src/uno_codegen_tests.rs index daebf5125..f03fca4d9 100644 --- a/crates/engine/src/uno_codegen_tests.rs +++ b/crates/engine/src/uno_codegen_tests.rs @@ -80,6 +80,7 @@ internal sealed partial class EmptyView : UserControl { public EmptyView() { + // Empty var empty = new Border() .Width(100) .Height(50) @@ -100,6 +101,7 @@ fn a_frame_with_a_stroke_and_children_keeps_the_children_out_of_the_border() { set(&mut s, f, json!({"fill": "#112233", "stroke": "#FF0000", "strokeWeight": 3, "opacity": 0.5, "cornerRadius": 8})); ex(&mut s, "shape.rectangle", json!({"x": 5, "y": 5, "width": 20, "height": 20, "parent": f, "props": {"name": "Box"}})); let expected = "// warning: 1 frame has no auto layout: its children are positioned absolutely and do not adapt to size. +// Login Screen var loginScreen = new Grid() .Width(200) .Height(100) @@ -111,6 +113,7 @@ var loginScreenBorder = new Border() .CornerRadius(8); loginScreen.Children.Add(loginScreenBorder); var loginScreenCanvas = new Canvas(); +// Box var box = new Border() .Canvas(left: 5, top: 5) .Width(20) @@ -364,7 +367,8 @@ fn a_row_is_an_auto_layout_with_its_box_gap_padding_and_alignment() { rect(&mut s, f, 20.0, 20.0, "B"); let code = uno(&mut s, f); assert!(code.starts_with("using Windows.UI;\nusing Uno.Toolkit.UI;\n") || code.contains("using Uno.Toolkit.UI;"), "{code}"); - let expected = "var row = new AutoLayout() + let expected = "// Row +var row = new AutoLayout() .Width(200) .Height(100) .Background(Color.FromArgb(0xFF, 0x11, 0x22, 0x33)) @@ -374,11 +378,13 @@ fn a_row_is_an_auto_layout_with_its_box_gap_padding_and_alignment() { .Padding(15, 7, 15, 7) .PrimaryAxisAlignment(AutoLayoutAlignment.Center) .CounterAxisAlignment(AutoLayoutAlignment.Center); +// A var a = new Border() .Width(20) .Height(20) .Background(Color.FromArgb(0xFF, 0xFF, 0x00, 0x00)); row.Children.Add(a); +// B var b = new Border() .Width(20) .Height(20) @@ -981,3 +987,60 @@ fn vectors_that_a_path_cannot_draw_are_png_assets_with_unique_lowercase_names() assert_eq!(code.matches("new Microsoft.UI.Xaml.Shapes.Path()").count(), 1, "{code}"); assert!(!code.contains("star_icon_4") && !code.contains(".svg"), "{code}"); } + +#[test] +fn the_last_comment_line_above_a_layer_is_its_name_and_notes_and_warnings_cannot_be_taken_for_it() { + // The plugin that post-processes the code pairs elements with layers by this rule. + let mut s = Session::new(); + let root = frame(&mut s, "Root", 200.0, 200.0); + let warn = rect(&mut s, root, 10.0, 10.0, "warning: x"); + set(&mut s, warn, json!({"effects": [{"type": "dropShadow", "color": "#00000040", "offset": [0, 4], "radius": 8}]})); + rect(&mut s, root, 10.0, 10.0, "line one\nline two\u{2028}three"); + rect(&mut s, root, 10.0, 10.0, &"long ".repeat(40)); + let hidden = rect(&mut s, root, 10.0, 10.0, "Hidden Layer"); + set(&mut s, hidden, json!({"visible": false})); + let code = uno(&mut s, root); + let tree_text = tree(&code); + let lines: Vec<&str> = tree_text.lines().map(str::trim).collect(); + // For every statement that creates a layer's element (not the helpers a layer needs), the line + // above it is `// `; `// warning:` lines come before that line. + let decl = |l: &str| l.starts_with("var "); + let anchors: Vec<(&str, &str)> = lines + .iter() + .enumerate() + .filter(|(_, l)| decl(l)) + .map(|(i, l)| (*l, i.checked_sub(1).and_then(|j| lines.get(j)).copied().unwrap_or(""))) + .collect(); + let name_of = |var: &str| anchors.iter().find(|(l, _)| l.starts_with(&format!("var {var} = "))).map(|(_, a)| *a); + assert_eq!(name_of("root"), Some("// Root"), "{code}"); + assert_eq!(name_of("warningX"), Some("// warning: x"), "{code}"); + assert_eq!(name_of("lineOneLineTwoThree"), Some("// line one line two three"), "{code}"); + assert!(anchors.iter().any(|(_, a)| a.starts_with("// long long ") && a.ends_with('…') && a.chars().count() <= 84), "{code}"); + // The root's warning is above its name, never between the name and the statement. + let at = lines.iter().position(|l| l.starts_with("var root = ")).unwrap_or(0); + assert!(lines.get(at.wrapping_sub(2)).is_some_and(|l| l.starts_with("// warning: 1 frame has no auto layout")), "{code}"); + // A note is below the constructor, in the chain, and the layer's name still comes first. + let shadow = chain(&code, "warningX"); + assert!(shadow.iter().any(|l| l.starts_with("// not mapped: drop shadow")), "{code}"); + assert!(!anchors.iter().any(|(_, a)| a.starts_with("// not mapped:")), "{code}"); + // Hidden layers write nothing. + assert!(!code.contains("Hidden Layer") && !code.contains("hiddenLayer"), "{code}"); +} + +#[test] +fn a_slice_writes_nothing_and_a_cut_subtree_keeps_its_name() { + let mut s = Session::new(); + let f = frame(&mut s, "Cut", 100.0, 100.0); + ex(&mut s, "node.create", json!({"type": "slice", "parent": f, "name": "Export Area", "x": 0, "y": 0, "width": 10, "height": 10})); + let mut parent = f; + for i in 0..20 { + parent = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50, "parent": parent, "name": format!("Level {i}")}))); + } + let code = uno(&mut s, f); + assert!(!code.contains("Export Area") && !code.contains("exportArea"), "{code}"); + // The placeholder where the depth cap cuts keeps its layer's name above its statement. + let tree_text = tree(&code); + let lines: Vec<&str> = tree_text.lines().map(str::trim).collect(); + let cut = lines.iter().position(|l| l.ends_with(" …")).unwrap_or(0); + assert!(lines.get(cut + 1).is_some_and(|l| l.starts_with("var ") && l.ends_with("new Border();")), "{code}"); +} From 395392f3abe1ce360845b11359383dbb6cebdb7b Mon Sep 17 00:00:00 2001 From: Andrej Skvorc Date: Sat, 14 Nov 2026 09:25:59 +0100 Subject: [PATCH 24/48] M6: Uno text: tight line heights with BlockLineHeight A line height below the font's natural height keeps LineHeight as written and adds LineStackingStrategy.BlockLineHeight, which Uno draws as FigCraft does (the lines overlap). No padding or margin shift; a looser line height keeps the half-leading shift. Docs updated. --- ROADMAP.md | 2 +- crates/engine/src/dev/codegen/uno.rs | 11 ++++++----- crates/engine/src/uno_codegen_tests.rs | 16 ++++++++++++---- docs/mcp.md | 2 +- 4 files changed, 20 insertions(+), 11 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c57998246..7bba078d5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -365,7 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| -| 2026-11-14 | minor | M6: Uno C# Markup code, auto layout and vectors (ours): a frame with horizontal or vertical auto layout is a Toolkit `AutoLayout` that takes the box itself (`Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`) with `Orientation`, `Spacing`, `Padding` (less the stroke weight unless strokes are included; where that goes negative the border sits behind the layout in a `Grid`), `PrimaryAxisAlignment`, `CounterAxisAlignment` and `Justify`; children are sized per axis (fixed writes the length, hug none, fill stretches with the attached `AutoLayout` call, min and max lengths on the child), text hugs, fills or is fixed, a child that ignores the layout is independent at its offset (a hugging parent with one is written at its size), and `reverse_z` paints with descending `Canvas.ZIndex`; grid mode is a `Grid` with `ColumnDefinitions` / `RowDefinitions` (pixels, `Auto`, whole-number stars), `ColumnSpacing` / `RowSpacing`, children in the cell the layout crate gives them (`.Grid(row:, column:, rowSpan:, columnSpan:)`) aligned in it; wrap is one line with a note; frames without auto layout keep the `Canvas` with one warning per view that counts them; an explicit line height moves the text down by the half-leading of the face FigCraft draws with (a top padding with a negative bottom margin in a panel, the offset in a `Canvas`; the number depends on the fonts installed where `inspect.code` runs; a line height below the font's natural height is a note); vectors, booleans and shapes are a `Microsoft.UI.Xaml.Shapes.Path` with path data (`F1` non-zero, `F0` even-odd; at most 5,000 elements), one solid fill and one solid stroke, falling back to a PNG `Image` for gradients, several paints, effects and over the cap; containers are locals and children go in with `Children.Add(x)` / `Child = x`, since fluent `.Children(…)` doubles the load time with every level of nesting. Numbers unchanged (the incumbent has no such target). | +| 2026-11-14 | minor | M6: Uno C# Markup code, auto layout and vectors (ours): a frame with horizontal or vertical auto layout is a Toolkit `AutoLayout` that takes the box itself (`Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`) with `Orientation`, `Spacing`, `Padding` (less the stroke weight unless strokes are included; where that goes negative the border sits behind the layout in a `Grid`), `PrimaryAxisAlignment`, `CounterAxisAlignment` and `Justify`; children are sized per axis (fixed writes the length, hug none, fill stretches with the attached `AutoLayout` call, min and max lengths on the child), text hugs, fills or is fixed, a child that ignores the layout is independent at its offset (a hugging parent with one is written at its size), and `reverse_z` paints with descending `Canvas.ZIndex`; grid mode is a `Grid` with `ColumnDefinitions` / `RowDefinitions` (pixels, `Auto`, whole-number stars), `ColumnSpacing` / `RowSpacing`, children in the cell the layout crate gives them (`.Grid(row:, column:, rowSpan:, columnSpan:)`) aligned in it; wrap is one line with a note; frames without auto layout keep the `Canvas` with one warning per view that counts them; an explicit line height moves the text down by the half-leading of the face FigCraft draws with (a top padding with a negative bottom margin in a panel, the offset in a `Canvas`; the number depends on the fonts installed where `inspect.code` runs; a line height below the font's natural height keeps `LineHeight` and adds `LineStackingStrategy.BlockLineHeight`); vectors, booleans and shapes are a `Microsoft.UI.Xaml.Shapes.Path` with path data (`F1` non-zero, `F0` even-odd; at most 5,000 elements), one solid fill and one solid stroke, falling back to a PNG `Image` for gradients, several paints, effects and over the cap; containers are locals and children go in with `Children.Add(x)` / `Child = x`, since fluent `.Children(…)` doubles the load time with every level of nesting. Numbers unchanged (the incumbent has no such target). | | 2026-11-10 | minor | M6: Uno Platform C# Markup code (ours; the incumbent generates CSS, iOS and Android only): `inspect.code {language: uno}` (aliases `csharp-markup`, `cs-markup`) writes a `UserControl` class whose content is a fluent C# Markup tree for a layer: a frame, group or rectangle is a `Border` (fill as `Color.FromArgb`, border brush and thickness, per-side thickness, per-corner radius, opacity, rotation) holding a `Canvas` with the children at their offsets (a stroke and children put the border behind the canvas in a `Grid`, so the stroke does not push the children in), an ellipse is an `Ellipse`, text is a `TextBlock` (family, size, weight, italic, colour, line height, character spacing, alignment, wrapping, trimming and max lines from the auto resize mode, decoration, case applied when the code runs, mixed styles as `Run`s) and vectors and other shapes are an `Image` on an SVG asset (`ms-appx:///Assets/.svg`, a lowercase ASCII name unique in the snippet) with a comment to export it; image fills are an `ImageBrush` on a PNG asset. Fixed sizes everywhere; auto layout, variables, components and the project export are later steps. Shadows, blurs, blend modes, gradients beyond the first stop, masks and corner smoothing stay as `// not mapped: …` comments in the chain. Not offered for code connect or component code yet. Headline numbers unchanged. | | 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged | | 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/crates/engine/src/dev/codegen/uno.rs b/crates/engine/src/dev/codegen/uno.rs index 1f083853f..4d482c8a8 100644 --- a/crates/engine/src/dev/codegen/uno.rs +++ b/crates/engine/src/dev/codegen/uno.rs @@ -966,7 +966,7 @@ enum Leading { None, /// The text moves down by the half-leading (pixels). Shift(f64), - /// The line height is below the font's natural height. + /// The line height is below the font's natural height: block line stacking draws it as written. Tight, /// The font family is not installed where the code is written, so its metrics are unknown. NoFont, @@ -997,21 +997,22 @@ fn leading(s: &TextStyle) -> Leading { if !h.is_finite() || h.abs() < 0.5 { Leading::None } else if h < 0.0 { - // Uno never draws a line closer than the font's natural height (`BlockLineHeight` was tried - // for this and is left to a harness check), so the case is noted, not mapped. + // Uno's default stacking never draws a line closer than the font's natural height; + // `BlockLineHeight` does (measured), so the lines keep `LineHeight` as written. Leading::Tight } else { Leading::Shift(h) } } -/// The calls (or note) a [`Leading`] needs. `flow`: the text sits in a panel, where the shift is a +/// The calls (or note) a [`Leading`] needs. A tight line height needs no shift, only the stacking +/// strategy (the `LineHeight` call itself comes with the text style). `flow`: the text sits in a panel, where the shift is a /// top padding with a negative bottom margin that gives the room back (the box keeps its height /// and the last line is not cut); an existing margin (an independent child's offsets) is merged. fn leading_calls(e: &mut Element, leading: Leading, flow: bool) { match leading { Leading::None => {} - Leading::Tight => e.note("line height below the font's natural height is not reproduced in Uno"), + Leading::Tight => e.call(".LineStackingStrategy(LineStackingStrategy.BlockLineHeight)"), Leading::NoFont => e.note("line height shift (the font is not installed here, so its metrics are unknown)"), Leading::Shift(h) if flow => { e.call(format!(".Padding(0, {}, 0, 0)", num(h))); diff --git a/crates/engine/src/uno_codegen_tests.rs b/crates/engine/src/uno_codegen_tests.rs index f03fca4d9..9ba113abb 100644 --- a/crates/engine/src/uno_codegen_tests.rs +++ b/crates/engine/src/uno_codegen_tests.rs @@ -839,16 +839,24 @@ fn half_leading_merges_with_the_margin_of_an_independent_child() { } #[test] -fn a_line_height_below_the_font_is_noted_and_an_automatic_one_needs_nothing() { +fn a_line_height_below_the_font_uses_block_line_stacking_and_an_automatic_one_needs_nothing() { let mut s = Session::new(); let col = row(&mut s, json!({"layout": "vertical"})); let Some((t, _)) = spaced_text(&mut s, col, 1.0) else { return }; let c = chain(&uno(&mut s, col), "para"); - assert!(c.contains(&"// not mapped: line height below the font's natural height is not reproduced in Uno".to_string()), "{c:?}"); - assert!(!c.iter().any(|l| l.starts_with(".Padding(") || l.starts_with(".Margin(")), "{c:?}"); + assert!(c.contains(&".LineHeight(1)".to_string()), "{c:?}"); + assert!(c.contains(&".LineStackingStrategy(LineStackingStrategy.BlockLineHeight)".to_string()), "{c:?}"); + assert!(!c.iter().any(|l| l.starts_with(".Padding(") || l.starts_with(".Margin(") || l.starts_with("//")), "{c:?}"); set(&mut s, t, json!({"lineHeight": "auto"})); let c = chain(&uno(&mut s, col), "para"); - assert!(!c.iter().any(|l| l.starts_with(".Padding(") || l.starts_with(".Margin(") || l.starts_with("//")), "{c:?}"); + assert!( + !c.iter().any(|l| l.starts_with(".Padding(") || l.starts_with(".Margin(") || l.starts_with("//") || l.starts_with(".LineStacking")), + "{c:?}" + ); + // A looser line height than the font's keeps the half-leading shift and no block stacking. + set(&mut s, t, json!({"lineHeight": 60})); + let c = chain(&uno(&mut s, col), "para"); + assert!(c.iter().any(|l| l.starts_with(".Padding(0, ")) && !c.iter().any(|l| l.starts_with(".LineStacking")), "{c:?}"); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 18070e2d7..2589871af 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1785,7 +1785,7 @@ permissions: without it nothing is downloaded); `plugin.directory.publish {path `TextTrimming`, `MaxLines`, `TextDecorations`; case is applied at run time; style runs are `Inlines` of `Run`s); an explicit line height moves it down by the half-leading `(L - (ascent + descent) / upem * size) / 2` of the face FigCraft draws with (a top padding and a negative bottom margin in a panel, the offset in a `Canvas`), so the code depends on the fonts installed where `inspect.code` runs; - with the family missing, or a line height below the font's natural height, it is a note. Vectors, booleans and shapes are a + with the family missing it is a note; a line height below the font's natural height keeps `LineHeight` and adds `LineStackingStrategy.BlockLineHeight`, with no shift. Vectors, booleans and shapes are a `Microsoft.UI.Xaml.Shapes.Path` with `Data("F1 M …")` (`F1` non-zero, `F0` even-odd; at most 5,000 elements), one solid `Fill` and one solid `Stroke`; gradients, several fills or strokes, effects and bigger outlines are an `Image` on `ms-appx:///Assets/.png` with a comment to export it. Image fills are an `ImageBrush` on `.png` (names lowercase ASCII, unique in the snippet; the files are not From 3843338642db55e9af942d69d9dab34ff0c336ea Mon Sep 17 00:00:00 2001 From: Andrej Skvorc Date: Sat, 14 Nov 2026 09:36:01 +0100 Subject: [PATCH 25/48] M6: Uno docs: Developer Mode parity rows for the layer code The status line, the code row and two revision rows for Uno C# Markup layer code (auto layout, vectors as paths, Children.Add style), written on top of the current rows. --- docs/dev-mode-parity.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/dev-mode-parity.md b/docs/dev-mode-parity.md index d77dce75f..50177e7c3 100644 --- a/docs/dev-mode-parity.md +++ b/docs/dev-mode-parity.md @@ -1,6 +1,6 @@ # Dev Mode parity -> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-12 · **Change:** patch (SwiftUI, Compose and Flutter code write every visible colour and gradient fill of a frame, group, rectangle or ellipse in paint order, gradients as gradients, instead of one colour per layer (chained `.background` in SwiftUI, chained `Modifier.background` in Compose, a `DecoratedBox` for each fill under the top one in Flutter); CSS code export writes several fills as one layered `background`, top first, as the incumbent does (#2271): a solid above another fill becomes a one-colour gradient, the bottom solid stays a plain colour, Tailwind gets one `[background:...]` class; 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 Inspect tab then opens (never toggles away) with the caret in that layer's new-note field, and the engine never writes the note itself (#1840); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; class names transliterate non-ASCII layer names (#1235); measurements kept on the canvas; a read-only layers panel in Dev Mode; earlier: import lines in generated layer trees; compare with any saved version; Dev Mode behaviour suite: an inspect-only canvas, Changed in the ready list, statuses only on frames and sections; plugin panels from the Inspect tab) · **Target:** Figma Design Dev Mode (desktop app 126.10.7) +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-14 · **Change:** minor (Uno C# Markup code generation for layers, with auto layout and vectors as paths; earlier: SwiftUI, Compose and Flutter code write every visible colour and gradient fill of a frame, group, rectangle or ellipse in paint order, gradients as gradients, instead of one colour per layer (chained `.background` in SwiftUI, chained `Modifier.background` in Compose, a `DecoratedBox` for each fill under the top one in Flutter); CSS code export writes several fills as one layered `background`, top first, as the incumbent does (#2271): a solid above another fill becomes a one-colour gradient, the bottom solid stays a plain colour, Tailwind gets one `[background:...]` class; 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 Inspect tab then opens (never toggles away) with the caret in that layer's new-note field, and the engine never writes the note itself (#1840); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; class names transliterate non-ASCII layer names (#1235); measurements kept on the canvas; a read-only layers panel in Dev Mode; earlier: import lines in generated layer trees; compare with any saved version; Dev Mode behaviour suite: an inspect-only canvas, Changed in the ready list, statuses only on frames and sections; plugin panels from the Inspect tab) · **Target:** Figma Design Dev Mode (desktop app 126.10.7) **Breadth ~98%, ready ~78% (estimated).** The inspect surface is broad, components connect to the code components of a repository (with their imports, also inside generated layer trees), @@ -14,8 +14,8 @@ repository, third-party integrations. Remaining: 1–2 h. | 2026-11-07 | patch | Naming: the handoff mode is called Developer Mode in the interface, its shortcut row, its toasts, the control channel's refusal, the board refusal, the measurement parameter doc, the `.fig` export note, the CLI help and every catalog (24 languages, translations awaiting native review), since Figma holds a US registration for Dev Mode (7574348); command ids (`view.devMode`, `devMode.*`), preference keys and saved-document fields are unchanged, and the Actions palette still finds the command by the old name | | Dev Mode toggle (Shift+D), Inspect panel | done | the canvas only inspects: presses select, pan and comment but never move, resize, draw or edit text and vectors; menus and shortcuts refuse design edits with a note (Dev Mode's annotations, statuses, dev resources, measurements, code connections and comments still work); a drawing tool chosen in the toolbar goes back to the design. The layers panel only selects and expands (no renaming, reordering, hiding or locking; a double click says why), and the Pages list only opens pages (no adding, renaming, reordering, duplicating or deleting). Files dropped on the canvas aren't imported (a dropped document still opens as a file of its own), and the Assets panel places, swaps and applies nothing, doesn't change Hide when publishing, and doesn't accept library updates or add, remove or swap libraries; each says why | | Properties with their styles and variables; redlines on hover | done | positions from the frame around the layer (groups aren't frames), rotation, radius (CSS corner order), opacity, blend; colours in hex, RGB, CSS, HSL or HSB (`inspect.properties {colorFormat}`, the Inspect tab's Color format) | -| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue and Leptos (ours; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, several fills as one layered `background` (top first), gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235) | -| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue and Leptos (ours; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235); SwiftUI, Compose and Flutter write every colour and gradient fill of a layer in paint order, gradients as gradients (chained `.background` in SwiftUI, top fill first; chained `Modifier.background` in Compose, bottom fill first, a linear gradient snapped to eight directions and radial and angular ones at the box's centre; in Flutter a `DecoratedBox` for each fill under the top one); the native targets don't write image or pattern fills yet, and ArkUI and text still take one colour (#2271) | +| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue, Leptos and Uno C# Markup (ours; Uno writes layers only for now, as locals whose children are added with `Children.Add`: frames with auto layout (`AutoLayout`, `Grid`), text and vectors (`Path`), each layer's name as the last comment line above the statement that creates its element (a plugin pairs code with layers by it), the half-leading of explicit line heights depends on the fonts installed where the code is written; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, several fills as one layered `background` (top first), gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235) | +| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue, Leptos and Uno C# Markup (ours; Uno writes layers only for now, as locals whose children are added with `Children.Add`: frames with auto layout (`AutoLayout`, `Grid`), text and vectors (`Path`), each layer's name as the last comment line above the statement that creates its element (a plugin pairs code with layers by it), the half-leading of explicit line heights depends on the fonts installed where the code is written; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235); SwiftUI, Compose and Flutter write every colour and gradient fill of a layer in paint order, gradients as gradients (chained `.background` in SwiftUI, top fill first; chained `Modifier.background` in Compose, bottom fill first, a linear gradient snapped to eight directions and radial and angular ones at the box's centre; in Flutter a `DecoratedBox` for each fill under the top one); the native targets don't write image or pattern fills yet, and ArkUI and text still take one colour (#2271) | | Assets list with export | done | layers with export settings, icons (small, vector shapes only: SVG) and images (PNG); the icon rule is ours | | Annotations: pinned properties, categories, coloured callouts, filter | done | the Annotation tool (Shift+T, `tool.annotation`) picks a layer by a click or from the selection and opens its note field in the Inspect tab. Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet | | Ready for dev list, statuses, "Changed" after edits | done | the list filters Ready for dev, Changed, Completed or any, and badges changed ones (`inspect.readyForDev {status: changed}`, `changed` per item); only sections and frames at the top of a page or section take a status (others are refused) | @@ -31,6 +31,8 @@ repository, third-party integrations. Remaining: 1–2 h. | Date | Change | Summary | |---|---|---| +| 2026-11-14 | minor | M6: Uno C# Markup code, auto layout and vectors (ours): a frame with horizontal or vertical auto layout is a Toolkit `AutoLayout` that takes the box itself (`Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`) with `Orientation`, `Spacing`, `Padding` (less the stroke weight unless strokes are included; where that goes negative the border sits behind the layout in a `Grid`), `PrimaryAxisAlignment`, `CounterAxisAlignment` and `Justify`; children are sized per axis (fixed writes the length, hug none, fill stretches with the attached `AutoLayout` call, min and max lengths on the child), text hugs, fills or is fixed, a child that ignores the layout is independent at its offset (a hugging parent with one is written at its size), and `reverse_z` paints with descending `Canvas.ZIndex`; grid mode is a `Grid` with `ColumnDefinitions` / `RowDefinitions` (pixels, `Auto`, whole-number stars), `ColumnSpacing` / `RowSpacing`, children in the cell the layout crate gives them (`.Grid(row:, column:, rowSpan:, columnSpan:)`) aligned in it; wrap is one line with a note; frames without auto layout keep the `Canvas` with one warning per view that counts them; an explicit line height moves the text down by the half-leading of the face FigCraft draws with (a top padding with a negative bottom margin in a panel, the offset in a `Canvas`; the number depends on the fonts installed where `inspect.code` runs; a line height below the font's natural height keeps `LineHeight` and adds `LineStackingStrategy.BlockLineHeight`); vectors, booleans and shapes are a `Microsoft.UI.Xaml.Shapes.Path` with path data (`F1` non-zero, `F0` even-odd; at most 5,000 elements), one solid fill and one solid stroke, falling back to a PNG `Image` for gradients, several paints, effects and over the cap; containers are locals and children go in with `Children.Add(x)` / `Child = x`, since fluent `.Children(…)` doubles the load time with every level of nesting. Numbers unchanged (the incumbent has no such target). | +| 2026-11-10 | minor | M6: Uno Platform C# Markup code (ours; the incumbent generates CSS, iOS and Android only): `inspect.code {language: uno}` (aliases `csharp-markup`, `cs-markup`) writes a `UserControl` class whose content is a fluent C# Markup tree for a layer: a frame, group or rectangle is a `Border` (fill as `Color.FromArgb`, border brush and thickness, per-side thickness, per-corner radius, opacity, rotation) holding a `Canvas` with the children at their offsets (a stroke and children put the border behind the canvas in a `Grid`, so the stroke does not push the children in), an ellipse is an `Ellipse`, text is a `TextBlock` (family, size, weight, italic, colour, line height, character spacing, alignment, wrapping, trimming and max lines from the auto resize mode, decoration, case applied when the code runs, mixed styles as `Run`s) and vectors and other shapes are an `Image` on an SVG asset (`ms-appx:///Assets/.svg`, a lowercase ASCII name unique in the snippet) with a comment to export it; image fills are an `ImageBrush` on a PNG asset. Fixed sizes everywhere; auto layout, variables, components and the project export are later steps. Shadows, blurs, blend modes, gradients beyond the first stop, masks and corner smoothing stay as `// not mapped: …` comments in the chain. Not offered for code connect or component code yet. Numbers unchanged (the incumbent has no such target). | | 2026-11-12 | patch | CSS code export (#2271): a layer with several fills wrote one `background` per fill, so only the last survived. It now writes one `background` with every visible fill as a layer, top fill first, comma-separated: a solid above another fill is `linear-gradient(0deg, c, c)` (CSS allows a plain colour only as the last layer), the bottom solid stays a plain colour (with its variable), images and patterns keep their `url(...)` layers. Tailwind output carries the layered value as one `[background:...]` class. Text keeps one `color` per fill. Native targets unchanged. Percentages and hours unchanged | | 2026-11-09 | patch | The Annotation tool (Shift+T, `tool.annotation {id?}`): selects the layer pressed on (or the selection, or `id`) and asks the UI for its note, which the Inspect tab takes in its new-note field; the engine writes nothing itself, and Developer Mode lets the tool through its gates (#1840). Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet | | 2026-10-30 | minor | Gap 16: `figcraft-cli connect publish [--mappings figcraft.connect.json] [--dry-run]` publishes a code repository's mappings to a design file (as the incumbent's Code Connect CLI publishes a repository's mappings): it links each entry's component or set by name, warns about and skips links that don't fit, saves the file in place through the engine's save (or not, with `--dry-run`) and fails when nothing links. Dev Mode breadth (~98%) and ready (~78%) unchanged at this rounding; hours unchanged | From b141a4298389e94d8e69d03cd7fe9bca16f5bd64 Mon Sep 17 00:00:00 2001 From: Andrej Skvorc Date: Sat, 14 Nov 2026 13:41:25 +0100 Subject: [PATCH 26/48] M6: Uno vectors: a path longer than one literal is an image Path data longer than the 10,000 characters a C# literal is cut at would lose its last commands, so such an outline now falls back to the PNG asset like one with too many elements. Found in review. --- crates/engine/src/dev/codegen/uno.rs | 8 +++++-- crates/engine/src/uno_codegen_tests.rs | 33 ++++++++++++++++++++++++-- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/dev/codegen/uno.rs b/crates/engine/src/dev/codegen/uno.rs index 4d482c8a8..13e1e96bd 100644 --- a/crates/engine/src/dev/codegen/uno.rs +++ b/crates/engine/src/dev/codegen/uno.rs @@ -1035,8 +1035,9 @@ const MAX_PATH_ELEMENTS: usize = 5_000; /// An outline as the path mini-language of `Path.Data`: a fill rule (`F1` non-zero, `F0` even-odd) /// then `M x y`, `L x y`, `Q cx cy x y`, `C c1x c1y c2x c2y x y` and `Z`, numbers through [`num`]. -/// `None` for an empty outline, one with a coordinate that is not finite, or one past -/// [`MAX_PATH_ELEMENTS`]. +/// `None` for an empty outline, one with a coordinate that is not finite, one past +/// [`MAX_PATH_ELEMENTS`], or one whose text is longer than [`MAX_LITERAL`] (which [`cs_literal`] +/// would cut, leaving broken geometry): the layer is then exported as an image. pub(crate) fn path_data(path: &figcraft_geom::BezPath, rule: figcraft_render::FillRule) -> Option { use figcraft_geom::kurbo::PathEl; let els = path.elements(); @@ -1055,6 +1056,9 @@ pub(crate) fn path_data(path: &figcraft_geom::BezPath, rule: figcraft_render::Fi }; out.push(' '); out.push_str(&part); + if out.len() > MAX_LITERAL { + return None; + } } Some(out) } diff --git a/crates/engine/src/uno_codegen_tests.rs b/crates/engine/src/uno_codegen_tests.rs index 9ba113abb..2301b1348 100644 --- a/crates/engine/src/uno_codegen_tests.rs +++ b/crates/engine/src/uno_codegen_tests.rs @@ -911,12 +911,20 @@ fn path_data_refuses_empty_non_finite_and_huge_outlines() { huge.line_to((f64::from(i), 1.0)); } assert!(path_data(&huge, FillRule::Winding).is_none(), "5,001 elements are past the cap"); + // Under the element cap but longer than one C# literal (10,000 characters): refused too. + let mut long = BezPath::new(); + long.move_to((0.0, 0.0)); + for i in 0..2_000 { + long.line_to((f64::from(i), 1.0)); + } + assert!(path_data(&long, FillRule::Winding).is_none(), "about 16,000 characters"); let mut ok = BezPath::new(); ok.move_to((0.0, 0.0)); - for i in 0..4_999 { + for i in 0..999 { ok.line_to((f64::from(i), 1.0)); } - assert!(path_data(&ok, FillRule::Winding).is_some()); + let data = path_data(&ok, FillRule::Winding); + assert!(data.as_ref().is_some_and(|d| d.len() <= 10_000 && d.ends_with("L 998 1")), "{data:?}"); } #[test] @@ -996,6 +1004,27 @@ fn vectors_that_a_path_cannot_draw_are_png_assets_with_unique_lowercase_names() assert!(!code.contains("star_icon_4") && !code.contains(".svg"), "{code}"); } +#[test] +fn a_path_too_long_for_one_literal_is_an_image_not_cut_geometry() { + let mut s = Session::new(); + let f = frame(&mut s, "Long", 2000.0, 2000.0); + // 2,001 elements (under the element cap) but about 24,000 characters of path data. + let mut d = String::from("M0 0"); + for i in 0..2000 { + d.push_str(&format!(" L{}.25 {}.75", 1000 + i % 997, 1000 + (i * 7) % 991)); + } + d.push_str(" Z"); + let v = idv(&ex(&mut s, "node.create", json!({"type": "vector", "path": d, "closed": true, "parent": f, "name": "Long Line"}))); + set(&mut s, v, json!({"fills": ["#000000"]})); + let code = uno(&mut s, f); + assert!(!code.contains(".Data("), "{code}"); + assert!(code.contains(".Source(\"ms-appx:///Assets/long_line.png\")"), "{code}"); + // A short outline is still a path. + let short = idv(&ex(&mut s, "node.create", json!({"type": "vector", "path": "M0 0 L10 0 L10 10 Z", "closed": true, "parent": f}))); + set(&mut s, short, json!({"fills": ["#000000"]})); + assert_eq!(uno(&mut s, f).matches(".Data(").count(), 1); +} + #[test] fn the_last_comment_line_above_a_layer_is_its_name_and_notes_and_warnings_cannot_be_taken_for_it() { // The plugin that post-processes the code pairs elements with layers by this rule. From d0457d5f07e4c0d6272f5fe62636fe8609afbfce Mon Sep 17 00:00:00 2001 From: Andrej Skvorc Date: Mon, 16 Nov 2026 20:53:54 +0100 Subject: [PATCH 27/48] M6: Uno auto layout: the exported frame hugs where it hugs, and a clip only on a fixed frame An auto layout frame that is the exported layer kept the size it has in the design, so content that grows (a longer text, a larger gap) was cut off or left space. It now hugs on the axes where it hugs, as FigCraft lays it out. A clip is a fixed rectangle, so it is written only on a frame fixed on both axes; one that hugs or fills gets a note instead. --- ROADMAP.md | 2 +- crates/engine/src/dev/codegen/uno.rs | 30 +++++++++++++++++---- crates/engine/src/uno_codegen_tests.rs | 37 ++++++++++++++++++++++++-- docs/dev-mode-parity.md | 2 +- 4 files changed, 62 insertions(+), 9 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 7bba078d5..3a37e6864 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -365,7 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| -| 2026-11-14 | minor | M6: Uno C# Markup code, auto layout and vectors (ours): a frame with horizontal or vertical auto layout is a Toolkit `AutoLayout` that takes the box itself (`Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`) with `Orientation`, `Spacing`, `Padding` (less the stroke weight unless strokes are included; where that goes negative the border sits behind the layout in a `Grid`), `PrimaryAxisAlignment`, `CounterAxisAlignment` and `Justify`; children are sized per axis (fixed writes the length, hug none, fill stretches with the attached `AutoLayout` call, min and max lengths on the child), text hugs, fills or is fixed, a child that ignores the layout is independent at its offset (a hugging parent with one is written at its size), and `reverse_z` paints with descending `Canvas.ZIndex`; grid mode is a `Grid` with `ColumnDefinitions` / `RowDefinitions` (pixels, `Auto`, whole-number stars), `ColumnSpacing` / `RowSpacing`, children in the cell the layout crate gives them (`.Grid(row:, column:, rowSpan:, columnSpan:)`) aligned in it; wrap is one line with a note; frames without auto layout keep the `Canvas` with one warning per view that counts them; an explicit line height moves the text down by the half-leading of the face FigCraft draws with (a top padding with a negative bottom margin in a panel, the offset in a `Canvas`; the number depends on the fonts installed where `inspect.code` runs; a line height below the font's natural height keeps `LineHeight` and adds `LineStackingStrategy.BlockLineHeight`); vectors, booleans and shapes are a `Microsoft.UI.Xaml.Shapes.Path` with path data (`F1` non-zero, `F0` even-odd; at most 5,000 elements), one solid fill and one solid stroke, falling back to a PNG `Image` for gradients, several paints, effects and over the cap; containers are locals and children go in with `Children.Add(x)` / `Child = x`, since fluent `.Children(…)` doubles the load time with every level of nesting. Numbers unchanged (the incumbent has no such target). | +| 2026-11-14 | minor | M6: Uno C# Markup code, auto layout and vectors (ours): a frame with horizontal or vertical auto layout is a Toolkit `AutoLayout` that takes the box itself (`Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`) with `Orientation`, `Spacing`, `Padding` (less the stroke weight unless strokes are included; where that goes negative the border sits behind the layout in a `Grid`), `PrimaryAxisAlignment`, `CounterAxisAlignment` and `Justify`; children are sized per axis (fixed writes the length, hug none, fill stretches with the attached `AutoLayout` call, min and max lengths on the child), text hugs, fills or is fixed, a child that ignores the layout is independent at its offset (a hugging parent with one is written at its size), the exported frame itself hugs where it hugs in the design, a clip is written only on a frame fixed on both axes, and `reverse_z` paints with descending `Canvas.ZIndex`; grid mode is a `Grid` with `ColumnDefinitions` / `RowDefinitions` (pixels, `Auto`, whole-number stars), `ColumnSpacing` / `RowSpacing`, children in the cell the layout crate gives them (`.Grid(row:, column:, rowSpan:, columnSpan:)`) aligned in it; wrap is one line with a note; frames without auto layout keep the `Canvas` with one warning per view that counts them; an explicit line height moves the text down by the half-leading of the face FigCraft draws with (a top padding with a negative bottom margin in a panel, the offset in a `Canvas`; the number depends on the fonts installed where `inspect.code` runs; a line height below the font's natural height keeps `LineHeight` and adds `LineStackingStrategy.BlockLineHeight`); vectors, booleans and shapes are a `Microsoft.UI.Xaml.Shapes.Path` with path data (`F1` non-zero, `F0` even-odd; at most 5,000 elements), one solid fill and one solid stroke, falling back to a PNG `Image` for gradients, several paints, effects and over the cap; containers are locals and children go in with `Children.Add(x)` / `Child = x`, since fluent `.Children(…)` doubles the load time with every level of nesting. Numbers unchanged (the incumbent has no such target). | | 2026-11-10 | minor | M6: Uno Platform C# Markup code (ours; the incumbent generates CSS, iOS and Android only): `inspect.code {language: uno}` (aliases `csharp-markup`, `cs-markup`) writes a `UserControl` class whose content is a fluent C# Markup tree for a layer: a frame, group or rectangle is a `Border` (fill as `Color.FromArgb`, border brush and thickness, per-side thickness, per-corner radius, opacity, rotation) holding a `Canvas` with the children at their offsets (a stroke and children put the border behind the canvas in a `Grid`, so the stroke does not push the children in), an ellipse is an `Ellipse`, text is a `TextBlock` (family, size, weight, italic, colour, line height, character spacing, alignment, wrapping, trimming and max lines from the auto resize mode, decoration, case applied when the code runs, mixed styles as `Run`s) and vectors and other shapes are an `Image` on an SVG asset (`ms-appx:///Assets/.svg`, a lowercase ASCII name unique in the snippet) with a comment to export it; image fills are an `ImageBrush` on a PNG asset. Fixed sizes everywhere; auto layout, variables, components and the project export are later steps. Shadows, blurs, blend modes, gradients beyond the first stop, masks and corner smoothing stay as `// not mapped: …` comments in the chain. Not offered for code connect or component code yet. Headline numbers unchanged. | | 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged | | 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/crates/engine/src/dev/codegen/uno.rs b/crates/engine/src/dev/codegen/uno.rs index 13e1e96bd..7d90f8482 100644 --- a/crates/engine/src/dev/codegen/uno.rs +++ b/crates/engine/src/dev/codegen/uno.rs @@ -301,6 +301,9 @@ impl Element { #[derive(Clone, Copy, Debug, PartialEq)] enum Place { Flow, + /// The layer the code is generated for: placed like `Flow`, but an auto layout frame that hugs + /// its content keeps hugging (its size then follows the content, as FigCraft's layout does). + Root, At(f64, f64), Line { vertical: bool, @@ -344,7 +347,7 @@ pub(crate) fn uno(doc: &Document, id: NodeId) -> String { let Some(root) = doc.node(id) else { return String::new() }; let ctx = Ctx::new(doc, id); let mut g = Gen { ctx: &ctx, assets: BTreeSet::new(), free_frames: 0, names: BTreeSet::new() }; - let mut top = match g.layer(root, 0, Place::Flow) { + let mut top = match g.layer(root, 0, Place::Root) { Some(e) => e, None => { let mut e = Element::new("new Border()"); @@ -553,7 +556,7 @@ impl Gen<'_> { common(&mut outer, n); } if n.clip && n.corners.radii.iter().all(|r| *r <= 0.0) && !n.children.is_empty() { - outer.call(format!(".Clip(new RectangleGeometry().Rect(new Rect(0, 0, {}, {})))", num(n.width), num(n.height))); + clip(&mut outer, n, at); } outer } @@ -598,7 +601,7 @@ impl Gen<'_> { common(&mut outer, n); } if n.clip && has_kids && n.corners.radii.iter().all(|r| *r <= 0.0) { - outer.call(format!(".Clip(new RectangleGeometry().Rect(new Rect(0, 0, {}, {})))", num(n.width), num(n.height))); + clip(&mut outer, n, at); } outer } @@ -778,7 +781,7 @@ fn place(e: &mut Element, n: &Node, at: Place) { } }; match at { - Place::Flow => {} + Place::Flow | Place::Root => {} // The offsets read as the element's address. Place::At(x, y) => lead.push(format!(".Canvas(left: {}, top: {})", num(x), num(y))), Place::Line { vertical, z: order } => { @@ -863,10 +866,27 @@ fn cell_alignment(n: &Node, align: (CellAlign, CellAlign), lead: &mut Vec (Sizing, Sizing) { match at { Place::Line { .. } | Place::Cell { .. } => (n.child_layout.sizing_h, n.child_layout.sizing_v), + // With no parent to fill, only a hug of the root's own auto layout is kept. + Place::Root if n.layout.is_some() && n.kind.is_frame_like() => { + let own = |s: Sizing| if s == Sizing::Hug { Sizing::Hug } else { Sizing::Fixed }; + (own(n.child_layout.sizing_h), own(n.child_layout.sizing_v)) + } _ => (Sizing::Fixed, Sizing::Fixed), } } diff --git a/crates/engine/src/uno_codegen_tests.rs b/crates/engine/src/uno_codegen_tests.rs index 2301b1348..9f29e04f1 100644 --- a/crates/engine/src/uno_codegen_tests.rs +++ b/crates/engine/src/uno_codegen_tests.rs @@ -565,7 +565,7 @@ fn fill_stretches_on_the_axis_it_fills_and_fixed_keeps_its_size() { } #[test] -fn a_hugging_frame_has_no_size_of_its_own_and_the_root_keeps_its_size() { +fn a_hugging_frame_has_no_size_of_its_own_the_root_included() { let mut s = Session::new(); let outer = row(&mut s, json!({"layout": "vertical", "sizingH": "hug", "sizingV": "hug"})); let inner = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50, "parent": outer, "name": "Inner"}))); @@ -574,7 +574,8 @@ fn a_hugging_frame_has_no_size_of_its_own_and_the_root_keeps_its_size() { let code = uno(&mut s, outer); let has = |c: &[String], p: &str| c.iter().any(|l| l.starts_with(p)); let root = chain(&code, "row"); - assert!(has(&root, ".Width(") && has(&root, ".Height("), "the root keeps its size: {code}"); + // The root hugs too: its size follows its content, as FigCraft lays it out. + assert!(!has(&root, ".Width(") && !has(&root, ".Height("), "{code}"); let nested = chain(&code, "inner"); assert!(!has(&nested, ".Width(") && !has(&nested, ".Height("), "{code}"); } @@ -1081,3 +1082,35 @@ fn a_slice_writes_nothing_and_a_cut_subtree_keeps_its_name() { let cut = lines.iter().position(|l| l.ends_with(" …")).unwrap_or(0); assert!(lines.get(cut + 1).is_some_and(|l| l.starts_with("var ") && l.ends_with("new Border();")), "{code}"); } + +#[test] +fn a_root_that_hugs_its_content_keeps_hugging() { + let mut s = Session::new(); + let f = frame(&mut s, "Card", 240.0, 200.0); + set(&mut s, f, json!({"layout": "vertical", "padding": 16, "gap": 8, "sizingH": "fixed", "sizingV": "hug", "fills": []})); + idv(&ex(&mut s, "text.create", json!({"parent": f, "text": "Hello", "x": 0, "y": 0}))); + let code = uno(&mut s, f); + let root = tree(&code).split("// ").nth(1).unwrap_or_default().to_string(); + // The width is fixed; the height follows the content, so a longer text or a larger gap grows it. + assert!(root.contains(".Width(240)"), "{code}"); + assert!(!root.contains(".Height("), "{code}"); + // A root fixed on both axes keeps both sizes. + set(&mut s, f, json!({"sizingV": "fixed"})); + let fixed = uno(&mut s, f); + assert!(fixed.contains(".Width(240)") && fixed.contains(".Height("), "{fixed}"); +} + +#[test] +fn a_frame_that_hugs_or_fills_is_not_clipped_at_its_design_size() { + let mut s = Session::new(); + let f = frame(&mut s, "Card", 240.0, 120.0); + set(&mut s, f, json!({"layout": "vertical", "sizingV": "hug", "clip": true, "fills": []})); + idv(&ex(&mut s, "text.create", json!({"parent": f, "text": "Hello", "x": 0, "y": 0}))); + let code = uno(&mut s, f); + assert!(!code.contains(".Clip("), "{code}"); + assert!(code.contains("// not mapped: clip content on a frame that hugs or fills"), "{code}"); + // Fixed on both axes, the clip is the frame's box. + set(&mut s, f, json!({"sizingV": "fixed"})); + let fixed = uno(&mut s, f); + assert!(fixed.contains(".Clip(new RectangleGeometry().Rect(new Rect(0, 0, 240, "), "{fixed}"); +} diff --git a/docs/dev-mode-parity.md b/docs/dev-mode-parity.md index 50177e7c3..2b7ab6ff5 100644 --- a/docs/dev-mode-parity.md +++ b/docs/dev-mode-parity.md @@ -31,7 +31,7 @@ repository, third-party integrations. Remaining: 1–2 h. | Date | Change | Summary | |---|---|---| -| 2026-11-14 | minor | M6: Uno C# Markup code, auto layout and vectors (ours): a frame with horizontal or vertical auto layout is a Toolkit `AutoLayout` that takes the box itself (`Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`) with `Orientation`, `Spacing`, `Padding` (less the stroke weight unless strokes are included; where that goes negative the border sits behind the layout in a `Grid`), `PrimaryAxisAlignment`, `CounterAxisAlignment` and `Justify`; children are sized per axis (fixed writes the length, hug none, fill stretches with the attached `AutoLayout` call, min and max lengths on the child), text hugs, fills or is fixed, a child that ignores the layout is independent at its offset (a hugging parent with one is written at its size), and `reverse_z` paints with descending `Canvas.ZIndex`; grid mode is a `Grid` with `ColumnDefinitions` / `RowDefinitions` (pixels, `Auto`, whole-number stars), `ColumnSpacing` / `RowSpacing`, children in the cell the layout crate gives them (`.Grid(row:, column:, rowSpan:, columnSpan:)`) aligned in it; wrap is one line with a note; frames without auto layout keep the `Canvas` with one warning per view that counts them; an explicit line height moves the text down by the half-leading of the face FigCraft draws with (a top padding with a negative bottom margin in a panel, the offset in a `Canvas`; the number depends on the fonts installed where `inspect.code` runs; a line height below the font's natural height keeps `LineHeight` and adds `LineStackingStrategy.BlockLineHeight`); vectors, booleans and shapes are a `Microsoft.UI.Xaml.Shapes.Path` with path data (`F1` non-zero, `F0` even-odd; at most 5,000 elements), one solid fill and one solid stroke, falling back to a PNG `Image` for gradients, several paints, effects and over the cap; containers are locals and children go in with `Children.Add(x)` / `Child = x`, since fluent `.Children(…)` doubles the load time with every level of nesting. Numbers unchanged (the incumbent has no such target). | +| 2026-11-14 | minor | M6: Uno C# Markup code, auto layout and vectors (ours): a frame with horizontal or vertical auto layout is a Toolkit `AutoLayout` that takes the box itself (`Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`) with `Orientation`, `Spacing`, `Padding` (less the stroke weight unless strokes are included; where that goes negative the border sits behind the layout in a `Grid`), `PrimaryAxisAlignment`, `CounterAxisAlignment` and `Justify`; children are sized per axis (fixed writes the length, hug none, fill stretches with the attached `AutoLayout` call, min and max lengths on the child), text hugs, fills or is fixed, a child that ignores the layout is independent at its offset (a hugging parent with one is written at its size), the exported frame itself hugs where it hugs in the design, a clip is written only on a frame fixed on both axes, and `reverse_z` paints with descending `Canvas.ZIndex`; grid mode is a `Grid` with `ColumnDefinitions` / `RowDefinitions` (pixels, `Auto`, whole-number stars), `ColumnSpacing` / `RowSpacing`, children in the cell the layout crate gives them (`.Grid(row:, column:, rowSpan:, columnSpan:)`) aligned in it; wrap is one line with a note; frames without auto layout keep the `Canvas` with one warning per view that counts them; an explicit line height moves the text down by the half-leading of the face FigCraft draws with (a top padding with a negative bottom margin in a panel, the offset in a `Canvas`; the number depends on the fonts installed where `inspect.code` runs; a line height below the font's natural height keeps `LineHeight` and adds `LineStackingStrategy.BlockLineHeight`); vectors, booleans and shapes are a `Microsoft.UI.Xaml.Shapes.Path` with path data (`F1` non-zero, `F0` even-odd; at most 5,000 elements), one solid fill and one solid stroke, falling back to a PNG `Image` for gradients, several paints, effects and over the cap; containers are locals and children go in with `Children.Add(x)` / `Child = x`, since fluent `.Children(…)` doubles the load time with every level of nesting. Numbers unchanged (the incumbent has no such target). | | 2026-11-10 | minor | M6: Uno Platform C# Markup code (ours; the incumbent generates CSS, iOS and Android only): `inspect.code {language: uno}` (aliases `csharp-markup`, `cs-markup`) writes a `UserControl` class whose content is a fluent C# Markup tree for a layer: a frame, group or rectangle is a `Border` (fill as `Color.FromArgb`, border brush and thickness, per-side thickness, per-corner radius, opacity, rotation) holding a `Canvas` with the children at their offsets (a stroke and children put the border behind the canvas in a `Grid`, so the stroke does not push the children in), an ellipse is an `Ellipse`, text is a `TextBlock` (family, size, weight, italic, colour, line height, character spacing, alignment, wrapping, trimming and max lines from the auto resize mode, decoration, case applied when the code runs, mixed styles as `Run`s) and vectors and other shapes are an `Image` on an SVG asset (`ms-appx:///Assets/.svg`, a lowercase ASCII name unique in the snippet) with a comment to export it; image fills are an `ImageBrush` on a PNG asset. Fixed sizes everywhere; auto layout, variables, components and the project export are later steps. Shadows, blurs, blend modes, gradients beyond the first stop, masks and corner smoothing stay as `// not mapped: …` comments in the chain. Not offered for code connect or component code yet. Numbers unchanged (the incumbent has no such target). | | 2026-11-12 | patch | CSS code export (#2271): a layer with several fills wrote one `background` per fill, so only the last survived. It now writes one `background` with every visible fill as a layer, top fill first, comma-separated: a solid above another fill is `linear-gradient(0deg, c, c)` (CSS allows a plain colour only as the last layer), the bottom solid stays a plain colour (with its variable), images and patterns keep their `url(...)` layers. Tailwind output carries the layered value as one `[background:...]` class. Text keeps one `color` per fill. Native targets unchanged. Percentages and hours unchanged | | 2026-11-09 | patch | The Annotation tool (Shift+T, `tool.annotation {id?}`): selects the layer pressed on (or the selection, or `id`) and asks the UI for its note, which the Inspect tab takes in its new-note field; the engine writes nothing itself, and Developer Mode lets the tool through its gates (#1840). Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet | From 4f2ade852ebf2091a678126324242f12db31b9ea Mon Sep 17 00:00:00 2001 From: Anderson Date: Mon, 23 Nov 2026 02:31:03 +0100 Subject: [PATCH 28/48] MCP: allow confined sessions to join an approved server --- Cargo.lock | 1 + apps/figcraft-cli/Cargo.toml | 1 + apps/figcraft-cli/src/args.rs | 22 ++++++++++ apps/figcraft-cli/src/main.rs | 48 ++++++++++++++++++++- crates/collab-net/src/invite.rs | 13 ++++++ crates/collab-net/src/invite_tests.rs | 24 +++++++++++ crates/collab-net/src/link.rs | 9 ++++ crates/engine/src/automation/file_access.rs | 20 ++++++++- crates/engine/src/live_tests.rs | 44 +++++++++++++++++++ crates/engine/src/sharing/live.rs | 14 ++++-- crates/engine/src/sharing/live/host.rs | 5 ++- crates/engine/src/sharing/live/join.rs | 2 +- crates/engine/src/sharing/live/types.rs | 7 +++ crates/mcp/src/server.rs | 7 ++- docs/cli.md | 11 ++--- docs/mcp.md | 26 +++++++++++ 16 files changed, 239 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 75ce96f7a..5eb2c9a53 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2096,6 +2096,7 @@ dependencies = [ "clap", "clap_complete", "clap_mangen", + "figcraft-collab-net", "figcraft-doc", "figcraft-engine", "figcraft-format", diff --git a/apps/figcraft-cli/Cargo.toml b/apps/figcraft-cli/Cargo.toml index 16c228681..0b676a920 100644 --- a/apps/figcraft-cli/Cargo.toml +++ b/apps/figcraft-cli/Cargo.toml @@ -15,6 +15,7 @@ workspace = true [dependencies] figcraft-engine = { workspace = true } +figcraft-collab-net = { workspace = true } figcraft-doc = { workspace = true } figcraft-render = { workspace = true } figcraft-text = { workspace = true } diff --git a/apps/figcraft-cli/src/args.rs b/apps/figcraft-cli/src/args.rs index b8372ece4..dad0fe40e 100644 --- a/apps/figcraft-cli/src/args.rs +++ b/apps/figcraft-cli/src/args.rs @@ -212,6 +212,9 @@ pub struct McpArgs { /// How long the attached app may take over each request, in seconds (1–600; default 60) #[arg(long, value_name = "SECONDS", requires = "attach", value_parser = clap::value_parser!(u64).range(1..=600))] pub timeout: Option, + /// Allow a confined headless MCP session to join collaboration links from this server (repeatable) + #[arg(long = "automation-allow-server", value_name = "URL", conflicts_with = "attach")] + pub automation_allow_servers: Vec, #[command(flatten)] pub roots: RootArgs, } @@ -532,6 +535,7 @@ mod tests { (&["mcp", "--attach", "7979", "--timeout", "601"], ValueValidation), (&["mcp", "--timeout", "300"], MissingRequiredArgument), (&["mcp", "--attach", "7979", "--automation-read-root", "."], ArgumentConflict), + (&["mcp", "--attach", "7979", "--automation-allow-server", "wss://figcraft.example.com/"], ArgumentConflict), (&["mcp", "--automation-write-root"], InvalidValue), (&["mcp", "stray"], UnknownArgument), (&["convert", "a"], MissingRequiredArgument), @@ -565,6 +569,7 @@ mod tests { assert_eq!(e.as_ref().map(clap::Error::kind), Some(ErrorKind::DisplayHelp), "{args:?}"); assert_eq!(e.map(|e| e.exit_code()), Some(0), "{args:?}"); } + // The help is the subcommand's, even after a mistake. let help = try_parse(&["plugin", "publish", "--bogus", "--help"]).err().map(|e| e.to_string()).unwrap_or_default(); assert!(help.contains("Usage: figcraft-cli plugin publish"), "{help}"); @@ -573,6 +578,23 @@ mod tests { assert_eq!(a.file, "-h"); } + #[test] + fn mcp_accepts_repeated_server_allowlists() { + let Command::Mcp(a) = ok(&[ + "mcp", + "--automation-read-root", + "in", + "--automation-write-root", + "out", + "--automation-allow-server", + "wss://figcraft.example.com/", + "--automation-allow-server=wss://team.example.com/design/", + ]) else { + panic!("mcp") + }; + assert_eq!(a.automation_allow_servers, ["wss://figcraft.example.com/", "wss://team.example.com/design/"]); + } + /// Every subcommand's help renders and documents each of its options. #[test] fn every_subcommand_has_help() { diff --git a/apps/figcraft-cli/src/main.rs b/apps/figcraft-cli/src/main.rs index 44bdd4520..43d783de4 100644 --- a/apps/figcraft-cli/src/main.rs +++ b/apps/figcraft-cli/src/main.rs @@ -92,7 +92,7 @@ fn run(cli: Cli) -> CliResult { Ok(ExitCode::SUCCESS) } // `--attach` conflicts with the roots: the app runs the commands, only its own roots can confine them. - Command::Mcp(a) => mcp(a.attach.as_deref(), a.timeout, roots_of(&a.roots)?), + Command::Mcp(a) => mcp(a.attach.as_deref(), a.timeout, mcp_roots(&a.roots, &a.automation_allow_servers)?), Command::Plugin { command: PluginCommand::Publish(a) } => publish_plugin(&a.folder, &a.server), Command::Connect { command: ConnectCommand::Publish(a) } => confined(&a.roots, || files::connect_publish(&a.file, &a.mappings, a.dry_run)), Command::Perf(a) => { @@ -171,3 +171,49 @@ fn mcp(attach: Option<&str>, timeout: Option, roots: Option CliResult> { + let Some(roots) = roots_of(roots)? else { + return if allowed_servers.is_empty() { + Ok(None) + } else { + Err(CliError::Usage("--automation-allow-server requires automation read or write roots".into())) + }; + }; + let mut servers = Vec::with_capacity(allowed_servers.len()); + for server in allowed_servers { + if server.contains('?') { + return Err(CliError::Usage("--automation-allow-server must not contain a query or key".into())); + } + let (endpoint, query) = figcraft_collab_net::Endpoint::parse(server) + .map_err(|_| CliError::Usage("--automation-allow-server must be a ws:// or wss:// server URL".into()))?; + if !query.is_empty() { + return Err(CliError::Usage("--automation-allow-server must not contain a query or key".into())); + } + servers.push(endpoint.url()); + } + Ok(Some(roots.with_allowed_servers(servers))) +} + +#[cfg(test)] +mod tests { + use super::{CliError, mcp_roots}; + use crate::args::RootArgs; + + #[test] + fn an_allowed_server_needs_file_roots_and_cannot_carry_a_key() { + let server = "wss://figcraft.example.com/".to_string(); + let no_roots = RootArgs { automation_read_root: Vec::new(), automation_write_root: Vec::new() }; + assert!(matches!(mcp_roots(&no_roots, std::slice::from_ref(&server)), Err(CliError::Usage(_)))); + + let path = std::env::temp_dir().join(format!("figcraft-cli-roots-{}", std::process::id())); + std::fs::create_dir_all(&path).unwrap(); + let roots = RootArgs { automation_read_root: Vec::new(), automation_write_root: vec![path.to_string_lossy().into_owned()] }; + let allowed = mcp_roots(&roots, &[server]).unwrap().unwrap(); + assert_eq!(allowed.allowed_servers(), ["wss://figcraft.example.com:443/"]); + + let with_key = "wss://figcraft.example.com/?key=secret".to_string(); + assert!(matches!(mcp_roots(&roots, &[with_key]), Err(CliError::Usage(message)) if !message.contains("secret"))); + let _ = std::fs::remove_dir_all(path); + } +} diff --git a/crates/collab-net/src/invite.rs b/crates/collab-net/src/invite.rs index ace18d299..4f41051ef 100644 --- a/crates/collab-net/src/invite.rs +++ b/crates/collab-net/src/invite.rs @@ -84,6 +84,15 @@ impl Endpoint { } } + /// Whether this endpoint is within an explicitly allowed server origin and path prefix. + pub fn is_within(&self, allowed: &Endpoint) -> bool { + self.secure == allowed.secure + && self.host.eq_ignore_ascii_case(&allowed.host) + && safe_path(&self.path) + && safe_path(&allowed.path) + && (allowed.path == "/" || self.path.starts_with(&allowed.path)) + } + /// Read `ws(s)://host[:port][/path][?query]` (a missing port is the scheme's: 80 or 443): the /// endpoint and the query's decoded pairs. Errors say what's wrong without echoing `url`. pub fn parse(url: &str) -> Result<(Endpoint, Vec<(String, String)>), String> { @@ -261,6 +270,10 @@ fn valid_path(p: &str) -> bool { p.starts_with('/') && p.len() <= 256 && p.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'-' | b'_' | b'.' | b'~')) } +fn safe_path(p: &str) -> bool { + !p.split('/').any(|part| matches!(part, "." | "..")) +} + /// `%XX` escapes decoded (UTF-8); `None` for broken escapes. fn percent_decode(s: &str) -> Option { let bytes = s.as_bytes(); diff --git a/crates/collab-net/src/invite_tests.rs b/crates/collab-net/src/invite_tests.rs index b7618dc28..1bb2730dc 100644 --- a/crates/collab-net/src/invite_tests.rs +++ b/crates/collab-net/src/invite_tests.rs @@ -3,6 +3,8 @@ use proptest::prelude::*; +use figcraft_engine::live::LiveLink; + use crate::invite::{Endpoint, Invite}; const TOKEN: &str = "AbCdEfGhIjKlMnOpQrStUv"; @@ -58,6 +60,28 @@ fn server_links_carry_tls_and_a_path() { assert!(plain.link().starts_with("figcraft://join?host=10.0.0.5:47900&")); } +#[test] +fn an_automation_server_allowlist_matches_the_parsed_origin_and_path_prefix() { + let net = crate::NetLink::new(std::sync::Arc::new(|| {})); + let allowed = vec!["wss://figcraft.example.com/team/".to_string()]; + let invite = |server: &str| Invite { server: Endpoint::parse(server).unwrap().0, ..invite() }.link(); + + assert!(net.automation_join_allowed(&invite("wss://FIGCRAFT.example.com/team/live/"), &allowed)); + assert!(net.automation_join_allowed(&invite("wss://figcraft.example.com/team/"), &allowed)); + assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com/teams/"), &allowed)); + assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com/team/../outside/"), &allowed)); + assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com/team/live/"), &["wss://figcraft.example.com/team/../".to_string()])); + assert!(!net.automation_join_allowed(&invite("ws://figcraft.example.com/team/"), &allowed)); + assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com:444/team/"), &allowed)); + assert!(!net.automation_join_allowed(&invite("wss://other.example.com/team/"), &allowed)); + assert!(!net.automation_join_allowed( + "figcraft://join?server=wss://other.example.com/team/&file=0123456789abcdef&token=AbCdEfGhIjKlMnOpQrStUv", + &allowed + )); + assert!(!net.automation_join_allowed("figcraft://join?host=192.168.1.20:47900&file=0123456789abcdef&token=AbCdEfGhIjKlMnOpQrStUv", &allowed)); + assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com/team/"), &["wss://figcraft.example.com/team/?key=secret".to_string()])); +} + #[test] fn server_addresses_with_a_key() { let (e, q) = Endpoint::parse("ws://127.0.0.1:47900/?key=KeyKeyKeyKeyKeyKeyKey0").unwrap(); diff --git a/crates/collab-net/src/link.rs b/crates/collab-net/src/link.rs index 198022a09..1145be6ff 100644 --- a/crates/collab-net/src/link.rs +++ b/crates/collab-net/src/link.rs @@ -151,6 +151,15 @@ pub(crate) fn reachable(addr: SocketAddr) -> SocketAddr { } impl LiveLink for NetLink { + fn automation_join_allowed(&self, link: &str, allowed_servers: &[String]) -> bool { + let Ok((invite, _)) = Invite::parse_join(link) else { + return false; + }; + allowed_servers + .iter() + .any(|allowed| Endpoint::parse(allowed).is_ok_and(|(endpoint, query)| query.is_empty() && invite.server.is_within(&endpoint))) + } + /// Host the open file on `o.bind`: a join code's short secret when `o.short`, and a second, /// view-only secret with its invite link when `o.view`. fn host(&mut self, session: SessionId, o: HostOptions) -> Result { diff --git a/crates/engine/src/automation/file_access.rs b/crates/engine/src/automation/file_access.rs index 5eba5a506..1d5bfebcd 100644 --- a/crates/engine/src/automation/file_access.rs +++ b/crates/engine/src/automation/file_access.rs @@ -40,6 +40,7 @@ pub enum Access { pub struct Roots { read: Vec, write: Vec, + allowed_servers: Vec, } impl Roots { @@ -55,7 +56,18 @@ impl Roots { }) .collect::, String>>() }; - Ok(Self { read: resolve("--automation-read-root", read)?, write: resolve("--automation-write-root", write)? }) + Ok(Self { read: resolve("--automation-read-root", read)?, write: resolve("--automation-write-root", write)?, allowed_servers: Vec::new() }) + } + + /// Also allow headless collaboration joins to explicitly approved servers. + pub fn with_allowed_servers(mut self, servers: Vec) -> Self { + self.allowed_servers = servers; + self + } + + /// Servers an automation session may join through its collaboration link. + pub fn allowed_servers(&self) -> &[String] { + &self.allowed_servers } /// The resolved path to use for `access` to `path`, or why it is refused. @@ -91,7 +103,11 @@ impl Roots { /// The folders as JSON, resolved: `{read: [every folder that may be read], write: [the write roots]}`. pub fn to_json(&self) -> serde_json::Value { let list = |v: &[PathBuf]| v.iter().map(|p| shown(p)).collect::>(); - serde_json::json!({"read": list(&[self.read.as_slice(), self.write.as_slice()].concat()), "write": list(&self.write)}) + serde_json::json!({ + "read": list(&[self.read.as_slice(), self.write.as_slice()].concat()), + "write": list(&self.write), + "allowedServers": self.allowed_servers + }) } } diff --git a/crates/engine/src/live_tests.rs b/crates/engine/src/live_tests.rs index 4d19617ce..268b17603 100644 --- a/crates/engine/src/live_tests.rs +++ b/crates/engine/src/live_tests.rs @@ -34,11 +34,17 @@ pub(crate) struct Script { pub(crate) msgs_to: Vec, /// The people removed: `(session, client)`. pub(crate) removed: Vec<(u64, u32)>, + /// The scripted link's answer to an automation server allowlist check. + pub(crate) automation_join_allowed: bool, } pub(crate) struct Mock(pub(crate) Arc>); impl LiveLink for Mock { + fn automation_join_allowed(&self, link: &str, allowed_servers: &[String]) -> bool { + self.0.lock().unwrap().automation_join_allowed && allowed_servers.iter().any(|server| link.contains(server)) + } + fn host(&mut self, session: u64, opts: HostOptions) -> Result { let mut s = self.0.lock().unwrap(); s.session = session; @@ -50,6 +56,7 @@ impl LiveLink for Mock { i.url = format!("ws://{}/?file=f&token=t", i.address); Ok(i) } + fn join_resuming(&mut self, session: u64, link: &str, name: &str, resume: Option) -> Result<(), String> { self.0.lock().unwrap().resumed = resume; self.join(session, link, name) @@ -103,6 +110,43 @@ impl LiveLink for Mock { } } +#[test] +fn confined_headless_session_may_join_only_an_explicitly_allowed_server() { + let dir = std::env::temp_dir().join(format!("figcraft-join-allow-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let roots = Arc::new( + crate::file_access::Roots::new(&[], &[dir.to_string_lossy().into_owned()]) + .unwrap() + .with_allowed_servers(vec!["wss://figcraft.example.com/".into()]), + ); + let script = Arc::new(Mutex::new(Script { automation_join_allowed: true, ..Script::default() })); + let mut s = Session::new(); + s.live.install(Box::new(Mock(script.clone()))); + + crate::file_access::confined(Some(&roots), || { + assert!( + s.execute( + "collab.join", + &json!({"link": "figcraft://join?server=wss://figcraft.example.com/&file=0123456789abcdef&token=AbCdEfGhIjKlMnOpQrStUv"}) + ) + .is_ok() + ); + assert!( + s.execute( + "collab.join", + &json!({"link": "figcraft://join?server=wss://elsewhere.example.com/&file=0123456789abcdef&token=AbCdEfGhIjKlMnOpQrStUv"}) + ) + .is_err() + ); + assert!(s.execute("collab.publish", &json!({"server": "wss://figcraft.example.com/"})).is_err()); + assert!(s.execute("collab.host", &json!({})).is_err()); + assert!(s.execute("plugin.directory.list", &json!({"server": "wss://figcraft.example.com/"})).is_err()); + }); + assert_eq!(script.lock().unwrap().joined.len(), 1); + assert!(script.lock().unwrap().published.is_empty()); + let _ = std::fs::remove_dir_all(&dir); +} + /// A session you are in as `role`, as client `me`, everyone in it editing. pub(crate) fn info(role: Role, me: u32) -> SessionInfo { SessionInfo { diff --git a/crates/engine/src/sharing/live.rs b/crates/engine/src/sharing/live.rs index 1d41d0912..3c7d07f73 100644 --- a/crates/engine/src/sharing/live.rs +++ b/crates/engine/src/sharing/live.rs @@ -335,10 +335,18 @@ impl Lives { /// Start a session on the link for command `cmd`: `start` gets the link and the new /// session's id, which comes back with what it returned. - fn start(&mut self, cmd: &str, start: impl FnOnce(&mut dyn LiveLink, SessionId) -> Result) -> Result<(SessionId, T)> { + fn start( + &mut self, + cmd: &str, + join_link: Option<&str>, + start: impl FnOnce(&mut dyn LiveLink, SessionId) -> Result, + ) -> Result<(SessionId, T)> { let link = self.link.as_deref_mut().ok_or_else(|| unavailable(cmd))?; - if let Some(why) = crate::file_access::network_refused() { - return Err(EngineError::Disabled(cmd.to_string(), why)); + if let Some(roots) = crate::file_access::current() { + let allowed = cmd == "collab.join" && join_link.is_some_and(|invite| link.automation_join_allowed(invite, roots.allowed_servers())); + if !allowed { + return Err(EngineError::Disabled(cmd.to_string(), crate::file_access::NETWORK_REFUSED.into())); + } } let id = self.last.saturating_add(1); let out = start(link, id)?; diff --git a/crates/engine/src/sharing/live/host.rs b/crates/engine/src/sharing/live/host.rs index 916da6949..1907c3014 100644 --- a/crates/engine/src/sharing/live/host.rs +++ b/crates/engine/src/sharing/live/host.rs @@ -58,7 +58,8 @@ fn start_host(s: &mut Session, cmd: &str, p: &Value, bind: Bind, short: bool, vi }; let (doc, uid) = s.ds().map(|ds| (ds.doc.clone(), ds.uid))?; let opts = HostOptions { port, bind, name: display_name(&s.prefs), doc, short, view }; - let (id, info) = s.live.start(cmd, |l, id| l.host(id, opts).map_err(|e| EngineError::Other(format!("couldn't start the live session: {e}"))))?; + let (id, info) = + s.live.start(cmd, None, |l, id| l.host(id, opts).map_err(|e| EngineError::Other(format!("couldn't start the live session: {e}"))))?; s.live.open(Live { id, status: Status::Live, info: Some(info), doc_uid: Some(uid), tab: Some(uid), ..Live::default() }); Ok(id) } @@ -78,7 +79,7 @@ fn start_publish(s: &mut Session, cmd: &str, server: &str, p: &Value, share: boo let name = string(p, "name").map(|n| n.trim().chars().filter(|c| !c.is_control()).take(256).collect::()).filter(|n| !n.is_empty()); let me = display_name(&s.prefs); let opts = PublishOptions { server: server.trim().to_string(), key, name: name.unwrap_or_else(|| doc.name.clone()), me, doc, share }; - let (id, ()) = s.live.start(cmd, |l, id| l.publish(id, opts).map_err(|e| bad(cmd, e)))?; + let (id, ()) = s.live.start(cmd, None, |l, id| l.publish(id, opts).map_err(|e| bad(cmd, e)))?; // This tab becomes the server file's synced document once it is there. s.live.open(Live { id, status: Status::Connecting, doc_uid: Some(uid), tab: Some(uid), server: server.trim().to_string(), ..Live::default() }); Ok(id) diff --git a/crates/engine/src/sharing/live/join.rs b/crates/engine/src/sharing/live/join.rs index badc1fd91..ea450122c 100644 --- a/crates/engine/src/sharing/live/join.rs +++ b/crates/engine/src/sharing/live/join.rs @@ -27,7 +27,7 @@ pub(crate) fn start_join( resume: Option, ) -> Result { let (name, tab) = (display_name(&s.prefs), s.tab()); - let (id, ()) = s.live.start(cmd, |l, id| l.join_resuming(id, link, &name, resume).map_err(|e| bad(cmd, e)))?; + let (id, ()) = s.live.start(cmd, Some(link), |l, id| l.join_resuming(id, link, &name, resume).map_err(|e| bad(cmd, e)))?; let server = share.as_ref().map(|s| s.server.clone()).unwrap_or_default(); // The session's file opens in a tab of its own; until then the join shows on this one. s.live.open(Live { id, status: Status::Connecting, tab, server, published, share, ..Live::default() }); diff --git a/crates/engine/src/sharing/live/types.rs b/crates/engine/src/sharing/live/types.rs index 07c2dd242..7c02364a8 100644 --- a/crates/engine/src/sharing/live/types.rs +++ b/crates/engine/src/sharing/live/types.rs @@ -446,6 +446,13 @@ pub trait LiveLink: Send { fn can_host(&self) -> bool { true } + /// Whether `link` names a collaboration server in the automation allowlist. + /// + /// Implementations must parse the invite and compare its endpoint; a string-prefix check + /// would let a crafted invite bypass the file/network boundary. + fn automation_join_allowed(&self, _link: &str, _allowed_servers: &[String]) -> bool { + false + } /// Start hosting session `session` for `opts.doc`. fn host(&mut self, session: SessionId, opts: HostOptions) -> std::result::Result; /// Start joining the session behind an invite link, as session `session`. Errors are for diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index 58eb6b2e2..07fef4703 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -237,7 +237,12 @@ impl Server { fn roots_note(&self) -> String { let Some(r) = &self.roots else { return String::new() }; let j = r.to_json(); - format!(" Files: only these folders may be read: {}; written: {} (any other path is refused).", j["read"], j["write"]) + let files = format!(" Files: only these folders may be read: {}; written: {} (any other path is refused).", j["read"], j["write"]); + if r.allowed_servers().is_empty() { + files + } else { + format!("{files} Collaboration: may join only links on {}; other network requests are refused.", j["allowedServers"]) + } } fn notification(&mut self, method: &str) { diff --git a/docs/cli.md b/docs/cli.md index 07b19e58b..7410cd5d9 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -274,7 +274,7 @@ the flags leave the output identical when nothing strays outside the roots. Every command with its label, shortcut, undoable flag (`*`) and parameter docs; `--json` for machines. -### `mcp [--attach PORT] [--automation-read-root DIR]… [--automation-write-root DIR]…` +### `mcp [--attach PORT] [--automation-read-root DIR]… [--automation-write-root DIR]… [--automation-allow-server URL]…` Serve MCP on stdio: headless by default, or attached to a running app started with `figcraft --control PORT`. See [mcp.md](mcp.md). The automation roots (each repeatable; existing @@ -283,10 +283,11 @@ write root); everything else is refused ([mcp.md › Confining file access](mcp. They apply to the headless session only, and that is why `--attach` refuses them: an attached server is confined by the app it attaches to, from the flags that app was started with. With `--attach`, `--timeout SECONDS` (1–600, default 60) is how long the app may take over each request. The headless -session can host, join and publish -live sessions (`collab.*`: without a key on a server open to the public, with `collab.serverInfo`, -`collab.manageFile` for the owner token and `collab.report`) and use plugin directories -(`plugin.directory.*`); the one-shot `run` can't (no network link). +session can join a shared file on an explicitly allowed server with `--automation-allow-server +wss://host/`; the file must already have been published and the agent needs its edit link. That +flag only permits `collab.join` to the named server. Other network commands remain disabled; without +the flag, all network commands remain disabled as well. See [Confining file access](mcp.md#confining-file-access). +The one-shot `run` has no network link. ### `plugin publish --server ws://host:port/[?key=KEY]` diff --git a/docs/mcp.md b/docs/mcp.md index c1f3992a9..0bedffdd3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -112,6 +112,32 @@ Each may be given more than once, as `--flag DIR` or `--flag=DIR`: `\\server\share\…`, or a mounted network drive) is still a root, so reading and writing inside it reaches that file server, and saving there sends the document to it. Give only roots you would let the agent's files go to. +- **Joining one approved server (headless only):** add one or more + `--automation-allow-server wss://figcraft.example.com/` flags. Each URL must be a `ws://` or + `wss://` server address with no query or key. A join link is accepted only when its parsed + scheme, host and port match an allowed server and its path is within that server's path prefix. + The only newly permitted network operation is `collab.join` to such a server. Hosting, publishing + a new file, team libraries and plugin directories remain blocked; the server's administrative + key is not needed or accepted in the allowlist. Without this flag the network remains blocked, + as before. + + This lets an agent join a file that was published once from the desktop app. Give headless MCP + the file's **edit link**, then call `collab.join` with it. The server-hosted document is the shared + source of truth: the agent's edits sync to the server and other clients in the live session, and + the server keeps confirmed edits after everyone disconnects. A later headless MCP process can + join again with the same link. The desktop app does not need to stay open on the publishing + machine. A local `.figcraft` file is not automatically kept in sync; use `file.saveAs` to save a + separate local snapshot inside a write root when needed. + + For example: + + ```sh + figcraft-cli mcp --automation-read-root /work/designs --automation-write-root /work/designs \ + --automation-allow-server wss://figcraft.example.com/ + ``` + + The edit link is a file-specific secret; give it only to the agent and clients you trust. Use an + edit link, not a view link, when the agent must change the file. - Not confined: the app's own folders, which no tool names (preferences, Data Recovery copies, plugins installed from a plugin directory, the system fonts). - `--attach` with either flag is a usage error: the app runs the commands, so only the app can From 470b6483f1a5a40479e3aaeb204896a1265937e7 Mon Sep 17 00:00:00 2001 From: Anderson Date: Mon, 23 Nov 2026 04:04:24 +0100 Subject: [PATCH 29/48] Require both roots for headless MCP --- apps/figcraft-cli/src/main.rs | 32 +++++++++++++++++++------------ apps/figcraft-cli/tests/it/cli.rs | 28 ++++++++++++++++++++++++--- docs/cli.md | 2 ++ docs/mcp.md | 5 +++-- 4 files changed, 50 insertions(+), 17 deletions(-) diff --git a/apps/figcraft-cli/src/main.rs b/apps/figcraft-cli/src/main.rs index 43d783de4..385cec739 100644 --- a/apps/figcraft-cli/src/main.rs +++ b/apps/figcraft-cli/src/main.rs @@ -69,6 +69,10 @@ impl From for CliError { pub type CliResult = Result; fn run(cli: Cli) -> CliResult { + let mcp_roots_for_server = match &cli.command { + Command::Mcp(a) if a.attach.is_none() => Some(mcp_roots(&a.roots, &a.automation_allow_servers)?), + _ => None, + }; if !cli.no_system_fonts { // Text lays out with the installed fonts, like the desktop app, so headless renders and // auto layout sizes match what users see. @@ -92,7 +96,7 @@ fn run(cli: Cli) -> CliResult { Ok(ExitCode::SUCCESS) } // `--attach` conflicts with the roots: the app runs the commands, only its own roots can confine them. - Command::Mcp(a) => mcp(a.attach.as_deref(), a.timeout, mcp_roots(&a.roots, &a.automation_allow_servers)?), + Command::Mcp(a) => mcp(a.attach.as_deref(), a.timeout, mcp_roots_for_server), Command::Plugin { command: PluginCommand::Publish(a) } => publish_plugin(&a.folder, &a.server), Command::Connect { command: ConnectCommand::Publish(a) } => confined(&a.roots, || files::connect_publish(&a.file, &a.mappings, a.dry_run)), Command::Perf(a) => { @@ -172,14 +176,11 @@ fn mcp(attach: Option<&str>, timeout: Option, roots: Option CliResult> { - let Some(roots) = roots_of(roots)? else { - return if allowed_servers.is_empty() { - Ok(None) - } else { - Err(CliError::Usage("--automation-allow-server requires automation read or write roots".into())) - }; - }; +fn mcp_roots(roots: &RootArgs, allowed_servers: &[String]) -> CliResult { + if roots.automation_read_root.is_empty() || roots.automation_write_root.is_empty() { + return Err(CliError::Usage("headless mcp requires both --automation-read-root and --automation-write-root".into())); + } + let roots = figcraft_engine::file_access::Roots::new(&roots.automation_read_root, &roots.automation_write_root).map_err(CliError::Failed)?; let mut servers = Vec::with_capacity(allowed_servers.len()); for server in allowed_servers { if server.contains('?') { @@ -192,7 +193,7 @@ fn mcp_roots(roots: &RootArgs, allowed_servers: &[String]) -> CliResult Date: Mon, 23 Nov 2026 04:32:27 +0100 Subject: [PATCH 30/48] Clarify approved MCP network exception --- docs/mcp.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 42092830a..8c8580d06 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -103,16 +103,16 @@ Each may be given more than once, as `--flag DIR` or `--flag=DIR`: refused too. A local volume's `\\?\Volume{…}\` path is let through. A link whose text is a native NT name (`\Device\…`, `\??\…`, `\GLOBAL??\…`) is refused as a device path, and so is a name that ends in a period or a space, in a path or as a link's target, since Windows trims it where it looks a name up. -- **The network:** a confined call reaches no FigCraft or plugin server, so it can't send a - document anywhere through one. Hosting, joining, publishing and sharing a file (`collab.host`, - `collab.join`, `collab.publish`, `collab.share` …), team libraries on a server (`library.check` - refuses, and `library.updates` / `library.list` report the refusal for each instead of the last - version fetched) and plugin directories are refused with `automation roots are set: commands - don't reach the network …`. The app started with the flags confines its own window too, so its - sharing is off as well. One exception: a root on a network share (a UNC path such as - `\\server\share\…`, or a mounted network drive) is still a root, so reading and writing inside - it reaches that file server, and saving there sends the document to it. Give only roots you would - let the agent's files go to. +- **The network:** confined calls cannot reach a FigCraft or plugin server, except for headless + MCP's `collab.join` to a server explicitly allowed with `--automation-allow-server` (below). + Hosting, publishing and sharing a file (`collab.host`, `collab.publish`, `collab.share` …), team + libraries on a server (`library.check` refuses, and `library.updates` / `library.list` report the + refusal for each instead of the last version fetched) and plugin directories remain refused with + `automation roots are set: commands don't reach the network …`. The app started with the flags + confines its own window too, so its sharing is off as well. One exception: a root on a network + share (a UNC path such as `\\server\share\…`, or a mounted network drive) is still a root, so + reading and writing inside it reaches that file server, and saving there sends the document to + it. Give only roots you would let the agent's files go to. - **Joining one approved server (headless only):** add one or more `--automation-allow-server wss://figcraft.example.com/` flags. Each URL must be a `ws://` or `wss://` server address with no query or key. A join link is accepted only when its parsed From 3cbc4d0031b984fd41acde99bc38b3e6b8a03222 Mon Sep 17 00:00:00 2001 From: Livio Sidler <94077193+LS254@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:02:00 +0100 Subject: [PATCH 31/48] M8: the browser's canvas uploads only what an edit changed of its image Every finished render was converted to a texture image and uploaded whole: after an edit that redrew a part of the view, all of the view and its margin again, every frame of a drag. The retained renderer now says where a patched image differs from the one before (nothing after a full render or a pan, which moves every pixel), the browser's worker numbers its images and is told which one the canvas's texture holds, and a render that only patches that image hands over the patches, which go onto the texture in place. The image around the view and the desktop's render thread hand over whole images, as before. --- crates/render/src/retained.rs | 41 ++++- crates/render/src/retained_edit_tests.rs | 40 +++++ crates/ui-egui/src/canvas.rs | 29 +++- crates/ui-egui/src/canvas/render_worker.rs | 154 ++++++++++++++---- .../ui-egui/src/canvas/zoom_preview_tests.rs | 92 +++++++++-- docs/gaps.md | 11 +- 6 files changed, 310 insertions(+), 57 deletions(-) diff --git a/crates/render/src/retained.rs b/crates/render/src/retained.rs index e8a711fc6..7e24f30fc 100644 --- a/crates/render/src/retained.rs +++ b/crates/render/src/retained.rs @@ -195,12 +195,28 @@ impl Steps { #[derive(Default)] pub struct Retained { last: Option, + /// See [`Self::patched`]. + patched: Option>, } impl Retained { /// Forget the kept image (the next render is full). pub fn clear(&mut self) { self.last = None; + self.patched = None; + } + + /// The image kept from the last render. + pub fn image(&self) -> Option<&Pixmap> { + self.last.as_ref().map(|f| &f.pix) + } + + /// Where the last render's image differs from the one before it, when it is that image with + /// some areas drawn again in place (`[x, y, width, height]` in its pixels; none for a render + /// reused as it was): whoever holds the image before needs only these to have this one. + /// `None` after a full render and after a pan, which moves every pixel. + pub fn patched(&self) -> Option<&[[u32; 4]]> { + self.patched.as_deref() } /// Render `view` of `page`, reusing the previous render where nothing changed. Returns the @@ -267,6 +283,7 @@ impl Retained { /// The previous render patched where it could be (kept, see [`Self::keep`]), or what a full /// render of `view` needs. fn prepare(&mut self, doc: &Arc, page: NodeId, view: &View, opts: &Options) -> Option { + self.patched = None; // A view that can't be put on a pixel grid (non-finite or absurd) draws nothing. let Some((snapped, px)) = snap(view) else { self.last = None; @@ -296,9 +313,10 @@ impl Retained { { let same_doc = Arc::ptr_eq(&last.doc, doc); let s = if same_doc { last.sensitive.clone() } else { Arc::new(sensitive(doc)) }; - if let Some((pix, pixels)) = patch(last, doc, page, &snapped, px, opts, &s) { + if let Some((pix, pixels, areas)) = patch(last, doc, page, &snapped, px, opts, &s) { let work = if pixels == 0 { Work::Reused } else { Work::Partial { pixels } }; self.keep(doc, page, (&snapped, px, fonts), opts, pix, s); + self.patched = areas; return Some(Prepared::Patched(snapped, work)); } sens = Some(s); @@ -387,8 +405,18 @@ fn changed_areas(doc: &Document, page: NodeId, id: NodeId, out: &mut Vec) } /// The previous frame brought up to date for `doc` at `px`, rendering only what changed; `None` -/// when a full render is the better (or only correct) choice. Also returns the pixels rendered. -fn patch(last: Frame, doc: &Arc, page: NodeId, view: &View, px: (i64, i64), opts: &Options, s: &Sensitive) -> Option<(Pixmap, u64)> { +/// when a full render is the better (or only correct) choice. Also returns the pixels rendered, +/// and the areas they are in when nothing else of the image changed (it didn't move). +#[allow(clippy::type_complexity)] +fn patch( + last: Frame, + doc: &Arc, + page: NodeId, + view: &View, + px: (i64, i64), + opts: &Options, + s: &Sensitive, +) -> Option<(Pixmap, u64, Option>)> { let (w, h) = (i64::from(view.width), i64::from(view.height)); let (dx, dy) = (px.0.checked_sub(last.px.0)?, px.1.checked_sub(last.px.1)?); if dx.abs() >= w || dy.abs() >= h { @@ -445,7 +473,7 @@ fn patch(last: Frame, doc: &Arc, page: NodeId, view: &View, px: (i64, } let mut damage: Vec = damage.iter().filter_map(|d| d.clamp(w, h)).collect(); if damage.is_empty() && dx == 0 && dy == 0 { - return Some((last.pix, 0)); + return Some((last.pix, 0, Some(Vec::new()))); } // Layers whose look depends on where they are cut are redrawn whole. let sensitive: Vec = s.areas.iter().chain(last.sensitive.areas.iter()).filter_map(|r| to_px(*r, view.scale, px)).collect(); @@ -480,7 +508,10 @@ fn patch(last: Frame, doc: &Arc, page: NodeId, view: &View, px: (i64, for d in &damage { render_into(FrameRender { doc, page, view, px, opts }, d, margin, &mut pix)?; } - Some((pix, pixels)) + let area = + |d: &Px| Some([u32::try_from(d.x0).ok()?, u32::try_from(d.y0).ok()?, u32::try_from(d.x1 - d.x0).ok()?, u32::try_from(d.y1 - d.y0).ok()?]); + let areas = if dx == 0 && dy == 0 { damage.iter().map(area).collect() } else { None }; + Some((pix, pixels, areas)) } /// Move the image's content by `(-dx, -dy)` pixels in place (what was at `(x, y)` goes to diff --git a/crates/render/src/retained_edit_tests.rs b/crates/render/src/retained_edit_tests.rs index 38c4c3013..71723a870 100644 --- a/crates/render/src/retained_edit_tests.rs +++ b/crates/render/src/retained_edit_tests.rs @@ -65,3 +65,43 @@ fn a_clip_edge_on_a_pixel_boundary_clips_the_same_in_every_render() { assert_same(&pix, &render_view(&smaller, page, &shown, &opts).unwrap(), &format!("lod {lod}")); } } +/// What a patched render reports as changed ([`Retained::patched`]) takes in every pixel that +/// differs from the image before: whoever holds that image needs no more to have the new one. +#[test] +fn a_patched_render_says_where_it_differs_from_the_one_before() { + let mut d = Document::new("patched"); + let page = d.first_page().unwrap(); + let back = d.create(page, NodeKind::Rectangle, "Back", 0.0, 0.0, 200.0, 140.0).unwrap(); + d.get_mut(back).unwrap().fills = vec![Paint::solid(Color::from_hex("F4F6F5").unwrap())]; + let shape = d.create(page, NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }, "Shape", 30.0, 30.0, 72.0, 49.0).unwrap(); + d.get_mut(shape).unwrap().fills = vec![Paint::solid(Color::from_hex("7FAE9C").unwrap())]; + let v = View { origin: (0.0, 0.0), scale: 3.0, width: 600, height: 400 }; + let doc = Arc::new(d); + let mut r = Retained::default(); + r.render(&doc, page, &v, &Options::default()).unwrap(); + assert!(r.patched().is_none(), "a full render"); + let before = r.image().unwrap().clone(); + let mut d2 = (*doc).clone(); + d2.get_mut(shape).unwrap().height = 30.0; + let d2 = Arc::new(d2); + let (_, after, work) = r.render(&d2, page, &v, &Options::default()).unwrap(); + let after = after.clone(); + let areas = r.patched().expect("patched in place").to_vec(); + let Work::Partial { pixels } = work else { panic!("{work:?}") }; + assert_eq!(areas.iter().map(|a| u64::from(a[2]) * u64::from(a[3])).sum::(), pixels); + let w = after.width() as usize; + let (mut differ, mut outside) = (0, 0); + for (i, (a, b)) in before.data().chunks_exact(4).zip(after.data().chunks_exact(4)).enumerate() { + if a != b { + differ += 1; + let (x, y) = ((i % w) as u32, (i / w) as u32); + outside += usize::from(!areas.iter().any(|&[ax, ay, aw, ah]| x >= ax && y >= ay && x < ax + aw && y < ay + ah)); + } + } + assert!(differ > 1000 && outside == 0, "{differ} pixels differ, {outside} of them outside {areas:?}"); + // The same again: nothing to hand over. A pan: every pixel moved. + r.render(&d2, page, &v, &Options::default()).unwrap(); + assert_eq!(r.patched(), Some(&[][..])); + r.render(&d2, page, &View { origin: (2.0, 0.0), ..v }, &Options::default()).unwrap(); + assert!(r.patched().is_none(), "a pan"); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 3d3f05082..0c21d5e8f 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -59,6 +59,9 @@ pub struct CanvasState { pub tex_coarse: bool, /// The request the texture answers ([`crate::render_worker::Done::seq`]). tex_seq: u64, + /// Which of the worker's images the texture holds ([`render_worker::Done::frame`]), when it + /// is one of them: what the next render may hand over patches of. + tex_frame: Option, /// Refined images of the files and pages shown before, newest first: switching back to one /// shows its image at once while it renders again, instead of a blank canvas (and, where /// renders are slow, a coarse preview). @@ -109,6 +112,7 @@ impl Default for CanvasState { tex_of: None, tex_coarse: false, tex_seq: 0, + tex_frame: None, kept: Vec::new(), surround: None, submitted: None, @@ -157,6 +161,8 @@ impl CanvasState { self.kept.insert(0, Kept { texture, view, of, seq: self.tex_seq }); } self.tex_coarse = false; + // The worker's image is of the other file or page: this texture is none of its. + self.tex_frame = None; 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); } @@ -319,6 +325,9 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { let shown = app.session.ds().map(|ds| (ds.uid, ds.page)).ok(); let docs = &app.session.docs; app.canvas.switch_texture(shown, |uid| docs.iter().any(|d| d.uid == uid)); + // The browser's worker hands over only what changed of the image the texture holds. + #[cfg(target_arch = "wasm32")] + worker.texture_holds(app.canvas.tex_frame.filter(|_| app.canvas.texture.is_some() && app.canvas.tex_of == shown && !app.canvas.tex_coarse)); if let Some(done) = worker.poll() && shows(&app.canvas, &done, shown) { @@ -332,10 +341,18 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { } else { egui::TextureOptions::LINEAR }; - match &mut app.canvas.texture { - Some(t) => t.set(done.image, filter), - None => app.canvas.texture = Some(ctx.load_texture("figcraft-canvas", done.image, filter)), + match (done.image, &mut app.canvas.texture) { + (render_worker::Pixels::Whole(image), Some(t)) => t.set(image, filter), + (render_worker::Pixels::Whole(image), None) => app.canvas.texture = Some(ctx.load_texture("figcraft-canvas", image, filter)), + // Patches of the image the texture holds (the worker was told which). + (render_worker::Pixels::Patches(parts), Some(t)) => { + for (at, image) in parts { + t.set_partial(at, image, filter); + } + } + (render_worker::Pixels::Patches(_), None) => {} } + app.canvas.tex_frame = (done.frame != 0 && !done.coarse).then_some(done.frame); let latency = Some(done.at.elapsed().as_secs_f64() * 1000.0); if done.coarse { app.canvas.preview_latency_ms = latency; @@ -347,17 +364,19 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { app.canvas.tex_coarse = done.coarse; app.canvas.tex_seq = done.seq; } + // The image around the view always comes whole (nothing tells its worker what is held). if let Some(around) = worker.surround() && shown == Some((around.uid, around.page)) + && let render_worker::Pixels::Whole(image) = around.image { let of = (around.uid, around.page); match &mut app.canvas.surround { Some((t, view, at)) => { - t.set(around.image, egui::TextureOptions::LINEAR); + t.set(image, egui::TextureOptions::LINEAR); (*view, *at) = (around.view, of); } None => { - let t = ctx.load_texture("figcraft-canvas-surround", around.image, egui::TextureOptions::LINEAR); + let t = ctx.load_texture("figcraft-canvas-surround", image, egui::TextureOptions::LINEAR); app.canvas.surround = Some((t, around.view, of)); } } diff --git a/crates/ui-egui/src/canvas/render_worker.rs b/crates/ui-egui/src/canvas/render_worker.rs index c0fc8f312..54d4222d1 100644 --- a/crates/ui-egui/src/canvas/render_worker.rs +++ b/crates/ui-egui/src/canvas/render_worker.rs @@ -77,9 +77,33 @@ pub struct Job { pub at: Instant, } +/// What a finished render hands the canvas for its texture. +pub enum Pixels { + /// The whole image. + Whole(egui::ColorImage), + /// The parts that differ from the image the canvas said its texture holds + /// ([`Inline::texture_holds`]): each goes at its position (x, y) in that texture. An edit + /// redraws a part of the view; converting and uploading all of it again cost more than + /// drawing the part. + Patches(Vec<([usize; 2], egui::ColorImage)>), +} + +impl Pixels { + /// The whole image, when that is what this is. + pub fn whole(&self) -> Option<&egui::ColorImage> { + match self { + Pixels::Whole(image) => Some(image), + Pixels::Patches(_) => None, + } + } +} + pub struct Done { /// The image, ready for a texture (converted off the UI thread). - pub image: egui::ColorImage, + pub image: Pixels, + /// Which image of the worker's this is, numbered as they are drawn (0: a preview, or a + /// worker that doesn't number them): what the canvas reports back as its texture's. + pub frame: u64, /// The view the image shows (the requested one snapped outwards to whole device pixels). pub view: View, pub ms: f64, @@ -97,15 +121,39 @@ pub struct Done { /// A render of a document in `profile` as a texture image for the screen (sRGB). pub fn screen_image(pix: &Pixmap, profile: ColorProfile) -> egui::ColorImage { - let size = [pix.width() as usize, pix.height() as usize]; + screen_pixels([pix.width() as usize, pix.height() as usize], pix.data(), profile) +} + +/// [`screen_image`] of `size` premultiplied RGBA pixels. +fn screen_pixels(size: [usize; 2], rgba: &[u8], profile: ColorProfile) -> egui::ColorImage { if profile.is_srgb() { - return egui::ColorImage::from_rgba_premultiplied(size, pix.data()); + return egui::ColorImage::from_rgba_premultiplied(size, rgba); } - let mut data = pix.data().to_vec(); + let mut data = rgba.to_vec(); profile.conversion_to(ColorProfile::Srgb).apply_pixels(&mut data); egui::ColorImage::from_rgba_premultiplied(size, &data) } +/// The areas `[x, y, width, height]` of `pix` as texture images at their positions; `None` when +/// one doesn't lie in it. +fn screen_patches(pix: &Pixmap, areas: &[[u32; 4]], profile: ColorProfile) -> Option> { + let row = pix.width() as usize * 4; + areas + .iter() + .map(|&[x, y, w, h]| { + let (x, y, w, h) = (x as usize, y as usize, w as usize, h as usize); + if w == 0 || h == 0 || x + w > pix.width() as usize || y + h > pix.height() as usize { + return None; + } + let mut rgba = Vec::with_capacity(w * h * 4); + for r in y..y + h { + rgba.extend_from_slice(pix.data().get(r * row + x * 4..r * row + (x + w) * 4)?); + } + Some(([x, y], screen_pixels([w, h], &rgba, profile))) + }) + .collect() +} + /// Soft proof: grey diagonal stripes over the pixels whose colours sRGB can't show. fn mark_outside_srgb(image: &mut egui::ColorImage, pix: &Pixmap, profile: ColorProfile) { let w = image.size[0].max(1); @@ -136,16 +184,25 @@ fn options(job: &Job) -> figcraft_render::Options { fn run(job: &Job, view: &View, retained: &mut Retained, coarse: bool) -> Option { let t0 = Instant::now(); let (view, pix, work) = retained.render(&job.doc, job.page, view, &options(job))?; - Some(done(job, view, pix, work, t0.elapsed().as_secs_f64() * 1000.0, coarse)) + Some(done(job, view, pix, work, t0.elapsed().as_secs_f64() * 1000.0, coarse, None)) } -/// The image `pix` of `view`, rendered for `job` in `ms`. -fn done(job: &Job, view: View, pix: &Pixmap, work: Work, ms: f64, coarse: bool) -> Done { - let mut image = screen_image(pix, job.doc.color_profile); - 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 } +/// The image `pix` of `view`, rendered for `job` in `ms`. With `patched`, only those areas of it +/// (see [`Pixels::Patches`]): the caller knows the canvas holds the rest. A soft proof stripes the +/// whole image, so it is always handed over whole. +fn done(job: &Job, view: View, pix: &Pixmap, work: Work, ms: f64, coarse: bool, patched: Option<&[[u32; 4]]>) -> Done { + let patches = patched.filter(|_| !job.proof).and_then(|areas| screen_patches(pix, areas, job.doc.color_profile)); + let image = match patches { + Some(parts) => Pixels::Patches(parts), + None => { + let mut image = screen_image(pix, job.doc.color_profile); + if job.proof { + mark_outside_srgb(&mut image, pix, job.doc.color_profile); + } + Pixels::Whole(image) + } + }; + Done { image, frame: 0, view, ms, work, uid: job.uid, page: job.page, coarse, at: job.at, seq: 0 } } /// The coarse image around the view is this many views wide and tall, centred on it. @@ -211,7 +268,7 @@ impl Surround { let t0 = Instant::now(); let d = guarded(&mut self.retained, |r| { let (snapped, pix, work) = r.render(&job.doc, job.page, &view, &options(job))?; - (!(same && work == Work::Reused)).then(|| done(job, snapped, pix, work, t0.elapsed().as_secs_f64() * 1000.0, true)) + (!(same && work == Work::Reused)).then(|| done(job, snapped, pix, work, t0.elapsed().as_secs_f64() * 1000.0, true, None)) }); if d.is_some() { self.of = Some((job.uid, job.page, view, job.proof)); @@ -240,6 +297,9 @@ pub struct Renders { /// A full render being drawn band by band (the browser): the job it was started for, the /// font generation then, the bands and the time they took so far. steps: Option, + /// The number of the image `full` keeps: every image drawn there gets the next one + /// ([`Done::frame`]), handed to the canvas or not. + frame: u64, } /// A full render drawn in steps and what it is of: a newer job of the same file, page, zoom, size @@ -298,7 +358,7 @@ impl Default for Renders { impl Renders { /// Previews when renders from scratch take at least `ms` (tests: 0, always). pub fn with_threshold(ms: f64) -> Self { - Self { full: Retained::default(), preview: Retained::default(), last: None, full_ms: 0.0, preview_after_ms: ms, steps: None } + Self { full: Retained::default(), preview: Retained::default(), last: None, full_ms: 0.0, preview_after_ms: ms, steps: None, frame: 0 } } /// Whether `job` is a render from scratch: the kept image is of another zoom, page or file, or @@ -332,9 +392,15 @@ impl Renders { preview_with(job, &mut self.preview) } + /// `d`, an image drawn in `full` just now, numbered. + fn numbered(&mut self, d: Done) -> Done { + self.frame += 1; + Done { frame: self.frame, ..d } + } + /// The image of `job`'s view, built on the kept one where it can be. pub fn refine(&mut self, job: &Job) -> Option { - let done = guarded(&mut self.full, |r| run(job, &job.view, r, false)); + let done = guarded(&mut self.full, |r| run(job, &job.view, r, false)).map(|d| self.numbered(d)); if let Some(d) = &done { self.last = Some((job.uid, job.page, job.view.scale)); if d.work == Work::Full { @@ -346,7 +412,10 @@ impl Renders { /// [`Self::refine`] for about `budget_ms` at a time (the browser): a full render is drawn band by /// band over several calls, the kept image (re-projected) or the preview showing meanwhile. - pub fn refine_for(&mut self, job: &Job, budget_ms: f64) -> Refined { + /// + /// `holds` is the number of the image the canvas's texture holds ([`Done::frame`]), if it is + /// one of these: a render that only patches that image hands over the patches. + pub fn refine_for(&mut self, job: &Job, budget_ms: f64, holds: Option) -> Refined { let t0 = Instant::now(); if let Some(s) = self.steps.as_ref() && !same_settings(&s.job, job) @@ -357,7 +426,7 @@ impl Renders { self.steps = None; } if self.steps.is_none() - && let Some(r) = self.begin(job, t0, None) + && let Some(r) = self.begin(job, t0, None, holds) { return r; } @@ -382,14 +451,15 @@ impl Renders { self.full_ms = spent; // The image of the job it was started for: its document's colour profile, its // proof setting and its request time. - let drawn = done(&drawn_for, view, pix, Work::Full, spent, false); + let drawn = done(&drawn_for, view, pix, Work::Full, spent, false, None); + let drawn = self.numbered(drawn); // Drawn for this very request: shown, done. Otherwise kept, then started on like // any render: an edit, a pan or images that came meanwhile are patched in, or it // is drawn again in steps (never all at once here), this one shown till then. if same_request(&drawn_for, fonts, job) { return Refined::Done(self.finished(job, Some(drawn))); } - self.begin(job, t0, Some(drawn)).unwrap_or(Refined::More) + self.begin(job, t0, Some(drawn), holds).unwrap_or(Refined::More) } Err(_) => { self.steps = None; @@ -402,18 +472,27 @@ impl Renders { /// Start `job` on the kept image: done when it is reused or patched, `None` when a full render /// is now drawn in steps. `drawn` is the kept image just drawn in steps: what a reuse shows, /// else shown while it is drawn again. - fn begin(&mut self, job: &Job, t0: Instant, mut drawn: Option) -> Option { + fn begin(&mut self, job: &Job, t0: Instant, mut drawn: Option, holds: Option) -> Option { // The snapped view may be a row taller. let rows = job.view.height.saturating_add(1).div_ceil(MAX_BANDS).max(MIN_BAND_ROWS); - let begun = - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match self.full.begin(&job.doc, job.page, &job.view, &options(job), rows) { - Some(Begun::Done(view, pix, work)) => Err(Box::new(match drawn.take() { - Some(d) if work == Work::Reused => Some(d), - _ => Some(done(job, view, pix, work, t0.elapsed().as_secs_f64() * 1000.0, false)), - })), - Some(Begun::Steps(steps)) => Ok(steps), - None => Err(Box::new(None)), - })); + // The canvas holds the image this render starts from: one that only patches it hands + // over the patches. + let held = holds.is_some_and(|f| f == self.frame); + let full = &mut self.full; + let begun = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let (view, work) = match full.begin(&job.doc, job.page, &job.view, &options(job), rows) { + Some(Begun::Done(view, _, work)) => (view, work), + Some(Begun::Steps(steps)) => return Ok(steps), + None => return Err(Box::new(None)), + }; + Err(Box::new(match drawn.take() { + Some(d) if work == Work::Reused => Some((d, false)), + _ => full.image().map(|pix| { + let patched = full.patched().filter(|_| held); + (done(job, view, pix, work, t0.elapsed().as_secs_f64() * 1000.0, false, patched), true) + }), + })) + })); match begun { Ok(Ok(steps)) => { // A pan or an edit at this zoom builds on this render: no preview for it. @@ -421,7 +500,11 @@ impl Renders { self.steps = Some(Stepping { job: job.clone(), fonts: figcraft_text::layout_generation(), steps, spent: 0.0 }); drawn.map(Refined::Shown) } - Ok(Err(d)) => Some(Refined::Done(self.finished(job, *d))), + Ok(Err(d)) => { + // An image drawn now gets its number; one drawn in steps just before has it. + let d = d.map(|(d, new)| if new { self.numbered(d) } else { d }); + Some(Refined::Done(self.finished(job, d))) + } Err(_) => { self.full.clear(); Some(Refined::Done(None)) @@ -687,6 +770,8 @@ pub struct Inline { /// The wait for the pending job's preview. wait: std::time::Duration, renders: Renders, + /// See [`Self::texture_holds`]. + holds: Option, } #[cfg(target_arch = "wasm32")] @@ -708,6 +793,7 @@ impl Inline { settle, wait: settle, renders: Renders::default(), + holds: None, } } /// Previewing when renders from scratch take at least `ms` (tests: 0, whatever the machine). @@ -731,6 +817,12 @@ impl Inline { pub fn surround(&mut self) -> Option { None } + /// Tell the worker which of its images the canvas's texture holds ([`Done::frame`]; `None`: + /// none of them, or not for sure). The next image comes as patches of that one when that is + /// all that changed ([`Pixels::Patches`]); without this, every image comes whole. + pub fn texture_holds(&mut self, frame: Option) { + self.holds = frame; + } pub fn poll(&mut self) -> Option { self.poll_at(Instant::now()) } @@ -755,7 +847,7 @@ impl Inline { } } let job = self.pending.as_ref()?; - match self.renders.refine_for(job, STEP_MS) { + match self.renders.refine_for(job, STEP_MS, self.holds) { Refined::Done(d) => { self.pending = None; d.map(|d| answering(d, self.submitted)) diff --git a/crates/ui-egui/src/canvas/zoom_preview_tests.rs b/crates/ui-egui/src/canvas/zoom_preview_tests.rs index af9914b74..6bb032bd5 100644 --- a/crates/ui-egui/src/canvas/zoom_preview_tests.rs +++ b/crates/ui-egui/src/canvas/zoom_preview_tests.rs @@ -20,9 +20,15 @@ use super::{CanvasState, shows}; use figcraft_render::Retained; use crate::render_worker::{ - Done, Inline, Job, PREVIEW_AFTER_MS, PREVIEW_FACTOR, Refined, Renders, SETTLE_MS, Worker, better, coarse_view, preview_with, render_now, + Done, Inline, Job, PREVIEW_AFTER_MS, PREVIEW_FACTOR, Pixels, Refined, Renders, SETTLE_MS, Worker, better, coarse_view, preview_with, render_now, }; +/// The whole image a render handed over (these all are: nothing here tells the worker what the +/// canvas holds). +fn whole(d: &Done) -> &egui::ColorImage { + d.image.whole().expect("a whole image") +} + /// A page of ellipses with a rectangle on top; the session and the rectangle. The system fonts are /// scanned first (once per process, and a concurrent caller waits for it): the scan another test /// starts bumps the global font generation, and a render kept from before it is stale, so a pan @@ -93,17 +99,17 @@ pub(super) fn job(doc: &Arc, page: NodeId, uid: u64, view: View) -> Jo /// Every pixel of `a` and `b` alike. fn same_pixels(a: &Done, b: &Done) -> bool { - a.image.size == b.image.size && a.image.pixels == b.image.pixels + whole(a).size == whole(b).size && whole(a).pixels == whole(b).pixels } /// The same image up to where render bands meet ([`figcraft_render::Steps`] and the desktop's /// parallel bands cut the view in different places): on each row, under a quarter of a level on /// average and at most one pixel in twenty off. fn close_pixels(a: &Done, b: &Done) -> bool { - let [w, h] = a.image.size; - a.image.size == b.image.size + let [w, h] = whole(a).size; + whole(a).size == whole(b).size && (0..h).all(|y| { - let row = |d: &Done| d.image.pixels[y * w..(y + 1) * w].to_vec(); + let row = |d: &Done| whole(d).pixels[y * w..(y + 1) * w].to_vec(); let (ra, rb) = (row(a), row(b)); let diffs: Vec = ra.iter().zip(&rb).map(|(p, q)| p.to_array().iter().zip(q.to_array()).map(|(x, y)| u32::from(x.abs_diff(y))).sum()).collect(); @@ -135,7 +141,7 @@ fn refined_at(w: &mut Inline, now: Instant) -> Option { /// Refine `job` through `r` with no time to spare (a band a call); the image and how many calls. fn stepped(r: &mut Renders, job: &Job) -> (Option, usize) { for n in 1..1000 { - match r.refine_for(job, 0.0) { + match r.refine_for(job, 0.0, None) { Refined::Done(d) => return (d, n), Refined::Shown(_) | Refined::More => {} } @@ -162,7 +168,7 @@ fn a_zoom_out_previews_the_whole_view_then_refines_to_a_fresh_render() { let p = r.preview(&out).expect("a preview first"); assert!(p.coarse && (p.uid, p.page) == (ds.uid, ds.page)); assert!(covers(&p.view, &out.view), "the preview shows the whole view asked for"); - let pixels = |d: &Done| d.image.size[0] * d.image.size[1]; + let pixels = |d: &Done| whole(d).size[0] * whole(d).size[1]; let fresh = render_now(&out).unwrap(); assert!( (pixels(&p) as f64) * PREVIEW_FACTOR * PREVIEW_FACTOR < 1.5 * pixels(&fresh) as f64, @@ -618,7 +624,7 @@ fn the_browser_draws_a_full_render_band_by_band() { assert!(n > 2 && !r.stepping(), "several calls, then done ({n})"); assert!(close_pixels(&d, &render_now(&at(300.0)).unwrap())); // Kept: a pan now patches it at once. - assert!(matches!(r.refine_for(&at(320.0), 0.0), Refined::Done(Some(d)) if d.work != Work::Full)); + assert!(matches!(r.refine_for(&at(320.0), 0.0, None), Refined::Done(Some(d)) if d.work != Work::Full)); } #[test] @@ -628,14 +634,14 @@ fn a_pan_while_drawing_finishes_the_render_then_patches_it_and_a_zoom_drops_it() let ds = s.ds().unwrap(); let at = |x, scale| job(&ds.doc, ds.page, ds.uid, view(x, scale)); let mut r = Renders::default(); - assert!(matches!(r.refine_for(&at(300.0, 1.0), 0.0), Refined::More)); + assert!(matches!(r.refine_for(&at(300.0, 1.0), 0.0, None), Refined::More)); // Panned meanwhile: the same render goes on, and what comes is the panned view. let (d, _) = stepped(&mut r, &at(330.0, 1.0)); let d = d.expect("drawn"); assert!(close_pixels(&d, &render_now(&at(330.0, 1.0)).unwrap()), "the panned view"); // Zoomed meanwhile: the render under way is dropped for one of the new zoom. let mut r = Renders::default(); - assert!(matches!(r.refine_for(&at(300.0, 1.0), 0.0), Refined::More)); + assert!(matches!(r.refine_for(&at(300.0, 1.0), 0.0, None), Refined::More)); let (d, _) = stepped(&mut r, &at(300.0, 2.0)); assert_eq!(d.expect("drawn").view.scale, 2.0); } @@ -649,7 +655,7 @@ fn an_edit_while_drawing_shows_in_what_comes() { (ds.doc.clone(), ds.page, ds.uid) }; let mut r = Renders::default(); - assert!(matches!(r.refine_for(&job(&doc, page, uid, v.clone()), 0.0), Refined::More)); + assert!(matches!(r.refine_for(&job(&doc, page, uid, v.clone()), 0.0, None), Refined::More)); // Edited meanwhile, the view unchanged: the render goes on and what comes shows the edit. s.execute("shape.rectangle", &json!({"x": 100, "y": 0, "width": 400, "height": 400})).unwrap(); let edited = job(&s.ds().unwrap().doc, page, uid, v); @@ -663,11 +669,11 @@ fn a_render_overtaken_by_a_long_pan_is_shown_then_drawn_again() { let s = slow_scene(std::slice::from_ref(&v), 3.0 * PREVIEW_AFTER_MS); let ds = s.ds().unwrap(); let mut r = Renders::default(); - assert!(matches!(r.refine_for(&job(&ds.doc, ds.page, ds.uid, v.clone()), 0.0), Refined::More)); + assert!(matches!(r.refine_for(&job(&ds.doc, ds.page, ds.uid, v.clone()), 0.0, None), Refined::More)); // Panned more than a view meanwhile: nothing to patch. What was drawn shows, then the new view. let far = job(&ds.doc, ds.page, ds.uid, view_at((1500.0, 200.0), 1.0, 600, 600)); let mut shown = vec![]; - let last = (0..1000).find_map(|_| match r.refine_for(&far, 0.0) { + let last = (0..1000).find_map(|_| match r.refine_for(&far, 0.0, None) { Refined::More => None, Refined::Shown(d) => { shown.push(d); @@ -709,7 +715,7 @@ fn a_change_of_options_while_drawing_drops_the_render() { outlined.outline = true; let (_, alone) = stepped(&mut Renders::default(), &outlined); let mut r = Renders::default(); - assert!(matches!(r.refine_for(&plain, 0.0), Refined::More)); + assert!(matches!(r.refine_for(&plain, 0.0, None), Refined::More)); let (d, n) = stepped(&mut r, &outlined); assert!(d.is_some_and(|d| !d.coarse)); assert!(n <= alone + 1, "the old render's bands are dropped: {n} calls against {alone} alone"); @@ -726,6 +732,62 @@ fn a_render_dropped_while_drawing_leaves_its_time_as_the_measure() { let at = |scale| job(&ds.doc, ds.page, ds.uid, view(scale)); // Previews once renders have taken any time at all: a band has, where no measure (0 ms) hasn't. let mut r = Renders::with_threshold(1e-9); - assert!(matches!(r.refine_for(&at(1.0), 0.0), Refined::More)); + assert!(matches!(r.refine_for(&at(1.0), 0.0, None), Refined::More)); assert!(r.preview(&at(2.0)).is_some(), "the zoom gets a preview by the dropped render's measure"); } + +/// `parts` put on `image` at their positions, as the canvas puts them on its texture. +fn patched(image: &egui::ColorImage, parts: &[([usize; 2], egui::ColorImage)]) -> egui::ColorImage { + let mut out = image.clone(); + let w = out.size[0]; + for ([x, y], part) in parts { + for (r, row) in part.pixels.chunks(part.size[0]).enumerate() { + out.pixels[(y + r) * w + x..(y + r) * w + x + row.len()].copy_from_slice(row); + } + } + out +} + +/// An edit redraws a part of the view. Told which image the canvas holds, the worker hands over +/// that part only; put on that image, it makes the new one. Converting and uploading the whole +/// image again after every edit cost more than drawing the part. +#[test] +fn an_edit_hands_over_only_what_changed_of_the_image_the_canvas_holds() { + let (mut s, rect) = document(); + let view = view_at((300.0, 250.0), 1.0, 700, 600); + let now = |s: &Session| { + let ds = s.ds().unwrap(); + job(&ds.doc, ds.page, ds.uid, view.clone()) + }; + let widen = |s: &mut Session, w: u32| s.execute("node.set", &json!({"id": rect, "width": w})).unwrap(); + let mut r = Renders::default(); + let first = stepped(&mut r, &now(&s)).0.expect("drawn"); + assert_ne!(first.frame, 0, "a numbered image"); + // Not told what the canvas holds: the whole image. + widen(&mut s, 280); + let Refined::Done(Some(second)) = r.refine_for(&now(&s), 0.0, None) else { panic!("a patch is done at once") }; + assert!(matches!(second.work, Work::Partial { .. }) && second.image.whole().is_some()); + // Told it holds that image: the changed part only, and with it the canvas has the new image. + widen(&mut s, 240); + let Refined::Done(Some(third)) = r.refine_for(&now(&s), 0.0, Some(second.frame)) else { panic!("a patch is done at once") }; + let Pixels::Patches(parts) = &third.image else { panic!("patches of the image the canvas holds") }; + let handed: usize = parts.iter().map(|(_, p)| p.pixels.len()).sum(); + let all = whole(&second).pixels.len(); + assert!(handed > 0 && handed * 4 < all, "{handed} of {all} pixels handed over"); + let fresh = stepped(&mut Renders::default(), &now(&s)).0.expect("drawn"); + let have = Done { image: Pixels::Whole(patched(whole(&second), parts)), ..render_now(&now(&s)).unwrap() }; + assert!(close_pixels(&have, &fresh), "the patched image is the new one"); + assert!(!close_pixels(&second, &fresh), "and the one before it is not"); + // A canvas that holds an older image (it showed none of the last) gets the whole one. + widen(&mut s, 200); + let Refined::Done(Some(fourth)) = r.refine_for(&now(&s), 0.0, Some(second.frame)) else { panic!("a patch is done at once") }; + assert!(fourth.image.whole().is_some(), "whole for a canvas an image behind"); + // Nothing changed: nothing to hand over. + let Refined::Done(Some(same)) = r.refine_for(&now(&s), 0.0, Some(fourth.frame)) else { panic!("reused at once") }; + assert!(matches!(&same.image, Pixels::Patches(parts) if parts.is_empty()) && same.work == Work::Reused); + // A pan moves every pixel: whole. + let ds = s.ds().unwrap(); + let panned = job(&ds.doc, ds.page, ds.uid, view_at((320.0, 250.0), 1.0, 700, 600)); + let Refined::Done(Some(moved)) = r.refine_for(&panned, 0.0, Some(same.frame)) else { panic!("a pan is patched at once") }; + assert!(moved.image.whole().is_some(), "whole after a pan"); +} diff --git a/docs/gaps.md b/docs/gaps.md index b45e62e81..be7adb84a 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-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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-24 · **Change:** minor (gap 7: the browser uploads only what an edit changed of the canvas image; 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 @@ -287,6 +287,14 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe sixteenth of the pixels first, then refined. With no measure to go by (the first render, another page, a zoom after quick renders), a watchdog thread previews any such render still running after 12 ms (desktop only; the browser renders inline). +- **Landed (2026-11-24):** the browser's canvas uploads only what an edit changed of its image. + Every finished render was converted to a texture image and uploaded whole: after an edit that + redrew a part of the view, all of the view and its margin again, every frame of a drag (37 MB + for a 4112 × 2292 view). The retained renderer says where a patched image differs from the one + before (`Retained::patched`; nothing after a full render or a pan, which moves every pixel), + the browser's worker numbers its images and is told which one the canvas's texture holds, and + a render that only patches that image hands over the patches, put on the texture in place. The + desktop's render thread hands over whole images, as before. - **Landed (2026-10-29):** the browser draws a zoom's full render a band at a time (`Retained::begin`, `Steps`; at least a band a frame and at most eight bands, so a frame draws a part of the render where it drew the whole of it: 0.7–1.4 s where the render took 3.7–4.0 s in the measurement of @@ -615,6 +623,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | Gap 7: after an edit the browser converts and uploads only the redrawn areas of the canvas image to its texture, not all of it. Numbers unchanged | | 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. | From 3ba4292580deb8df16defaf581d9382a51a8143c Mon Sep 17 00:00:00 2001 From: Livio Sidler <94077193+LS254@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:38:18 +0100 Subject: [PATCH 32/48] M8: turning soft proof off hands the canvas the whole image Review of #2598. A soft proof stripes the image handed over, not the renderer's own. With the proof turned off and nothing else changed the renderer reuses its image, and as patches of the one the canvas holds that was nothing at all: the stripes stayed on the texture, and under later patches. An image handed over with a proof is no base for patches. --- crates/ui-egui/src/canvas/render_worker.rs | 29 ++++++++++++++----- .../ui-egui/src/canvas/zoom_preview_tests.rs | 22 ++++++++++++++ 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/canvas/render_worker.rs b/crates/ui-egui/src/canvas/render_worker.rs index 54d4222d1..32e86e6db 100644 --- a/crates/ui-egui/src/canvas/render_worker.rs +++ b/crates/ui-egui/src/canvas/render_worker.rs @@ -300,6 +300,8 @@ pub struct Renders { /// The number of the image `full` keeps: every image drawn there gets the next one /// ([`Done::frame`]), handed to the canvas or not. frame: u64, + /// Whether that image was handed over with a soft proof's stripes ([`Job::proof`]). + frame_proofed: bool, } /// A full render drawn in steps and what it is of: a newer job of the same file, page, zoom, size @@ -358,7 +360,16 @@ impl Default for Renders { impl Renders { /// Previews when renders from scratch take at least `ms` (tests: 0, always). pub fn with_threshold(ms: f64) -> Self { - Self { full: Retained::default(), preview: Retained::default(), last: None, full_ms: 0.0, preview_after_ms: ms, steps: None, frame: 0 } + Self { + full: Retained::default(), + preview: Retained::default(), + last: None, + full_ms: 0.0, + preview_after_ms: ms, + steps: None, + frame: 0, + frame_proofed: false, + } } /// Whether `job` is a render from scratch: the kept image is of another zoom, page or file, or @@ -392,15 +403,16 @@ impl Renders { preview_with(job, &mut self.preview) } - /// `d`, an image drawn in `full` just now, numbered. - fn numbered(&mut self, d: Done) -> Done { + /// `d`, an image drawn in `full` just now for a job with soft proof `proofed`, numbered. + fn numbered(&mut self, d: Done, proofed: bool) -> Done { self.frame += 1; + self.frame_proofed = proofed; Done { frame: self.frame, ..d } } /// The image of `job`'s view, built on the kept one where it can be. pub fn refine(&mut self, job: &Job) -> Option { - let done = guarded(&mut self.full, |r| run(job, &job.view, r, false)).map(|d| self.numbered(d)); + let done = guarded(&mut self.full, |r| run(job, &job.view, r, false)).map(|d| self.numbered(d, job.proof)); if let Some(d) = &done { self.last = Some((job.uid, job.page, job.view.scale)); if d.work == Work::Full { @@ -452,7 +464,7 @@ impl Renders { // The image of the job it was started for: its document's colour profile, its // proof setting and its request time. let drawn = done(&drawn_for, view, pix, Work::Full, spent, false, None); - let drawn = self.numbered(drawn); + let drawn = self.numbered(drawn, drawn_for.proof); // Drawn for this very request: shown, done. Otherwise kept, then started on like // any render: an edit, a pan or images that came meanwhile are patched in, or it // is drawn again in steps (never all at once here), this one shown till then. @@ -477,7 +489,10 @@ impl Renders { let rows = job.view.height.saturating_add(1).div_ceil(MAX_BANDS).max(MIN_BAND_ROWS); // The canvas holds the image this render starts from: one that only patches it hands // over the patches. - let held = holds.is_some_and(|f| f == self.frame); + // Not when that image was handed over with a soft proof's stripes on it: the renderer's + // image has none, so patches of it (none at all, when only the proof was turned off) + // would leave them on the texture. + let held = holds.is_some_and(|f| f == self.frame) && !self.frame_proofed; let full = &mut self.full; let begun = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let (view, work) = match full.begin(&job.doc, job.page, &job.view, &options(job), rows) { @@ -502,7 +517,7 @@ impl Renders { } Ok(Err(d)) => { // An image drawn now gets its number; one drawn in steps just before has it. - let d = d.map(|(d, new)| if new { self.numbered(d) } else { d }); + let d = d.map(|(d, new)| if new { self.numbered(d, job.proof) } else { d }); Some(Refined::Done(self.finished(job, d))) } Err(_) => { diff --git a/crates/ui-egui/src/canvas/zoom_preview_tests.rs b/crates/ui-egui/src/canvas/zoom_preview_tests.rs index 6bb032bd5..88fc51979 100644 --- a/crates/ui-egui/src/canvas/zoom_preview_tests.rs +++ b/crates/ui-egui/src/canvas/zoom_preview_tests.rs @@ -791,3 +791,25 @@ fn an_edit_hands_over_only_what_changed_of_the_image_the_canvas_holds() { let Refined::Done(Some(moved)) = r.refine_for(&panned, 0.0, Some(same.frame)) else { panic!("a pan is patched at once") }; assert!(moved.image.whole().is_some(), "whole after a pan"); } + +/// A soft proof stripes the image handed over, not the renderer's own. With the proof turned off +/// and nothing else changed, the renderer has nothing to redraw: the canvas still gets the whole +/// image, or the stripes would stay on its texture. +#[test] +fn turning_soft_proof_off_hands_over_the_whole_image() { + let (mut s, rect) = document(); + let view = view_at((300.0, 250.0), 1.0, 700, 600); + let now = |s: &Session, proof: bool| { + let ds = s.ds().unwrap(); + Job { proof, ..job(&ds.doc, ds.page, ds.uid, view.clone()) } + }; + let mut r = Renders::default(); + let proofed = stepped(&mut r, &now(&s, true)).0.expect("drawn"); + assert!(proofed.image.whole().is_some()); + let Refined::Done(Some(plain)) = r.refine_for(&now(&s, false), 0.0, Some(proofed.frame)) else { panic!("reused at once") }; + assert!(plain.image.whole().is_some(), "the whole image without the stripes"); + // From there on, edits are patches again. + s.execute("node.set", &json!({"id": rect, "width": 240})).unwrap(); + let Refined::Done(Some(edited)) = r.refine_for(&now(&s, false), 0.0, Some(plain.frame)) else { panic!("a patch is done at once") }; + assert!(matches!(&edited.image, Pixels::Patches(parts) if !parts.is_empty())); +} From 4e48e6f9f29a35acacf055b953791624f32969c2 Mon Sep 17 00:00:00 2001 From: Utakata <5735026+Utakata@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:34:05 +0900 Subject: [PATCH 33/48] Dependencies: align craft-libs at merged sensor develop stage 249a41bd Every craft-libs crate moves to storytold/craft-libs@249a41bd, after craft-develop gained its sensor stage (storytold/craft-libs#3021), which camera raw support needs. craft-image-codecs leaves its own rev and joins the others. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 149 ++++++++++------------------------- Cargo.toml | 44 +++++------ apps/figcraft-web/Cargo.toml | 4 +- 3 files changed, 67 insertions(+), 130 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b56684fec..b959ba8be 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1056,7 +1056,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "rustix 1.1.5", ] @@ -1064,15 +1064,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" -dependencies = [ - "rayon", -] - -[[package]] -name = "craft-dds" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "rayon", ] @@ -1080,12 +1072,12 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" [[package]] name = "craft-fig" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "craft-figma-rest", "craft-kiwi", @@ -1100,7 +1092,7 @@ dependencies = [ [[package]] name = "craft-figcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "craft-zip", "serde", @@ -1112,7 +1104,7 @@ dependencies = [ [[package]] name = "craft-figma-rest" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "serde", "serde_json", @@ -1122,7 +1114,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1137,7 +1129,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "cap-primitives", "craft-atomic", @@ -1158,12 +1150,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "gif", "image", @@ -1172,7 +1164,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1195,39 +1187,12 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ - "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220)", - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220)", - "crc32fast", - "exr", - "flate2", - "half", - "hayro-jpeg2000", - "image", - "image-webp", - "jpeg-encoder", - "png", - "rayon", - "serde_json", - "thiserror 2.0.21", - "tiff", - "zune-core", - "zune-jpeg", - "zune-jpegxl", -] - -[[package]] -name = "craft-image-codecs" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" -dependencies = [ - "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-dds", + "craft-jpeg", + "craft-metadata", + "craft-tiff", "crc32fast", "exr", "flate2", @@ -1249,15 +1214,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" -dependencies = [ - "thiserror 2.0.21", -] - -[[package]] -name = "craft-jpeg" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "thiserror 2.0.21", ] @@ -1265,7 +1222,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "egui", "serde", @@ -1275,12 +1232,12 @@ dependencies = [ [[package]] name = "craft-kiwi" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "craft-keymap", "craft-quit", @@ -1293,23 +1250,11 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "brotli-decompressor", "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220)", - "quick-xml 0.41.0", - "serde", -] - -[[package]] -name = "craft-metadata" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" -dependencies = [ - "brotli-decompressor", - "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-tiff", "quick-xml 0.41.0", "serde", ] @@ -1317,7 +1262,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "krilla", "thiserror 2.0.21", @@ -1326,7 +1271,7 @@ dependencies = [ [[package]] name = "craft-penpot" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "craft-zip", "serde", @@ -1337,7 +1282,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "dispatch2", "egui", @@ -1348,7 +1293,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "craft-atomic", "dirs", @@ -1359,7 +1304,7 @@ dependencies = [ [[package]] name = "craft-sketch" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "craft-figma-rest", "craft-zip", @@ -1371,9 +1316,9 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220)", + "craft-image-codecs", "craft-xml", "data-url", "flate2", @@ -1389,25 +1334,17 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" -dependencies = [ - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-tiff" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "serde", "thiserror 2.0.21", + "tiff", ] [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1427,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "chrono", "dunce", @@ -1454,7 +1391,7 @@ dependencies = [ [[package]] name = "craft-vectordrawable" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "kurbo", ] @@ -1462,7 +1399,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ea9407b3500488bd8af71eb0f1b950306315bf7e#ea9407b3500488bd8af71eb0f1b950306315bf7e" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "js-sys", "serde_json", @@ -1473,7 +1410,7 @@ dependencies = [ [[package]] name = "craft-web-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ea9407b3500488bd8af71eb0f1b950306315bf7e#ea9407b3500488bd8af71eb0f1b950306315bf7e" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "wasm-bindgen", "web-sys", @@ -1482,7 +1419,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "wayland-client", ] @@ -1490,7 +1427,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1500,7 +1437,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2275,8 +2212,8 @@ dependencies = [ "craft-fig", "craft-figcraft-format", "craft-figma-rest", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220)", + "craft-image-codecs", + "craft-jpeg", "craft-penpot", "craft-sketch", "craft-zip", @@ -2370,7 +2307,7 @@ name = "figcraft-render" version = "0.18.1" dependencies = [ "craft-gif", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "crc32fast", "figcraft-color", "figcraft-doc", @@ -3568,7 +3505,7 @@ checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab595c41f33209a7d2220#a49329e71e32ad93794ab595c41f33209a7d2220" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ "base64 0.22.1", "bumpalo", diff --git a/Cargo.toml b/Cargo.toml index c891c0ef4..0c65f864e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,10 +13,10 @@ rust-version = "1.95" repository = "https://github.com/storytold/figcraft" [workspace.dependencies] -craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } -craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220", default-features = false, features = ["tree"] } -craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } -craft-pdf = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } +craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } +craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a", default-features = false, features = ["tree"] } +craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } +craft-pdf = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } # internal figcraft-geom = { path = "crates/geom" } figcraft-color = { path = "crates/color" } @@ -39,39 +39,39 @@ figcraft-plugin = { path = "crates/plugin" } # Keep every craft-libs crate on one rev. # Which paths stored in a document may be followed (craft-libs). -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } # Who draws the window frame on Linux — the compositor or the app — so every Craft app shows the # same native titlebar per desktop (craft-libs). FigCraft only reads the probe result and maps it # to its own `TitleBar`, so it does not enable craft-window's optional `egui` helpers (which would # pull a second egui family version). -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a49329e71e32ad93794ab595c41f33209a7d2220", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a", features = ["egui"] } # The suite's font store: exact lookup of a missing font in the pinned Google Fonts and Noto # indexes, and checksum-verified installs into the one folder every Craft app reads (craft-libs). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } # Shared dropdown menus: a combo box whose menu grows back after shrinking (craft-libs). -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } # The macOS app menu whose Quit (⌘Q) asks the app before quitting, like the window's close button # (craft-libs; the menu it replaces quits straight through `terminate:` and loses unsaved work). -craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } +craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } # Where the settings live: the suite's folder rules, portable mode included (craft-libs). -craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } +craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } # Penpot export container only; JSON values cross this boundary, not shared model types. -craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } +craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } # The design-file formats (craft-libs): the .fig container and its kiwi encoding, the mapping of # a .fig message onto the REST file JSON, and that JSON's shared helpers. -craft-sketch = { git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } -craft-fig = { git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } -craft-figcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } -craft-figma-rest = { git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220", features = ["frames"] } +craft-sketch = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } +craft-fig = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } +craft-figcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } +craft-figma-rest = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a", features = ["frames"] } # foundation kurbo = { version = "0.13", features = ["serde"] } @@ -200,4 +200,4 @@ winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457 # craft-libs' vendored krilla 0.8.2: decoded PNGs are capped at 1 GiB and reserved fallibly, and a # panic while drawing unwinds without aborting. -krilla = { git = "https://github.com/storytold/craft-libs", rev = "a49329e71e32ad93794ab595c41f33209a7d2220" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } diff --git a/apps/figcraft-web/Cargo.toml b/apps/figcraft-web/Cargo.toml index 4494b005c..45b2c864d 100644 --- a/apps/figcraft-web/Cargo.toml +++ b/apps/figcraft-web/Cargo.toml @@ -21,8 +21,8 @@ figcraft-collab-net = { workspace = true } figcraft-text = { workspace = true } # The host messages (storytold/craft-libs): one contract and one bridge for the web builds. # The page command API (storytold/craft-libs#413): the request plumbing behind window.figcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "ea9407b3500488bd8af71eb0f1b950306315bf7e", version = "0.1.0" } -craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "ea9407b3500488bd8af71eb0f1b950306315bf7e", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a", version = "0.1.0" } +craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a", version = "0.1.0" } base64 = { workspace = true } egui = { workspace = true } log = { workspace = true } From 90d2d92430ad506fcd61cd256ae00f42c56c89a3 Mon Sep 17 00:00:00 2001 From: Utakata <5735026+Utakata@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:34:49 +0900 Subject: [PATCH 34/48] format: open camera raw files as their developed picture RW2, CR2, CR3, NEF, ARW, RAF, ORF, DNG and the other containers craft-raw decodes now open, import, place and fill shapes. add_image develops a raw once with craft-develop's stages (AHD demosaic, highlight rebuild, as-shot white balance and colour matrices, neutral tone curve, sRGB, orientation) and the document keeps the picture as a quality 95 JPEG, so every way an image comes in takes raws. file.open and the Open, Import, Place and image fill dialogs know the raw extensions. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 312 +++++++++++++++++++++- Cargo.toml | 6 + apps/figcraft-cli/src/args.rs | 3 +- crates/engine/Cargo.toml | 2 + crates/engine/src/cmd/file/load.rs | 2 +- crates/engine/src/lib.rs | 2 + crates/engine/src/raw_tests.rs | 138 ++++++++++ crates/format/Cargo.toml | 4 + crates/format/src/lib.rs | 19 +- crates/format/src/raw.rs | 158 +++++++++++ crates/ui-egui/src/app.rs | 2 +- crates/ui-egui/src/app/files.rs | 10 +- crates/ui-egui/src/open.rs | 9 +- crates/ui-egui/src/widgets/colorpicker.rs | 4 +- docs/cli.md | 4 +- docs/file-format-parity.md | 1 + 16 files changed, 661 insertions(+), 15 deletions(-) create mode 100644 crates/engine/src/raw_tests.rs create mode 100644 crates/format/src/raw.rs diff --git a/Cargo.lock b/Cargo.lock index b959ba8be..7f5593a93 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -138,19 +138,34 @@ dependencies = [ "memchr", ] +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + [[package]] name = "alloc-no-stdlib" version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib 2.0.4", +] + [[package]] name = "alloc-stdlib" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" dependencies = [ - "alloc-no-stdlib", + "alloc-no-stdlib 3.0.0", ] [[package]] @@ -632,14 +647,24 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "brotli-decompressor" +version = "5.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +dependencies = [ + "alloc-no-stdlib 2.0.4", + "alloc-stdlib 0.2.4", +] + [[package]] name = "brotli-decompressor" version = "6.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e" dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", ] [[package]] @@ -1061,6 +1086,41 @@ dependencies = [ "rustix 1.1.5", ] +[[package]] +name = "craft-cms" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" +dependencies = [ + "md-5", + "rayon", +] + +[[package]] +name = "craft-color" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" +dependencies = [ + "serde", +] + +[[package]] +name = "craft-color-transform" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" +dependencies = [ + "craft-cms", + "craft-color", + "serde", +] + +[[package]] +name = "craft-crw" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-dds" version = "0.1.0" @@ -1069,6 +1129,33 @@ dependencies = [ "rayon", ] +[[package]] +name = "craft-develop" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" +dependencies = [ + "craft-color", + "craft-color-transform", + "craft-develop-model", + "craft-geom", + "craft-raw", + "rayon", + "serde", + "serde_json", +] + +[[package]] +name = "craft-develop-model" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" +dependencies = [ + "craft-geom", + "craft-metadata", + "miniz_oxide 0.9.1", + "serde", + "serde_json", +] + [[package]] name = "craft-docpath" version = "0.1.0" @@ -1152,6 +1239,14 @@ name = "craft-fonts-build" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" +[[package]] +name = "craft-geom" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" +dependencies = [ + "serde", +] + [[package]] name = "craft-gif" version = "0.1.0" @@ -1252,7 +1347,7 @@ name = "craft-metadata" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" dependencies = [ - "brotli-decompressor", + "brotli-decompressor 6.3.2", "chrono", "craft-tiff", "quick-xml 0.41.0", @@ -1290,6 +1385,24 @@ dependencies = [ "objc2-app-kit 0.3.2", ] +[[package]] +name = "craft-raw" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" +dependencies = [ + "chrono", + "craft-crw", + "craft-metadata", + "craft-tiff", + "jxl-oxide", + "miniz_oxide 0.9.1", + "rayon", + "serde", + "thiserror 2.0.21", + "zune-core", + "zune-jpeg", +] + [[package]] name = "craft-settings" version = "0.1.0" @@ -2179,6 +2292,7 @@ dependencies = [ "craft-docpath", "craft-font-catalog", "craft-font-store", + "craft-raw", "deunicode", "figcraft-collab", "figcraft-color", @@ -2209,12 +2323,16 @@ dependencies = [ name = "figcraft-format" version = "0.18.1" dependencies = [ + "craft-color-transform", + "craft-develop", "craft-fig", "craft-figcraft-format", "craft-figma-rest", + "craft-geom", "craft-image-codecs", "craft-jpeg", "craft-penpot", + "craft-raw", "craft-sketch", "craft-zip", "figcraft-doc", @@ -3475,6 +3593,182 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jxl-bitstream" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b480e752277e29eb4054f69546887a9b84656fe78c08f54ba5850ced98a378fe" +dependencies = [ + "tracing", +] + +[[package]] +name = "jxl-coding" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd972bcd125e776f1eb241ac50e39f956095a1c2770c64736c968f8946bd9a3c" +dependencies = [ + "jxl-bitstream", + "tracing", +] + +[[package]] +name = "jxl-color" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f316b1358c1711755b3ee8e8cb5c4a1dad12e796233088a7a513440782de80b2" +dependencies = [ + "jxl-bitstream", + "jxl-coding", + "jxl-grid", + "jxl-image", + "jxl-oxide-common", + "jxl-threadpool", + "tracing", +] + +[[package]] +name = "jxl-frame" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d967c6fd669c7c01060b5022d8835fa82fd46b06ffc98b549f17600a097c2b3" +dependencies = [ + "jxl-bitstream", + "jxl-coding", + "jxl-grid", + "jxl-image", + "jxl-modular", + "jxl-oxide-common", + "jxl-threadpool", + "jxl-vardct", + "tracing", +] + +[[package]] +name = "jxl-grid" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01671307879a033bfa52e6e8784b941aca770b3f3a7d33830b455b6844f793fb" +dependencies = [ + "tracing", +] + +[[package]] +name = "jxl-image" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5f752d62577c702a94dbbce4045caf08cb58639e8a4d56464b40ecf33ffe565" +dependencies = [ + "jxl-bitstream", + "jxl-grid", + "jxl-oxide-common", + "tracing", +] + +[[package]] +name = "jxl-jbr" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d032bcec660647828527ff42c6f5776d2fd44b8357f9f6d9ac6dc07218e46" +dependencies = [ + "brotli-decompressor 5.0.3", + "jxl-bitstream", + "jxl-frame", + "jxl-grid", + "jxl-image", + "jxl-modular", + "jxl-oxide-common", + "jxl-threadpool", + "jxl-vardct", + "tracing", +] + +[[package]] +name = "jxl-modular" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a2f045b24c738dd91d482be385512b512721ae08a671bd4b27bf1c47f215235" +dependencies = [ + "jxl-bitstream", + "jxl-coding", + "jxl-grid", + "jxl-oxide-common", + "jxl-threadpool", + "tracing", +] + +[[package]] +name = "jxl-oxide" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d36c662923f47586880211f3bc7c0d83fb3a9b410d278c7bde93450748abeef3" +dependencies = [ + "brotli-decompressor 5.0.3", + "jxl-bitstream", + "jxl-color", + "jxl-frame", + "jxl-grid", + "jxl-image", + "jxl-jbr", + "jxl-oxide-common", + "jxl-render", + "jxl-threadpool", + "tracing", +] + +[[package]] +name = "jxl-oxide-common" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b62394c5021b3a9e7e0dbb2d639d555d019090c9946c39f6d3b09d390db4157b" +dependencies = [ + "jxl-bitstream", +] + +[[package]] +name = "jxl-render" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d34386bfdb6a19b5a30cc9beb4d475d537422c31ae8c39bb69640fcce3fcaf19" +dependencies = [ + "bytemuck", + "jxl-bitstream", + "jxl-coding", + "jxl-color", + "jxl-frame", + "jxl-grid", + "jxl-image", + "jxl-modular", + "jxl-oxide-common", + "jxl-threadpool", + "jxl-vardct", + "tracing", +] + +[[package]] +name = "jxl-threadpool" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25f15eb830aa77a7f21148d72e153562a26bfe570139bd4922eab1908dd499d3" +dependencies = [ + "tracing", +] + +[[package]] +name = "jxl-vardct" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce72a18c6d3a47172ab6c479be2bdb56f22066b5d7092663f03b4490820b4511" +dependencies = [ + "jxl-bitstream", + "jxl-coding", + "jxl-grid", + "jxl-modular", + "jxl-oxide-common", + "jxl-threadpool", + "tracing", +] + [[package]] name = "keyboard-types" version = "0.8.3" @@ -3668,6 +3962,16 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4" +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest 0.10.7", +] + [[package]] name = "memchr" version = "2.8.3" diff --git a/Cargo.toml b/Cargo.toml index 0c65f864e..d382f76a4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -71,6 +71,12 @@ craft-figcraft-format = { git = "https://github.com/storytold/craft-libs", rev = craft-figma-rest = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } +# Camera raw files (craft-libs): the container decoders, and the shared develop stages that turn +# sensor data into a picture (demosaic, white balance, colour matrices, tone). +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } +craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } +craft-color-transform = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } +craft-geom = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a", features = ["frames"] } # foundation diff --git a/apps/figcraft-cli/src/args.rs b/apps/figcraft-cli/src/args.rs index b8372ece4..5b2a2de55 100644 --- a/apps/figcraft-cli/src/args.rs +++ b/apps/figcraft-cli/src/args.rs @@ -14,7 +14,8 @@ use figcraft_doc::{PrintSettings, VdCompat}; /// /// Files: .figcraft (native), .penpot (Penpot 2.x), .json (FigCraft or REST API file JSON), .fig /// (best effort; `info` lists what wasn't imported), .sketch (Sketch 48 or newer, best effort), -/// .svg, .png/.jpg/.webp/.gif/.bmp (open as an image layer). +/// .svg, .png/.jpg/.webp/.gif/.bmp (open as an image layer), camera raw files such as .rw2, .cr2, +/// .cr3, .nef, .arw, .raf, .orf and .dng (developed as shot into an image layer). #[derive(Parser)] #[command(name = "figcraft-cli", bin_name = "figcraft-cli", version, arg_required_else_help = true, after_help = "See docs/cli.md and docs/mcp.md.")] pub struct Cli { diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 11fb7f2fa..f587f4138 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -43,3 +43,5 @@ craft-font-catalog = { workspace = true } zip = { workspace = true } wat = { workspace = true } image = { workspace = true } +# Writes the DNG files the camera raw tests open. +craft-raw = { workspace = true } diff --git a/crates/engine/src/cmd/file/load.rs b/crates/engine/src/cmd/file/load.rs index d204931ac..74f02cf79 100644 --- a/crates/engine/src/cmd/file/load.rs +++ b/crates/engine/src/cmd/file/load.rs @@ -124,7 +124,7 @@ fn load_any( font_notes.append(&mut notes); // Show missing-font details first in the UI toast. Ok((figcraft_format::Loaded { issues: font_notes, ..doc.into() }, true)) } - "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "tif" | "tiff" => { + e if matches!(e, "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "tif" | "tiff") || figcraft_format::raw::is_extension(e) => { let mut doc = Document::new(file_stem(name_hint)); let page = doc.first_page().ok_or(EngineError::NoDocument)?; let (hash, w, h) = crate::cmd::create::add_readable_image(&mut doc, bytes.to_vec()).map_err(EngineError::Other)?; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ad6bb085e..8cfc49c26 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -543,6 +543,8 @@ mod proto_run_tests; #[cfg(test)] mod proto_tail_tests; #[cfg(test)] +mod raw_tests; +#[cfg(test)] mod rest_slot_tests; #[cfg(test)] mod retained_walk_tests; diff --git a/crates/engine/src/raw_tests.rs b/crates/engine/src/raw_tests.rs new file mode 100644 index 000000000..06fb2697a --- /dev/null +++ b/crates/engine/src/raw_tests.rs @@ -0,0 +1,138 @@ +//! Camera raw files open, import and place as the picture they develop to; damaged ones are +//! errors. The raw files are DNGs written here from synthetic sensor data (craft-raw's writer). + +use base64::Engine as _; +use craft_raw::opcodes::OpcodeLists; +use craft_raw::{BlackLevel, Cfa, ColorData, DngCompression, DngWriteOptions, Orientation, RawData, RawFormat, RawImage, Rect}; +use serde_json::json; + +use crate::Session; + +/// Sensor columns a band of the scene covers. +const BAND: usize = 22; +const BLACK: f32 = 64.0; +const WHITE: f32 = 4095.0; +/// The camera's response to a neutral (`AsShotNeutral`): white balance multiplies red by 2 and blue by 1/0.7. +const NEUTRAL: [f64; 3] = [0.5, 1.0, 0.7]; + +/// A 3 × 22 by 48 RGGB raw, turned a quarter (Exif orientation 6), whose camera RGB is linear sRGB. +/// Its sensor columns hold three bands: a red, a mid grey, and a light that clips every channel. +fn dng() -> Vec { + let (w, h) = (3 * BAND, 48); + let cfa = Cfa::bayer("RGGB").unwrap(); + let scene = |x: usize| match x / BAND { + 0 => [0.40, 0.08, 0.06], + 1 => [0.18, 0.18, 0.18], + _ => [4.0, 4.0, 4.0], + }; + let data = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let c = cfa.color_at(x, y) as usize; + let level = (scene(x)[c] * NEUTRAL[c] as f32).clamp(0.0, 1.0); + (BLACK + (WHITE - BLACK) * level).round() as u16 + }) + .collect(); + // XYZ (D65) → linear sRGB (IEC 61966-2-1): this camera sees in sRGB primaries. + let xyz_to_camera = [[3.2404542, -1.5371385, -0.4985314], [-0.9692660, 1.8760108, 0.0415560], [0.0556434, -0.2040259, 1.0572252]]; + let raw = RawImage { + format: RawFormat::Dng, + width: w, + height: h, + cpp: 1, + data: RawData::U16(data), + cfa: Some(cfa), + bits: 12, + black: BlackLevel::uniform(BLACK), + white: vec![WHITE], + active_area: Rect::new(0, 0, w, h), + crop: Rect::new(0, 0, w, h), + orientation: Orientation::Rotate90, + color: ColorData { illuminant: [21, 0], color_matrix: [Some(xyz_to_camera), None], as_shot_neutral: Some(NEUTRAL), ..Default::default() }, + wb_multipliers: None, + linearized: true, + linearization_table: None, + pixel_aspect: 1.0, + opcodes: OpcodeLists::default(), + camera: Default::default(), + cinema: Default::default(), + lens_metadata: Default::default(), + level_sources: Default::default(), + notices: Default::default(), + }; + let opts = DngWriteOptions { compression: DngCompression::Uncompressed, software: "figcraft tests".into(), ..Default::default() }; + craft_raw::write_dng(&raw, &opts).unwrap() +} + +fn import(s: &mut Session, bytes: &[u8], name: &str) -> crate::Result { + let b64 = base64::engine::general_purpose::STANDARD.encode(bytes); + s.execute("file.import", &json!({"data": b64, "name": name, "x": 0, "y": 0})) +} + +/// The mean colour of the 5 × 5 pixels around (`x`, `y`) of the layer's image. +fn colour_at(s: &Session, id: figcraft_doc::NodeId, x: u32, y: u32) -> [i32; 3] { + let doc = s.doc().unwrap(); + let hash = match &doc.node(id).unwrap().fills[0].kind { + figcraft_color::PaintKind::Image(paint) => paint.image.clone(), + other => panic!("not an image fill: {other:?}"), + }; + let picture = image::load_from_memory(&doc.images[&hash].bytes).unwrap().to_rgb8(); + let mut sum = [0i32; 3]; + for dy in 0..5 { + for dx in 0..5 { + let p = picture.get_pixel(x + dx - 2, y + dy - 2); + for c in 0..3 { + sum[c] += i32::from(p[c]); + } + } + } + sum.map(|v| v / 25) +} + +fn spread(c: [i32; 3]) -> i32 { + c.iter().max().unwrap() - c.iter().min().unwrap() +} + +#[test] +fn camera_raw_files_import_and_open_as_their_developed_picture() { + let bytes = dng(); + let mut s = Session::new(); + let out = import(&mut s, &bytes, "shot.dng").unwrap(); + let id = crate::params::id_of(&out["id"]).unwrap(); + let n = s.doc().unwrap().node(id).unwrap(); + // The orientation tag is applied: the sensor's columns run down the picture. + assert!(n.height > n.width, "{} x {}", n.width, n.height); + let x = n.width as u32 / 2; + let band = BAND as u32; + let (red, grey, light) = (colour_at(&s, id, x, band / 2), colour_at(&s, id, x, band * 3 / 2), colour_at(&s, id, x, band * 5 / 2)); + // White balance and the colour matrix give back the scene: red stays red, grey stays neutral. + assert!(red[0] > red[1] + 60 && red[0] > red[2] + 60, "red band: {red:?}"); + assert!(spread(grey) <= 8, "grey band: {grey:?}"); + // Clipped channels are rebuilt: white balance alone would turn the clipped light magenta. + assert!(light.iter().all(|&c| c > grey[1]) && spread(light) <= 8, "clipped band: {light:?}, grey {grey:?}"); + + let path = std::env::temp_dir().join(format!("figcraft-raw-{}.dng", std::process::id())); + std::fs::write(&path, &bytes).unwrap(); + let opened = s.execute("file.open", &json!({"path": path.to_string_lossy()})); + let _ = std::fs::remove_file(&path); + opened.unwrap(); + assert_eq!(s.doc().unwrap().images.len(), 1); +} + +#[test] +fn damaged_camera_raw_files_are_errors() { + let mut s = Session::new(); + // A Panasonic RW2 header over junk: refused, saying why. + let mut junk = b"IIU\0\x08\0\0\0".to_vec(); + junk.extend(std::iter::repeat_n(0x5a, 4096)); + let err = import(&mut s, &junk, "shot.rw2").unwrap_err().to_string(); + assert!(err.contains("camera raw"), "{err}"); + // Cut short anywhere: refused or placed, never a panic, and the renderer copes with what was placed. + let bytes = dng(); + for len in [12, 200, bytes.len() / 3, bytes.len() - 100] { + if let Ok(out) = import(&mut s, &bytes[..len], "shot.dng") { + let id = crate::params::id_of(&out["id"]).unwrap(); + assert!(s.doc().unwrap().node(id).is_some()); + } + } +} diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index 2a0101b04..3d11dd37c 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -28,3 +28,7 @@ craft-figcraft-format = { workspace = true } craft-figma-rest = { workspace = true } craft-jpeg = { workspace = true } craft-image-codecs = { workspace = true } +craft-raw = { workspace = true } +craft-develop = { workspace = true } +craft-color-transform = { workspace = true } +craft-geom = { workspace = true } diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 58353e67b..3ec35d42e 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -21,6 +21,7 @@ pub mod fig; pub mod jpeg; pub mod library; pub mod penpot; +pub mod raw; pub mod rest; pub mod sketch; pub mod thumbnail; @@ -174,14 +175,30 @@ fn stored_dimensions(bytes: &[u8]) -> Result<(u32, u32), craft_image_codecs::Cod } } -/// Register encoded image bytes with the document; returns the hash and pixel size. +/// Register encoded image bytes with the document; returns the hash and pixel size. A camera raw +/// file is developed first and the document keeps the developed picture (see [`raw`]). pub fn add_image(doc: &mut Document, bytes: Vec) -> Result<(String, u32, u32), FormatError> { + let bytes = developed_if_raw(bytes)?; let (w, h) = stored_dimensions(&bytes).map_err(|e| FormatError::Corrupt(format!("unsupported image: {e}")))?; let hash = image_hash(&bytes); doc.images.insert(hash.clone(), ImageData { bytes: Arc::new(bytes), width: w, height: h }); Ok((hash, w, h)) } +/// `bytes`, or the picture developed from them when they are a camera raw file. Camera makers +/// write raw files in TIFF containers, so a TIFF the raw reader claims but can't develop stays the +/// TIFF it is when it reads as one. +fn developed_if_raw(bytes: Vec) -> Result, FormatError> { + if !raw::is_camera_raw(&bytes) { + return Ok(bytes); + } + match raw::develop(&bytes) { + Ok(developed) => Ok(developed.bytes), + Err(_) if stored_dimensions(&bytes).is_ok() => Ok(bytes), + Err(e) => Err(e), + } +} + /// Image bytes with their pixel size (0×0 when they can't be decoded). pub(crate) fn image_data(data: Vec) -> ImageData { let (w, h) = stored_dimensions(&data).unwrap_or((0, 0)); diff --git a/crates/format/src/raw.rs b/crates/format/src/raw.rs new file mode 100644 index 000000000..80e20e370 --- /dev/null +++ b/crates/format/src/raw.rs @@ -0,0 +1,158 @@ +//! Camera raw files (Panasonic RW2, Canon CR2 / CR3, Nikon NEF, Sony ARW, Fujifilm RAF, Olympus +//! ORF, DNG and the other containers [`craft_raw`] decodes) as images. +//! +//! A raw file holds sensor samples, not a picture, so it is developed once, when it enters a +//! document, and the document keeps the result: a JPEG at quality 95 with full chroma resolution, +//! untagged and so read as sRGB. Drawing, export, collaboration and the browser build then see an +//! ordinary image; the raw file itself is not stored. (A PNG of the same picture is several times +//! larger, and every collaborator downloads the document's images.) +//! +//! The development is the camera's as-shot rendering at neutral settings, made of the shared +//! stages in `craft-develop`: +//! +//! 1. [`craft_raw::decode_with`]: black and white levels, the active area and default crop, the +//! file's own corrections as DNG opcodes (defect pixels, the in-camera distortion correction of +//! RW2 and NEF files). +//! 2. The demosaic (AHD) of the white-balanced mosaic, cropped and with the pixel aspect applied +//! ([`RawDevelopExt::develop_balanced_masked`]). +//! 3. Clipped highlights rebuilt from the channels that did not clip ([`highlight`]). +//! 4. The as-shot white balance and the camera's colour matrices to linear ITU-R BT.2020 (the DNG +//! colour model, DNG 1.7.1 chapter 6), raised by the file's baseline exposure. +//! 5. The generic tone curve on luminance ([`ToneMap::rolloff_hdr`] at neutral settings). +//! 6. BT.2020 to BT.709 primaries, colours outside them desaturated toward their luminance +//! ([`gamut_map`]), the sRGB transfer function (IEC 61966-2-1) and the file's orientation. +//! +//! Not applied: the look tables and tone curve of a camera profile that some DNGs carry, lens +//! corrections a file only records as metadata, noise reduction and sharpening. + +use craft_color_transform::{Mat3, REC2020, SRGB}; +use craft_develop::finish::gamut_map; +use craft_develop::raster::{Image, par_rows}; +use craft_develop::sensor::{Method, RawDevelopExt, color, highlight}; +use craft_develop::tone::ToneMap; + +use crate::FormatError; + +/// A normalised sensor sample (1 = the white level) at or above this counts as clipped. +const CLIP: f32 = 0.99; + +/// The most samples a raw file may declare: the pixels of the largest image the renderer decodes +/// (512 MiB of RGBA), so a raw that develops is also one the canvas can draw. +const MAX_SAMPLES: usize = 1 << 27; + +/// JPEG quality of the developed picture. +const QUALITY: u8 = 95; + +/// Luminance weights of the BT.2020 primaries (ITU-R BT.2020, table 4). +const LUMA_2020: [f32; 3] = [0.2627, 0.6780, 0.0593]; + +/// Luminance weights of the BT.709 primaries (ITU-R BT.709, item 3.2). +const LUMA_709: [f32; 3] = [0.2126, 0.7152, 0.0722]; + +/// The file extensions of the raw containers [`craft_raw`] decodes, lower case. Opening goes by the +/// extension; whether the bytes are a raw file is still [`is_camera_raw`]'s to say. +pub const EXTENSIONS: [&str; 21] = [ + "3fr", "arw", "cr2", "cr3", "crw", "dng", "erf", "fff", "mef", "mrw", "nef", "nrw", "orf", "pef", "raf", "raw", "rw2", "rwl", "sr2", "srf", "srw", +]; + +/// Whether `ext` (any case, without the dot) is one of [`EXTENSIONS`]. +pub fn is_extension(ext: &str) -> bool { + EXTENSIONS.iter().any(|e| e.eq_ignore_ascii_case(ext)) +} + +/// Whether `bytes` are a camera raw file (decodable in this build or not). +pub fn is_camera_raw(bytes: &[u8]) -> bool { + craft_raw::probe(bytes).is_some() +} + +/// A camera raw file developed into an image. +#[derive(Clone, Debug)] +pub struct Developed { + /// The picture, encoded. + pub bytes: Vec, + pub width: u32, + pub height: u32, +} + +/// Develop the camera raw file `bytes` (see the module docs). An error names what stopped it: not +/// a raw file, a raw variant this build doesn't decode, or damaged data. +pub fn develop(bytes: &[u8]) -> Result { + let format = craft_raw::probe(bytes).ok_or_else(|| raw_error("not a camera raw file"))?; + if !format.is_supported() { + return Err(raw_error(format!("{format:?} files can't be read"))); + } + let mut limits = craft_raw::Limits::default(); + limits.max_samples = MAX_SAMPLES; + let raw = craft_raw::decode_with(bytes, &limits).map_err(|e| raw_error(e.to_string()))?; + + let white = color::as_shot_white_xy(&raw); + let transform = color::camera_transform(&raw, white); + let wb = transform.wb; + let (mut picture, clipped) = raw.develop_balanced_masked(Method::Ahd, wb, CLIP).map_err(|e| raw_error(e.to_string()))?; + match clipped { + Some(mask) => highlight::reconstruct_masked(&mut picture, wb, CLIP, [1.0; 3], &mask), + None => highlight::reconstruct(&mut picture, wb, CLIP), + }; + + let gain = 2f64.powf(transform.baseline_exposure); + let gain = if gain.is_finite() { gain } else { 1.0 }; + // White-balanced camera RGB → scene-linear BT.2020, the baseline exposure included. + let to_2020 = rows(&transform.matrix.mul(&Mat3::diag(f64::from(wb[0]) * gain, f64::from(wb[1]) * gain, f64::from(wb[2]) * gain))); + let to_709 = rows(&SRGB.from_xyz().mul(&REC2020.to_xyz())); + let tone = ToneMap::rolloff_hdr(0.0, 0.0, 0.0, 1.0); + + let (width, height) = (picture.width, picture.height); + let mut rgb: Image<[u8; 3]> = Image::new(width, height); + let source = &picture.data; + par_rows(&mut rgb.data, width, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + let scene = apply(&to_2020, source[y * width + x]); + let luminance = dot(LUMA_2020, scene); + let display = if luminance > 0.0 { scene.map(|c| c * tone.apply(luminance) / luminance) } else { [0.0; 3] }; + let (linear, _) = gamut_map(apply(&to_709, display), LUMA_709); + *out = linear.map(encode_srgb); + } + }); + drop(picture); + let rgb = rgb.into_oriented(craft_geom::Orientation::from_exif(raw.orientation.to_exif())); + let (width, height) = (u32::try_from(rgb.width).map_err(|_| too_large())?, u32::try_from(rgb.height).map_err(|_| too_large())?); + + let image = craft_image_codecs::Image::from_u8(width, height, craft_image_codecs::ChannelLayout::Rgb, rgb.data.into_flattened()) + .map_err(|e| raw_error(e.to_string()))?; + let options = craft_image_codecs::EncodeOptions { + jpeg_quality: QUALITY, + jpeg_chroma_subsampling: false, + embed_icc: false, + embed_metadata: false, + ..Default::default() + }; + let bytes = craft_image_codecs::encode(&image, craft_image_codecs::Format::Jpeg, &options).map_err(|e| raw_error(e.to_string()))?; + Ok(Developed { bytes, width, height }) +} + +fn raw_error(reason: impl std::fmt::Display) -> FormatError { + FormatError::Corrupt(format!("unsupported image: camera raw: {reason}")) +} + +fn too_large() -> FormatError { + raw_error("the picture is too large") +} + +fn rows(m: &Mat3) -> [[f32; 3]; 3] { + m.0.map(|row| row.map(|v| v as f32)) +} + +fn apply(m: &[[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] { + m.map(|row| dot(row, v)) +} + +fn dot(a: [f32; 3], b: [f32; 3]) -> f32 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +/// Linear `v` (0 to 1) as an 8-bit sRGB code (IEC 61966-2-1, the inverse of its equation 1). +fn encode_srgb(v: f32) -> u8 { + let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + let e = if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; + (e * 255.0 + 0.5) as u8 +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 10a82ed5c..71ee8f5f9 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -1,5 +1,5 @@ use super::clock::{AUTO_SAVE_RETRY_SECS, AUTO_SAVE_SECS, AUTOSAVE_SECS, CJK_CHANGES, FrameClock, TOAST_SECS, ToastClock, repaint_in}; -use super::open::OPEN_EXTENSIONS; +use super::open::open_extensions; use super::services::{DialogFuture, PickFuture, Picked, RepaintWaker, Services}; use super::state::{LEFT_PANEL, LeftTab, MOBILE_STRIP, MobilePanel, NARROW_WIDTH, PANEL_DEFAULT, RIGHT_PANEL, RightTab, TitleBar, fit_panels}; use super::{ diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 1ae5e5679..fb7b9539a 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1,6 +1,6 @@ use super::{ - AUTO_SAVE_RETRY_SECS, AUTO_SAVE_SECS, AUTOSAVE_SECS, Arc, DialogFuture, FigApp, OPEN_EXTENSIONS, OsStr, Path, PathBuf, PendingDialog, PickFuture, - Picked, Poll, RepaintWaker, Services, TaskContext, Value, Waker, dialogs, i18n, json, repaint_in, windows, + AUTO_SAVE_RETRY_SECS, AUTO_SAVE_SECS, AUTOSAVE_SECS, Arc, DialogFuture, FigApp, OsStr, Path, PathBuf, PendingDialog, PickFuture, Picked, Poll, + RepaintWaker, Services, TaskContext, Value, Waker, dialogs, i18n, json, repaint_in, windows, }; impl FigApp { @@ -73,7 +73,7 @@ impl FigApp { pub fn open_dialog(&mut self) { // Opening needs no file in front: it goes ahead even if that file closed meanwhile. - self.pick_file(i18n::tr("Open"), OPEN_EXTENSIONS, false, |app, file| { + self.pick_file(i18n::tr("Open"), &super::open_extensions(), false, |app, file| { if app.run_user("file.open", file).is_some() { app.ui.home = false; } @@ -86,8 +86,10 @@ impl FigApp { } else { &["penpot", "svg", "png", "jpg", "jpeg", "webp", "gif", "tif", "tiff", "figcraft", "fig", "jam", "sketch"] }; + // Camera raw files place as the image they develop to. + let exts: Vec<&str> = exts.iter().chain(figcraft_format::raw::EXTENSIONS.iter()).copied().collect(); let title = if place { i18n::tr("Place image") } else { i18n::tr("Import") }; - self.pick_file(title, exts, true, |app, file| { + self.pick_file(title, &exts, true, |app, file| { app.run_user("file.import", file); }); } diff --git a/crates/ui-egui/src/open.rs b/crates/ui-egui/src/open.rs index b9ffb7c2c..ca63910f9 100644 --- a/crates/ui-egui/src/open.rs +++ b/crates/ui-egui/src/open.rs @@ -7,9 +7,16 @@ use super::{OsStr, Path, theme}; pub(crate) const OPEN_EXTENSIONS: &[&str] = &["figcraft", "fig", "jam", "penpot", "sketch", "json", "svg", "png", "jpg", "jpeg", "webp", "gif", "tif", "tiff"]; +/// [`OPEN_EXTENSIONS`] and the camera raw files, which open as an image too: what File ▸ Open offers. +pub(crate) fn open_extensions() -> Vec<&'static str> { + OPEN_EXTENSIONS.iter().chain(figcraft_format::raw::EXTENSIONS.iter()).copied().collect() +} + /// Whether `path` names a file type that opens as a document (the extension, in any case). pub(crate) fn opens(path: &Path) -> bool { - path.extension().and_then(OsStr::to_str).is_some_and(|e| OPEN_EXTENSIONS.iter().any(|x| x.eq_ignore_ascii_case(e))) + path.extension() + .and_then(OsStr::to_str) + .is_some_and(|e| OPEN_EXTENSIONS.iter().any(|x| x.eq_ignore_ascii_case(e)) || figcraft_format::raw::is_extension(e)) } /// Whether `path` is a whole document (`.figcraft`, `.fig`, `.jam`, `.penpot`, `.sketch`, file JSON) rather than an image or SVG: diff --git a/crates/ui-egui/src/widgets/colorpicker.rs b/crates/ui-egui/src/widgets/colorpicker.rs index 662e4ba24..e4f7d73d2 100644 --- a/crates/ui-egui/src/widgets/colorpicker.rs +++ b/crates/ui-egui/src/widgets/colorpicker.rs @@ -628,7 +628,9 @@ fn picked_bytes(file: &serde_json::Value) -> Option> { /// Ask for an image file for `target`: layers' paints keep their fill mode, crop and position. fn upload_image(app: &mut FigApp, target: &PickerTarget) { let target = target.clone(); - app.pick_file(tr("Choose image"), &IMAGE_FILES, true, move |app, file| { + // Camera raw files fill as the image they develop to. + let files: Vec<&str> = IMAGE_FILES.iter().chain(figcraft_format::raw::EXTENSIONS.iter()).copied().collect(); + app.pick_file(tr("Choose image"), &files, true, move |app, file| { if let PickerTarget::Paint { fills, index, ids } = &target && !region_backed(app, &target) { diff --git a/docs/cli.md b/docs/cli.md index 07b19e58b..156feee32 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -171,7 +171,9 @@ figcraft-cli export app.figcraft -o handoff.fig By extension. Inputs: `.figcraft`, `.json` (FigCraft or REST API file JSON), `.fig` (best effort), `.sketch` (Sketch 48 or newer, best effort), `.svg` (an editable frame: groups, shapes, text, gradients, masks and effects; `info` lists what it left out as `note:` lines), `.png/.jpg/.webp/.gif/.tif/.bmp` -(an image layer). Outputs: `.figcraft`, `.json` (FigCraft JSON, pretty-printed), `.svg`, +(an image layer), camera raw files (`.rw2`, `.cr2`, `.cr3`, `.nef`, `.arw`, `.raf`, `.orf`, `.dng` and the other +containers craft-raw reads: an image layer of the picture developed with the camera's as-shot white balance and a +neutral tone curve; the document keeps that picture, not the raw file). Outputs: `.figcraft`, `.json` (FigCraft JSON, pretty-printed), `.svg`, `.png/.jpg/.webp` (the current page rendered at 1x with its background), `.pdf` (the current page's frames, one page each), `.fig` (the whole file, experimental, as `export --format fig`), `.penpot` (the whole file as a Penpot 2.x archive, as `export --format penpot`). diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 8eac69eee..b22d6313a 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -37,6 +37,7 @@ and prototype interactions are still unchecked there. | HEIC | yes | **no** | shortcut: no Rust decoder; the usable ones (libheif, libde265) are C libraries, and HEVC carries patents. Revisit when a Rust decoder exists | 2–3 | | TIFF | Safari only | **yes** | open, import, place, drop (the `image` crate's TIFF decoder; its embedded ICC profile is honoured); SVG exports embed it (and BMP) as PNG, which SVG viewers show | — | | BMP | — | yes | | — | +| Camera raw (RW2, CR2, CR3, NEF, ARW, RAF, ORF, DNG and the other containers craft-raw reads) | no | **yes**, developed | open, import, place, drop, image fills: the raw is developed once as it comes in (craft-raw decode; craft-develop demosaic, as-shot white balance, colour matrices, highlight rebuild and neutral tone curve) and the document keeps the picture as a JPEG at quality 95 with full chroma, not the raw file; a raw variant craft-raw doesn't decode is refused with its reason. Not applied: DNG camera-profile looks, lens corrections kept only as metadata, noise reduction, sharpening | — | | MP4, MOV, WebM (video fills, paid plans) | yes | **no** | shortcut: decoding H.264/HEVC/VP9 needs non-Rust libraries (FFmpeg or each platform's media framework); presenter playback would reuse the animated GIF clock | 4–8 | | Images over 4096 px | downscaled to 4096 | kept | | — | | Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` | From b69121232d03065ad4001879fbd2d1e67d1b9929 Mon Sep 17 00:00:00 2001 From: B-uchi Date: Fri, 27 Nov 2026 10:33:25 +0100 Subject: [PATCH 35/48] M8: the Screen sizes section keeps a typed rule and its group field per document The section kept its rule draft under the same id as the text field's editing state, which the field removes when it loses focus, returning nothing because the text equals the value it was given: a rule typed and then left by clicking anywhere but Add rule was gone. The draft and the editor now have ids of their own; the draft is updated when the field commits, and Add rule uses what the field holds while it has focus. The group field's id held only the layer id, which repeats across open documents, so an unfinished edit could land on another document's layer. It now includes the document, as the rule draft does. --- crates/ui-egui/src/dev_mode_tests.rs | 29 +++++++++++++++++++++++++++ crates/ui-egui/src/panels/dev_mode.rs | 25 ++++++++++++++++++----- 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dev_mode_tests.rs b/crates/ui-egui/src/dev_mode_tests.rs index 0e8fa2726..bfc5c6ceb 100644 --- a/crates/ui-egui/src/dev_mode_tests.rs +++ b/crates/ui-egui/src/dev_mode_tests.rs @@ -257,3 +257,32 @@ fn a_rule_draft_belongs_to_its_document_and_outlives_a_refusal() { u.run("file.new", json!({})); assert_ne!(crate::dev_mode::rule_draft(&u.app, f), field); } + +#[test] +fn a_typed_rule_stays_when_the_field_loses_focus() { + let mut s = Session::new(); + let f = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 400, "name": "Home"})).unwrap()); + s.execute("select.set", &json!({"ids": [f]})).unwrap(); + let mut u = crate::layers_drag_tests::Ui::new(s); + u.app.ui.right_tab = crate::RightTab::Inspect; + u.ctx.enable_accesskit(); + u.frame(vec![]); + let te = crate::dev_mode::rule_editor(&u.app, f).with("te"); + u.ctx.memory_mut(|m| m.request_focus(te)); + u.frame(vec![]); + u.frame(vec![Event::Text("Cards stack".into())]); + // Click something else in the panel: the field loses focus as it does in use. + let mobile = tree(&mut u).into_iter().find(|n| n.role() == Role::Button && n.label() == Some("Mobile")).expect("the Mobile button"); + click(&mut u, centre(&mobile)); + u.frame(vec![]); + let draft = u.ctx.data(|d| d.get_temp::(crate::dev_mode::rule_draft(&u.app, f))); + assert_eq!(draft.as_deref(), Some("Cards stack")); +} + +#[test] +fn the_group_field_belongs_to_its_document() { + let (mut u, f, _) = setup(); + let here = crate::dev_mode::group_field(&u.app, f); + u.run("file.new", json!({})); + assert_ne!(crate::dev_mode::group_field(&u.app, f), here, "another document's layer with the same id has its own field"); +} diff --git a/crates/ui-egui/src/panels/dev_mode.rs b/crates/ui-egui/src/panels/dev_mode.rs index ea9a27bf4..5a7950fd9 100644 --- a/crates/ui-egui/src/panels/dev_mode.rs +++ b/crates/ui-egui/src/panels/dev_mode.rs @@ -572,19 +572,22 @@ pub fn responsive_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: Nod let group = responsive::group_of(n); row(ui, 32.0, |ui| { let width = ui.available_width() - 2.0 * PAD; - if let Some(v) = widgets::text_field(ui, Id::unique(("responsive_group", id)), group, width, tr("Design it's a version of")) { + if let Some(v) = widgets::text_field(ui, group_field(app, id), group, width, tr("Design it's a version of")) { // Emptied: back to the frame's name. let group = if v.trim().is_empty() { json!(null) } else { json!(v) }; app.run("responsive.set", json!({"id": id, "viewport": current, "group": group})); } }); } - let field = rule_draft(app, id); - let draft = ui.data(|d| d.get_temp::(field)).unwrap_or_default(); + let (field, editor) = (rule_draft(app, id), rule_editor(app, id)); + let mut draft = ui.data(|d| d.get_temp::(field)).unwrap_or_default(); widgets::sublabels(ui, tr("Add a rule"), None); - if let Some(v) = widgets::multiline_field(ui, field, &draft, tr("Sidebar becomes a drawer below 768 px"), 3) { - ui.data_mut(|d| d.insert_temp(field, v)); + if let Some(v) = widgets::multiline_field(ui, editor, &draft, tr("Sidebar becomes a drawer below 768 px"), 3) { + ui.data_mut(|d| d.insert_temp(field, v.clone())); + draft = v; } + // While the field has focus, what it holds is the rule. + let draft = ui.data(|d| d.get_temp::(editor)).unwrap_or(draft); row(ui, 32.0, |ui| { if widgets::button(ui, tr("Add rule"), false, !draft.trim().is_empty()).clicked() { add_rule(app, ui.ctx(), id, &draft); @@ -593,6 +596,18 @@ pub fn responsive_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: Nod widgets::note(ui, tr("Rules appear under Annotations, in the Responsive category."), t.text_secondary); } +/// The Screen sizes section's field for the design layer `id` is a version of. +pub(crate) fn group_field(app: &FigApp, id: NodeId) -> Id { + // Layer ids repeat across open documents. + Id::unique(("responsive_group", app.session.ds().ok().map(|d| d.uid), id)) +} + +/// The rule field's own editing state for layer `id`. +pub(crate) fn rule_editor(app: &FigApp, id: NodeId) -> Id { + // Apart from the draft: the field drops its editing state when it loses focus. + rule_draft(app, id).with("editor") +} + /// Where the Screen sizes section keeps the rule being typed for layer `id`. pub(crate) fn rule_draft(app: &FigApp, id: NodeId) -> Id { // Layer ids repeat across open documents. From ce5b5f686f4aded993cf313eca5da4b836e305c4 Mon Sep 17 00:00:00 2001 From: B-uchi Date: Fri, 27 Nov 2026 14:05:52 +0100 Subject: [PATCH 36/48] M8: Add rule sends only what the rule field shows Add rule used the rule editor's stored text whenever there was some. When the Screen sizes section went away while the field had focus (the selection changed), that text stayed stored but nothing committed it, so when the section came back the field showed the empty draft while Add rule would send the hidden text. It now reads the editor's text only while the field has focus. --- crates/ui-egui/src/dev_mode_tests.rs | 38 +++++++++++++++++++++++++++ crates/ui-egui/src/panels/dev_mode.rs | 6 +++-- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dev_mode_tests.rs b/crates/ui-egui/src/dev_mode_tests.rs index bfc5c6ceb..f02584578 100644 --- a/crates/ui-egui/src/dev_mode_tests.rs +++ b/crates/ui-egui/src/dev_mode_tests.rs @@ -286,3 +286,41 @@ fn the_group_field_belongs_to_its_document() { u.run("file.new", json!({})); assert_ne!(crate::dev_mode::group_field(&u.app, f), here, "another document's layer with the same id has its own field"); } + +/// `n` frames with no input. +fn idle(u: &mut crate::layers_drag_tests::Ui, n: usize) { + for _ in 0..n { + u.frame(vec![]); + } +} + +/// A frame named `name`, marked desktop and selected, with the Inspect tab drawn. +fn marked_frame(u: &mut crate::layers_drag_tests::Ui, name: &str) -> NodeId { + let f = id(&u.app.run("frame.create", json!({"x": 0, "y": 0, "width": 300, "height": 400, "name": name})).unwrap()); + u.app.run("responsive.set", json!({"ids": [f], "viewport": "desktop"})); + u.app.run("select.set", json!({"ids": [f]})); + idle(u, 3); + f +} + +#[test] +fn a_rule_left_typed_when_the_section_hid_isnt_added_unseen() { + let mut u = crate::layers_drag_tests::Ui::new(Session::new()); + u.app.ui.right_tab = crate::RightTab::Inspect; + u.ctx.enable_accesskit(); + let f = marked_frame(&mut u, "Home"); + let te = crate::dev_mode::rule_editor(&u.app, f).with("te"); + u.ctx.memory_mut(|m| m.request_focus(te)); + u.frame(vec![]); + u.frame(vec![Event::Text("Stale".into())]); + // The section goes while the field has focus, then comes back. + u.app.run("select.set", json!({"ids": []})); + idle(&mut u, 3); + u.app.run("select.set", json!({"ids": [f]})); + idle(&mut u, 3); + let add = tree(&mut u).into_iter().find(|n| n.role() == Role::Button && n.label() == Some("Add rule")).expect("Add rule"); + click(&mut u, centre(&add)); + idle(&mut u, 2); + let rules = u.app.session.doc().unwrap().node(f).unwrap().annotations.len(); + assert_eq!(rules, 0, "nothing the field doesn't show is added"); +} diff --git a/crates/ui-egui/src/panels/dev_mode.rs b/crates/ui-egui/src/panels/dev_mode.rs index 5a7950fd9..f35c0d299 100644 --- a/crates/ui-egui/src/panels/dev_mode.rs +++ b/crates/ui-egui/src/panels/dev_mode.rs @@ -586,8 +586,10 @@ pub fn responsive_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: Nod ui.data_mut(|d| d.insert_temp(field, v.clone())); draft = v; } - // While the field has focus, what it holds is the rule. - let draft = ui.data(|d| d.get_temp::(editor)).unwrap_or(draft); + // While the field has focus, what it holds is the rule. Only then: text it kept when the + // section went away mid-edit isn't shown, so it mustn't be what Add rule sends. + let focused = ui.memory(|m| m.has_focus(editor.with("te"))); + let draft = if focused { ui.data(|d| d.get_temp::(editor)).unwrap_or(draft) } else { draft }; row(ui, 32.0, |ui| { if widgets::button(ui, tr("Add rule"), false, !draft.trim().is_empty()).clicked() { add_rule(app, ui.ctx(), id, &draft); From 44f88c54f91604d85e82bb334b52924ccdb62d60 Mon Sep 17 00:00:00 2001 From: B-uchi Date: Fri, 27 Nov 2026 14:06:04 +0100 Subject: [PATCH 37/48] M8: the group field's per-document test checks what lands in the document `the_group_field_belongs_to_its_document` compared the field ids, which only shows the wiring. `an_unfinished_group_edit_stays_with_its_document` leaves an edit unfinished in one document, opens another with a layer of the same id, presses Enter there and checks the edit didn't land on it; with the old id it does. --- crates/ui-egui/src/dev_mode_tests.rs | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dev_mode_tests.rs b/crates/ui-egui/src/dev_mode_tests.rs index f02584578..de397ca2a 100644 --- a/crates/ui-egui/src/dev_mode_tests.rs +++ b/crates/ui-egui/src/dev_mode_tests.rs @@ -279,14 +279,6 @@ fn a_typed_rule_stays_when_the_field_loses_focus() { assert_eq!(draft.as_deref(), Some("Cards stack")); } -#[test] -fn the_group_field_belongs_to_its_document() { - let (mut u, f, _) = setup(); - let here = crate::dev_mode::group_field(&u.app, f); - u.run("file.new", json!({})); - assert_ne!(crate::dev_mode::group_field(&u.app, f), here, "another document's layer with the same id has its own field"); -} - /// `n` frames with no input. fn idle(u: &mut crate::layers_drag_tests::Ui, n: usize) { for _ in 0..n { @@ -303,6 +295,26 @@ fn marked_frame(u: &mut crate::layers_drag_tests::Ui, name: &str) -> NodeId { f } +#[test] +fn an_unfinished_group_edit_stays_with_its_document() { + let mut u = crate::layers_drag_tests::Ui::new(Session::new()); + u.app.ui.right_tab = crate::RightTab::Inspect; + u.ctx.enable_accesskit(); + let a = marked_frame(&mut u, "Home"); + let field = tree(&mut u).into_iter().find(|n| n.label() == Some("Design it's a version of")).expect("the group field"); + click(&mut u, centre(&field)); + u.frame(vec![Event::Text("Alpha".into())]); + // Left unfinished: another document opens, with a layer of the same id. + u.app.run("file.new", json!({})); + let b = marked_frame(&mut u, "Pricing"); + assert_eq!(a, b, "the same layer id in both documents"); + let enter = |pressed| Event::Key { key: Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + u.frame(vec![enter(true), enter(false)]); + idle(&mut u, 2); + let group = u.app.session.doc().unwrap().node(b).unwrap().plugin_data.get("figcraft.viewportGroup").cloned(); + assert_ne!(group.as_deref(), Some("Alpha"), "the other document's edit didn't land here"); +} + #[test] fn a_rule_left_typed_when_the_section_hid_isnt_added_unseen() { let mut u = crate::layers_drag_tests::Ui::new(Session::new()); From efb8d7eed2158861df8fd97dcfe51f7e2d8df33f Mon Sep 17 00:00:00 2001 From: B-uchi Date: Fri, 27 Nov 2026 17:48:27 +0100 Subject: [PATCH 38/48] M8: an added rule clears the field even when it keeps focus Add rule cleared the rule's draft but not the field's own editing buffer. An assistive Click activates the button without moving focus, so the focused field reloaded the rule it had just sent and Add rule could send it again. Both are cleared on success; a refused rule keeps both, so nothing typed is lost. Text the field kept when the section went away mid-edit is dropped while the field has no focus, so editing again starts from what the field shows instead of bringing that text back. --- crates/ui-egui/src/dev_mode_tests.rs | 42 +++++++++++++++++++++++++++ crates/ui-egui/src/panels/dev_mode.rs | 20 +++++++++---- 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dev_mode_tests.rs b/crates/ui-egui/src/dev_mode_tests.rs index de397ca2a..b8bdad819 100644 --- a/crates/ui-egui/src/dev_mode_tests.rs +++ b/crates/ui-egui/src/dev_mode_tests.rs @@ -279,6 +279,13 @@ fn a_typed_rule_stays_when_the_field_loses_focus() { assert_eq!(draft.as_deref(), Some("Cards stack")); } +/// The text the field whose editor is `te` shows, as assistive technology reads it. +fn shown(u: &mut crate::layers_drag_tests::Ui, te: egui::Id) -> String { + let nodes = u.frame_output(vec![]).platform_output.accesskit_update.unwrap().nodes; + let field = nodes.into_iter().find(|(at, _)| *at == te.accesskit_id()).expect("the field").1; + field.value().unwrap_or_default().to_string() +} + /// `n` frames with no input. fn idle(u: &mut crate::layers_drag_tests::Ui, n: usize) { for _ in 0..n { @@ -335,4 +342,39 @@ fn a_rule_left_typed_when_the_section_hid_isnt_added_unseen() { idle(&mut u, 2); let rules = u.app.session.doc().unwrap().node(f).unwrap().annotations.len(); assert_eq!(rules, 0, "nothing the field doesn't show is added"); + // Nor does it come back when the field is edited again. + u.ctx.memory_mut(|m| m.request_focus(te)); + idle(&mut u, 2); + assert_eq!(shown(&mut u, te), "", "the field starts from what it showed"); +} + +#[test] +fn a_rule_added_while_its_field_keeps_focus_is_added_once() { + let mut u = crate::layers_drag_tests::Ui::new(Session::new()); + u.app.ui.right_tab = crate::RightTab::Inspect; + u.ctx.enable_accesskit(); + let f = marked_frame(&mut u, "Home"); + let te = crate::dev_mode::rule_editor(&u.app, f).with("te"); + u.ctx.memory_mut(|m| m.request_focus(te)); + u.frame(vec![]); + u.frame(vec![Event::Text("Cards stack".into())]); + // An assistive Click activates the button without taking focus from the field. + let nodes = u.frame_output(vec![]).platform_output.accesskit_update.unwrap().nodes; + let add = nodes.iter().find(|(_, n)| n.role() == Role::Button && n.label() == Some("Add rule")).expect("Add rule").0; + let activate = || { + Event::AccessKitActionRequest(egui::accesskit::ActionRequest { + action: egui::accesskit::Action::Click, + target_tree: egui::accesskit::TreeId::ROOT, + target_node: add, + data: None, + }) + }; + u.frame(vec![activate()]); + idle(&mut u, 2); + assert!(u.ctx.memory(|m| m.has_focus(te)), "the field kept focus"); + assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().annotations.len(), 1); + assert_eq!(shown(&mut u, te), "", "the field clears once the rule is added"); + u.frame(vec![activate()]); + idle(&mut u, 2); + assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().annotations.len(), 1, "a second activation adds nothing"); } diff --git a/crates/ui-egui/src/panels/dev_mode.rs b/crates/ui-egui/src/panels/dev_mode.rs index f35c0d299..dbb6921ce 100644 --- a/crates/ui-egui/src/panels/dev_mode.rs +++ b/crates/ui-egui/src/panels/dev_mode.rs @@ -586,10 +586,16 @@ pub fn responsive_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: Nod ui.data_mut(|d| d.insert_temp(field, v.clone())); draft = v; } - // While the field has focus, what it holds is the rule. Only then: text it kept when the - // section went away mid-edit isn't shown, so it mustn't be what Add rule sends. + // While the field has focus, what it holds is the rule. Without focus, text it kept when the + // section went away mid-edit was never shown: it isn't sent, and it's dropped so the next + // edit starts from the draft the field shows. let focused = ui.memory(|m| m.has_focus(editor.with("te"))); - let draft = if focused { ui.data(|d| d.get_temp::(editor)).unwrap_or(draft) } else { draft }; + let draft = if focused { + ui.data(|d| d.get_temp::(editor)).unwrap_or(draft) + } else { + ui.data_mut(|d| d.remove_temp::(editor)); + draft + }; row(ui, 32.0, |ui| { if widgets::button(ui, tr("Add rule"), false, !draft.trim().is_empty()).clicked() { add_rule(app, ui.ctx(), id, &draft); @@ -618,9 +624,13 @@ pub(crate) fn rule_draft(app: &FigApp, id: NodeId) -> Id { /// Add `text` as a rule on `id`. The draft stays when the rule is refused, so nothing typed is lost. pub(crate) fn add_rule(app: &mut FigApp, ctx: &egui::Context, id: NodeId, text: &str) { - let field = rule_draft(app, id); + let (field, editor) = (rule_draft(app, id), rule_editor(app, id)); if app.run("responsive.rule", json!({"id": id, "text": text})).is_some() { - ctx.data_mut(|d| d.remove_temp::(field)); + // Both: a field that kept focus (an assistive Click doesn't move it) would bring the rule back. + ctx.data_mut(|d| { + d.remove_temp::(field); + d.remove_temp::(editor); + }); } } From 07fea877ef453ff431f3c3bf5e74544e33294e7a Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 07:31:51 +0100 Subject: [PATCH 39/48] Order the connector bar's end menus by where each end lies (#1744) Swapping the two menus fixed a connector drawn right to left but broke one drawn left to right. The menu on the left now belongs to whichever end lies further left on the canvas, and its pictures point left, so both directions match. Adds a test for a connector drawn right to left; the left-to-right test is unchanged. --- crates/ui-egui/src/board_line_tests.rs | 22 ++++++++++++++++++++++ crates/ui-egui/src/canvas/board_bar.rs | 25 +++++++++++++++++++------ 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/board_line_tests.rs b/crates/ui-egui/src/board_line_tests.rs index 4303e7bd8..9b420b6ba 100644 --- a/crates/ui-egui/src/board_line_tests.rs +++ b/crates/ui-egui/src/board_line_tests.rs @@ -85,6 +85,28 @@ fn the_connector_bar_sets_its_ends_dashes_and_weight() { assert_eq!(stroke(&u).weight, 4.0, "the weight is its own step"); } +/// A connector drawn from right to left (#1744): its end point's menu comes first, so the menu on +/// the left sets the end on the left. +#[test] +fn the_left_menu_sets_the_left_end_of_a_connector_drawn_right_to_left() { + let mut s = Session::new(); + s.execute("file.newBoard", &json!({})).unwrap(); + let a = s.execute("board.sticky", &json!({"x": 400, "y": 300})).unwrap()["id"].clone(); + let b = s.execute("board.sticky", &json!({"x": 0, "y": 0})).unwrap()["id"].clone(); + let c = id(&s.execute("board.connector", &json!({"from": a, "to": b, "style": "elbow"})).unwrap()); + let mut u = Ui::new(s); + u.frame(vec![]); + u.frame(vec![]); + let stroke = |u: &Ui| u.app.session.doc().unwrap().node(c).unwrap().stroke.clone(); + // The two menus' places on the bar, named for a connector drawn left to right. + let (left, right) = (START, END); + pick(&mut u, left, "Circle"); + assert_eq!(stroke(&u).cap_end, StrokeCap::CircleFilled, "the left menu is the end's"); + assert_ne!(stroke(&u).cap_start, StrokeCap::CircleFilled); + pick(&mut u, right, "Diamond"); + assert_eq!(stroke(&u).cap_start, StrokeCap::DiamondFilled, "the right menu is the start's"); +} + #[test] fn the_colour_wheel_opens_the_picker_for_connectors_only() { let (mut u, c, b) = connector(); diff --git a/crates/ui-egui/src/canvas/board_bar.rs b/crates/ui-egui/src/canvas/board_bar.rs index 84ebede97..022f3f84c 100644 --- a/crates/ui-egui/src/canvas/board_bar.rs +++ b/crates/ui-egui/src/canvas/board_bar.rs @@ -135,6 +135,9 @@ struct Line { dashed: bool, /// Every selected connector is a mind map's branch: no line types. branch: bool, + /// The first connector's start lies to the right of its end on the canvas, so the bar shows its + /// end point's menu first (#1744). + start_right: bool, ids: Vec, } @@ -171,6 +174,7 @@ fn has(app: &FigApp) -> Option { weight: s.weight, dashed: !s.dashes.is_empty(), branch: true, + start_right: start_right(&ds.doc, c), ids: Vec::new(), }); line.branch &= c.branch; @@ -494,17 +498,26 @@ fn line_part(app: &mut FigApp, ui: &mut Ui, line: &Line, at: Pos2, t: &Tokens) { } x = divider(ui, t, x - 2.0, at.y); } - for (start, cap) in [(true, line.start), (false, line.end)] { - cap_menu(app, ui, t, pos2(x, at.y), start, cap); + // Each end's menu sits on the side where that end lies on the canvas, so the left menu sets + // the left end whichever way the connector was drawn (#1744). + let ends = if line.start_right { [(false, line.end), (true, line.start)] } else { [(true, line.start), (false, line.end)] }; + for (i, (start, cap)) in ends.into_iter().enumerate() { + cap_menu(app, ui, t, pos2(x, at.y), start, cap, i == 0); x += CAP_W + 2.0; } x = divider(ui, t, x - 2.0, at.y); style_menu(app, ui, t, pos2(x, at.y), line); } +/// Whether connector `c`'s start lies to the right of its end on the canvas. +fn start_right(doc: &figcraft_doc::Document, c: &figcraft_doc::Connector) -> bool { + let points = figcraft_engine::board::route(doc, c).unwrap_or_default(); + matches!((points.first(), points.last()), (Some(a), Some(b)) if a.x > b.x) +} + /// The menu of a connector's start (`start`) or end point at `at` (its left edge and middle), -/// showing `cap`. -fn cap_menu(app: &mut FigApp, ui: &mut Ui, t: &Tokens, at: Pos2, start: bool, cap: StrokeCap) { +/// showing `cap`, its pictures pointing left when it is the left one of the two (`left`). +fn cap_menu(app: &mut FigApp, ui: &mut Ui, t: &Tokens, at: Pos2, start: bool, cap: StrokeCap, left: bool) { let r = Rect::from_min_size(pos2(at.x, at.y - CELL / 2.0), vec2(CAP_W, CELL)); let label = if start { tr("Start point") } else { tr("End point") }; let resp = ui.interact(r, ui.scope_id().with(("bb_cap", start)), Sense::click()).on_hover_text(label); @@ -514,12 +527,12 @@ fn cap_menu(app: &mut FigApp, ui: &mut Ui, t: &Tokens, at: Pos2, start: bool, ca } // The picture ends 14 before the rectangle it is given: 4 in from this cell's left edge. let art = Rect::from_min_max(pos2(r.min.x, r.min.y), pos2(r.min.x + 62.0, r.max.y)); - crate::right::cap_art(ui.painter(), art, t.icon, cap, start); + crate::right::cap_art(ui.painter(), art, t.icon, cap, left); icons::paint(ui.painter(), Rect::from_center_size(pos2(r.max.x - 7.0, at.y), vec2(12.0, 12.0)), Icon::Chevron, t.icon_secondary); let key = if start { "startCap" } else { "endCap" }; crate::right::menu_popup(&resp).show(|ui| { for c in StrokeCap::ALL { - let art = |p: &egui::Painter, row: Rect, ink: Color32| crate::right::cap_art(p, row, ink, c, start); + let art = |p: &egui::Painter, row: Rect, ink: Color32| crate::right::cap_art(p, row, ink, c, left); if crate::right::menu_item_with(ui, tr(c.label()), "", crate::right::CAP_ART_W, art) { app.run("board.setStyle", json!({key: c})); ui.close(); From 6e55d5b44973885666b9ab2cf856683f898c70ba Mon Sep 17 00:00:00 2001 From: Bryton Cooper Date: Sat, 28 Nov 2026 00:38:14 -0700 Subject: [PATCH 40/48] fix(collab): align delta encode/decode budgets and charge bound/meta --- crates/collab/src/delta_snapshot/decode.rs | 47 +++++++++++++++--- crates/collab/src/delta_snapshot/encode.rs | 49 ++++++++++++++++-- crates/collab/src/delta_snapshot_tests.rs | 58 ++++++++++++++++++++++ crates/collab/src/server.rs | 15 +++--- 4 files changed, 150 insertions(+), 19 deletions(-) diff --git a/crates/collab/src/delta_snapshot/decode.rs b/crates/collab/src/delta_snapshot/decode.rs index 2579a12dc..fbb716edb 100644 --- a/crates/collab/src/delta_snapshot/decode.rs +++ b/crates/collab/src/delta_snapshot/decode.rs @@ -26,6 +26,12 @@ use crate::replica::{Positions, Replica}; const MAX_AMPLIFICATION_FACTOR: usize = 64; const MIN_MATERIALIZED_FLOOR: usize = 16 << 20; +/// Effective materialized-byte ceiling shared by encoder and decoder. +pub(super) fn materialized_budget(declared: usize, ceiling: usize) -> usize { + let cap = declared.saturating_mul(MAX_AMPLIFICATION_FACTOR).max(MIN_MATERIALIZED_FLOOR); + ceiling.min(cap) +} + /// Decode a compressed `CatchUp::DeltaSnapshot` payload into a validated [`Replica`]. pub fn decode_delta_snapshot(bytes: &[u8], max_bytes: usize, max_nodes: usize) -> Result { decode_delta_snapshot_with_budget(bytes, max_bytes, max_nodes, DEFAULT_MAX_MATERIALIZED_BYTES) @@ -51,15 +57,14 @@ pub fn decode_delta_snapshot_with_budget(bytes: &[u8], max_bytes: usize, max_nod return Err(Error::Decode(format!("delta snapshot truncated: header declared {declared} bytes, inflated {}", raw.len()))); } - let cap = declared.saturating_mul(MAX_AMPLIFICATION_FACTOR).max(MIN_MATERIALIZED_FLOOR); - stream_decode_wire(&raw, max_nodes, max_materialized_bytes.min(cap)) + stream_decode_wire(&raw, max_nodes, materialized_budget(declared, max_materialized_bytes)) } fn est_str_map(m: &BTreeMap) -> usize { m.iter().fold(0usize, |a, (k, v)| a.saturating_add(k.len()).saturating_add(v.len()).saturating_add(48)) } -fn est_vector_bytes(net: &VectorNetwork) -> usize { +pub(super) fn est_vector_bytes(net: &VectorNetwork) -> usize { let regs = net.regions.iter().fold(0usize, |acc, r| { let loops = r.loops.iter().fold(0usize, |a, l| a.saturating_add(l.len().saturating_mul(size_of::()))); let fills = r.fills.as_ref().map_or(0, |f| f.len().saturating_mul(size_of::())); @@ -83,7 +88,7 @@ fn est_kind_bytes(kind: &NodeKind) -> usize { } } -fn est_node_bytes(n: &Node) -> usize { +pub(super) fn est_node_bytes(n: &Node) -> usize { let ov: usize = n.overrides.iter().fold(0, |a, s| a.saturating_add(s.len()).saturating_add(24)); size_of::() .saturating_add(n.name.len()) @@ -101,11 +106,13 @@ fn est_node_bytes(n: &Node) -> usize { .saturating_add(n.measurements.len().saturating_mul(size_of::())) .saturating_add(est_kind_bytes(&n.kind)) .saturating_add(ov) + .saturating_add(est_str_map(&n.bound)) + .saturating_add(est_str_map(&n.var_modes)) .saturating_add(est_str_map(&n.plugin_data)) .saturating_add(est_str_map(&n.prop_refs)) } -fn est_deltas_extra_bytes(deltas: &[FieldDelta], vector_sizes: &[usize]) -> usize { +pub(super) fn est_deltas_extra_bytes(deltas: &[FieldDelta], vector_sizes: &[usize]) -> usize { deltas.iter().fold(0usize, |acc, d| { let extra = match d { FieldDelta::Name(s) | FieldDelta::DevNote(s) => s.len(), @@ -113,7 +120,7 @@ fn est_deltas_extra_bytes(deltas: &[FieldDelta], vector_sizes: &[usize]) -> usiz FieldDelta::VectorRef(idx) => usize::try_from(*idx).ok().and_then(|i| vector_sizes.get(i).copied()).unwrap_or(0), FieldDelta::Fills(v) | FieldDelta::Strokes(v) => v.len().saturating_mul(size_of::()), FieldDelta::Effects(v) => v.len().saturating_mul(size_of::()), - FieldDelta::PluginData(m) | FieldDelta::PropRefs(m) => est_str_map(m), + FieldDelta::Bound(m) | FieldDelta::VarModes(m) | FieldDelta::PluginData(m) | FieldDelta::PropRefs(m) => est_str_map(m), FieldDelta::Annotations(v) => v.len().saturating_mul(size_of::()), _ => 0, }; @@ -121,6 +128,31 @@ fn est_deltas_extra_bytes(deltas: &[FieldDelta], vector_sizes: &[usize]) -> usiz }) } +pub(super) fn est_meta_bytes(meta: &WireMeta) -> usize { + let images = meta.images.iter().fold(0usize, |a, i| a.saturating_add(i.key.len()).saturating_add(i.bytes.len())); + let comments = meta.comments.iter().fold(0usize, |a, c| { + let replies = c.replies.iter().fold(0usize, |r, m| r.saturating_add(m.author.len()).saturating_add(m.text.len()).saturating_add(64)); + a.saturating_add(c.first.author.len()).saturating_add(c.first.text.len()).saturating_add(replies).saturating_add(128) + }); + let styles = meta.styles.iter().fold(0usize, |a, s| a.saturating_add(s.id.len()).saturating_add(s.name.len()).saturating_add(128)); + let dev_snaps = meta.dev_snapshots.values().fold(0usize, |a, s| s.nodes.iter().fold(a, |b, n| b.saturating_add(est_node_bytes(n)))); + let vars = meta.variables.collections.len().saturating_mul(128).saturating_add(meta.variables.variables.len().saturating_mul(128)); + let libs = meta.libraries.components.len().saturating_mul(128).saturating_add(meta.libraries.styles.len().saturating_mul(128)); + let votes = meta.votes.iter().fold(0usize, |a, (k, v)| a.saturating_add(k.len()).saturating_add(v.len().saturating_mul(size_of::()))); + meta.name + .len() + .saturating_add(images) + .saturating_add(comments) + .saturating_add(styles) + .saturating_add(dev_snaps) + .saturating_add(vars) + .saturating_add(libs) + .saturating_add(votes) + .saturating_add(meta.vote_history.len().saturating_mul(128)) + .saturating_add(meta.image_presets.len().saturating_mul(64)) + .saturating_add(meta.document_colors.len().saturating_mul(32)) +} + struct DecodeState { doc: Document, positions: Positions, @@ -296,8 +328,7 @@ impl<'de> Visitor<'de> for DeltaWireSeed<'_> { match key.as_str() { "meta" => { let meta: WireMeta = map.next_value()?; - let img_bytes = meta.images.iter().fold(0usize, |a, i| a.saturating_add(i.bytes.len())); - if let Err(err) = self.0.charge(img_bytes) { + if let Err(err) = self.0.charge(est_meta_bytes(&meta)) { return Err(self.0.fail(err)); } self.0.meta = Some(meta); diff --git a/crates/collab/src/delta_snapshot/encode.rs b/crates/collab/src/delta_snapshot/encode.rs index 474cea954..3b1512080 100644 --- a/crates/collab/src/delta_snapshot/encode.rs +++ b/crates/collab/src/delta_snapshot/encode.rs @@ -6,8 +6,9 @@ use std::io::{BufWriter, Write}; use figcraft_doc::{Document, Node, NodeId, NodeKind, VectorNetwork}; use sha2::{Digest as _, Sha256}; +use super::decode::{est_deltas_extra_bytes, est_meta_bytes, est_node_bytes, est_vector_bytes, materialized_budget}; use super::fields::{diff_mirror_fields, exact_vector_network_eq}; -use super::{DELTA_MAGIC, DELTA_VERSION, DeltaWireRef, MirrorWire, WireImage, WireMeta, WireRecord}; +use super::{DEFAULT_MAX_MATERIALIZED_BYTES, DELTA_MAGIC, DELTA_VERSION, DeltaWireRef, MirrorWire, WireImage, WireMeta, WireRecord}; use crate::Error; use crate::replica::Replica; @@ -102,6 +103,9 @@ fn topo_order(doc: &Document) -> Vec { } /// Encode `replica` as a compressed `CatchUp::DeltaSnapshot` payload. +/// +/// Returns `Error::TooLarge` if the payload would exceed the client decoder's materialized-memory +/// budget, allowing callers such as `Server::join_as` to fall back to `CatchUp::Snapshot`. pub fn encode_delta_snapshot(replica: &Replica) -> Result, Error> { let doc = replica.document(); let order = topo_order(doc); @@ -118,8 +122,42 @@ pub fn encode_delta_snapshot(replica: &Replica) -> Result, Error> { } let meta = build_meta(doc); + let est_materialized = estimate_decode_charge(&meta, &interner.table, &records); let wire = DeltaWireRef { meta: &meta, vectors: &interner.table, records: &records }; - compress_wire(&wire) + let (out, written) = compress_wire(&wire)?; + let budget = materialized_budget(written, DEFAULT_MAX_MATERIALIZED_BYTES); + if est_materialized > budget { + return Err(Error::TooLarge(budget)); + } + Ok(out) +} + +/// Mirror the decoder's materialized-byte accounting so the server never emits a delta snapshot +/// that a compliant client would reject with `Error::TooLarge`. +fn estimate_decode_charge(meta: &WireMeta, vectors: &[VectorNetwork], records: &[WireRecord]) -> usize { + let vector_sizes: Vec = vectors.iter().map(est_vector_bytes).collect(); + let mut total = est_meta_bytes(meta); + for &vs in &vector_sizes { + total = total.saturating_add(vs); + } + let mut node_sizes: HashMap = HashMap::with_capacity(records.len()); + for rec in records { + match rec { + WireRecord::Full { pos, node, vref } => { + let vsize = vref.and_then(|idx| usize::try_from(idx).ok()).and_then(|i| vector_sizes.get(i).copied()).unwrap_or(0); + let est = est_node_bytes(node).saturating_add(pos.len()).saturating_add(vsize); + total = total.saturating_add(est); + node_sizes.insert(node.id, est); + } + WireRecord::Mirror(m) => { + let src_size = node_sizes.get(&m.source).copied().unwrap_or(0); + let est = src_size.saturating_add(est_deltas_extra_bytes(&m.deltas, &vector_sizes)).saturating_add(m.pos.len()); + total = total.saturating_add(est); + node_sizes.insert(m.id, est); + } + } + } + total } fn encode_one_node(node: &Node, pos: String, seen: &HashMap, interner: &mut VectorInterner) -> Result { @@ -202,7 +240,7 @@ impl Write for CountingWriter { } } -fn compress_wire(wire: &DeltaWireRef<'_>) -> Result, Error> { +fn compress_wire(wire: &DeltaWireRef<'_>) -> Result<(Vec, usize), Error> { let mut out = Vec::with_capacity(4096); out.extend_from_slice(DELTA_MAGIC); out.push(DELTA_VERSION); @@ -213,10 +251,11 @@ fn compress_wire(wire: &DeltaWireRef<'_>) -> Result, Error> { let mut buffered = BufWriter::with_capacity(64 * 1024, CountingWriter { inner: encoder, written: 0 }); serde_json::to_writer(&mut buffered, wire).map_err(|e| Error::Encode(e.to_string()))?; let counting = buffered.into_inner().map_err(|e| Error::Encode(e.into_error().to_string()))?; - let len_u32 = u32::try_from(counting.written).map_err(|_| Error::TooLarge(u32::MAX as usize))?; + let written = counting.written; + let len_u32 = u32::try_from(written).map_err(|_| Error::TooLarge(u32::MAX as usize))?; let mut out = counting.inner.finish().map_err(|e| Error::Encode(e.to_string()))?; if let Some(slot) = out.get_mut(5..9) { slot.copy_from_slice(&len_u32.to_le_bytes()); } - Ok(out) + Ok((out, written)) } diff --git a/crates/collab/src/delta_snapshot_tests.rs b/crates/collab/src/delta_snapshot_tests.rs index ff6a369fc..6fdf3f7ea 100644 --- a/crates/collab/src/delta_snapshot_tests.rs +++ b/crates/collab/src/delta_snapshot_tests.rs @@ -348,3 +348,61 @@ fn delta_snapshot_never_panics_when_truncated_or_bit_flipped() { let _ = decode_delta_snapshot(&mutated, 16 << 20, 10_000); } } + +#[test] +fn bound_map_amplification_and_oversized_metadata_are_rejected_by_budget() { + // Source node with a large `bound` map mirrored 1,000 times must trip the memory budget. + let mut bound_entries = Vec::with_capacity(200); + for i in 0..200 { + bound_entries.push(format!(r#""k{i:03}":"{}""#, "v".repeat(512))); + } + let bound_json = bound_entries.join(","); + let mut recs = format!( + r#"{{"meta":{{"name":"BoundBomb"}},"records":[{{"r":"full","pos":"a0","node":{{"id":1,"name":"P","type":"page","width":0,"height":0}}}},{{"r":"full","pos":"a0","node":{{"id":2,"name":"Src","parent":1,"type":"rectangle","width":10,"height":10,"bound":{{{bound_json}}}}}}}"# + ); + for i in 3..1003u64 { + recs.push_str(&format!(r#",{{"r":"mirror","id":{i},"parent":1,"pos":"a{i:04}1","source":2}}"#)); + } + recs.push_str("]}"); + let err = decode_delta_snapshot(&make_raw_delta_payload(&recs, None), 16 << 20, Limits::default().max_nodes).unwrap_err(); + assert!(matches!(err, Error::TooLarge(_)), "bound-map amplification must fail TooLarge, got {err:?}"); + + // Oversized metadata (`name` of 2 MiB) under a 1 MiB materialized budget must fail TooLarge. + let big_meta = format!( + r#"{{"meta":{{"name":"{}"}},"records":[{{"r":"full","pos":"a0","node":{{"id":1,"name":"P","type":"page","width":0,"height":0}}}}]}}"#, + "M".repeat(2 << 20) + ); + let err2 = decode_delta_snapshot_with_budget(&make_raw_delta_payload(&big_meta, None), 16 << 20, 100, 1 << 20).unwrap_err(); + assert!(matches!(err2, Error::TooLarge(_)), "oversized metadata must fail TooLarge, got {err2:?}"); +} + +#[test] +fn server_falls_back_to_legacy_snapshot_when_delta_exceeds_decode_budget() { + // 2,000 mirrors of a 256 KiB text node exceed the client's 64x materialized ceiling: + // the server must fall back to `CatchUp::Snapshot` so capable clients still join cleanly. + let mut doc = Document::new("HighAmplificationHonest"); + let page = doc.first_page().unwrap(); + let src = doc.create(page, NodeKind::Text(TextData::new("T".repeat(256 * 1024))), "Big", 0.0, 0.0, 100.0, 20.0).unwrap(); + let src_snap = doc.node(src).unwrap().clone(); + for _ in 0..2000 { + let mut m = src_snap.clone(); + m.id = doc.alloc_id(); + m.parent = None; + m.source = Some(src); + doc.insert(m, page, None).unwrap(); + } + doc.take_dirty(); + + assert!(matches!(encode_delta_snapshot(&Replica::new(doc.clone())), Err(Error::TooLarge(_)))); + let mut srv = Server::new(doc, "tok", Limits::default()); + let ClientMsg::Hello(h) = Client::hello("f", "tok", "u", "#222") else { panic!() }; + let (id, outs) = srv.join(h).unwrap(); + let welcome = outs + .into_iter() + .find_map(|o| match o { + Outgoing::To(t, m @ ServerMsg::Welcome { .. }) if t == id => Some(m), + _ => None, + }) + .unwrap(); + assert!(matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })); +} diff --git a/crates/collab/src/server.rs b/crates/collab/src/server.rs index 785650625..0f2a648c8 100644 --- a/crates/collab/src/server.rs +++ b/crates/collab/src/server.rs @@ -427,12 +427,15 @@ impl Server { CatchUp::Delta(self.log.iter().filter(|a| a.seq > r.seq).cloned().collect()) } // Only send the cached delta snapshot to peers that also read `design-review`, since - // the compressed payload carries the document's review config without per-peer filtering. - // If delta encoding ever fails, fall back to the legacy snapshot instead of refusing join. - _ if reads_delta && reads_design_review => match self.cached_delta_snapshot() { - Ok(bytes) => CatchUp::DeltaSnapshot(bytes), - Err(_) => CatchUp::Snapshot(self.state.snapshot().map_err(|e| refuse(&e.to_string()))?), - }, + // the compressed payload carries the document's review config without per-peer filtering, + // and only when the document fits within the client decoder's default node cap. + // If delta encoding fails (e.g. materialized budget exceeded), fall back to `Snapshot`. + _ if reads_delta && reads_design_review && self.state.document().node_count() <= Limits::default().max_nodes => { + match self.cached_delta_snapshot() { + Ok(bytes) => CatchUp::DeltaSnapshot(bytes), + Err(_) => CatchUp::Snapshot(self.state.snapshot().map_err(|e| refuse(&e.to_string()))?), + } + } _ => CatchUp::Snapshot(self.state.snapshot().map_err(|e| refuse(&e.to_string()))?), }; // A peer that doesn't read the review settings can't decode them: its catch-up carries From a8653ba1f6469ec539f531ba4f288e709dfb9945 Mon Sep 17 00:00:00 2001 From: Bryton Cooper Date: Sat, 28 Nov 2026 01:04:31 -0700 Subject: [PATCH 41/48] fix(collab): charge annotation_categories and mirror overrides in budget estimate --- crates/collab/src/delta_snapshot/decode.rs | 6 ++++++ crates/collab/src/delta_snapshot/encode.rs | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/collab/src/delta_snapshot/decode.rs b/crates/collab/src/delta_snapshot/decode.rs index fbb716edb..cab21be9e 100644 --- a/crates/collab/src/delta_snapshot/decode.rs +++ b/crates/collab/src/delta_snapshot/decode.rs @@ -139,6 +139,11 @@ pub(super) fn est_meta_bytes(meta: &WireMeta) -> usize { let vars = meta.variables.collections.len().saturating_mul(128).saturating_add(meta.variables.variables.len().saturating_mul(128)); let libs = meta.libraries.components.len().saturating_mul(128).saturating_add(meta.libraries.styles.len().saturating_mul(128)); let votes = meta.votes.iter().fold(0usize, |a, (k, v)| a.saturating_add(k.len()).saturating_add(v.len().saturating_mul(size_of::()))); + let categories = meta + .annotation_categories + .iter() + .flatten() + .fold(0usize, |a, c| a.saturating_add(c.id.len()).saturating_add(c.name.len()).saturating_add(128)); meta.name .len() .saturating_add(images) @@ -148,6 +153,7 @@ pub(super) fn est_meta_bytes(meta: &WireMeta) -> usize { .saturating_add(vars) .saturating_add(libs) .saturating_add(votes) + .saturating_add(categories) .saturating_add(meta.vote_history.len().saturating_mul(128)) .saturating_add(meta.image_presets.len().saturating_mul(64)) .saturating_add(meta.document_colors.len().saturating_mul(32)) diff --git a/crates/collab/src/delta_snapshot/encode.rs b/crates/collab/src/delta_snapshot/encode.rs index 3b1512080..84b2b9e8b 100644 --- a/crates/collab/src/delta_snapshot/encode.rs +++ b/crates/collab/src/delta_snapshot/encode.rs @@ -152,8 +152,9 @@ fn estimate_decode_charge(meta: &WireMeta, vectors: &[VectorNetwork], records: & WireRecord::Mirror(m) => { let src_size = node_sizes.get(&m.source).copied().unwrap_or(0); let est = src_size.saturating_add(est_deltas_extra_bytes(&m.deltas, &vector_sizes)).saturating_add(m.pos.len()); + let overrides = m.overrides.iter().fold(0usize, |a, s| a.saturating_add(s.len()).saturating_add(24)); total = total.saturating_add(est); - node_sizes.insert(m.id, est); + node_sizes.insert(m.id, est.saturating_add(overrides)); } } } From 87fee2835ca970041392c46b46342665fb5f2549 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 13:23:07 +0700 Subject: [PATCH 42/48] M9: Stop sharing works for a file shared with the server key typed under Advanced (#2495) --- crates/engine/src/live_share_tests.rs | 25 +++++++++++++++++++++++++ crates/engine/src/sharing/live/host.rs | 22 +++++++++++++++++++++- crates/engine/src/sharing/live/join.rs | 2 +- docs/collaboration-parity.md | 1 + 4 files changed, 48 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/live_share_tests.rs b/crates/engine/src/live_share_tests.rs index 9581dc3fa..bce853df8 100644 --- a/crates/engine/src/live_share_tests.rs +++ b/crates/engine/src/live_share_tests.rs @@ -311,6 +311,31 @@ fn sharing_online_uses_a_separate_key_param() { assert!(!r.to_string().contains("KeyKey"), "the server's key is nowhere in the summary"); } +#[test] +fn stopping_a_file_shared_with_a_separate_key_asks_with_that_key() { + // A file published with the server key has no owner token (#2495): Stop sharing must go as + // the server's operator, with the key it was published with, not an empty token. The key + // given replaces one the address carries, as it did for the publish. + for (server, asked_with) in [ + ("wss://share.example/", "wss://share.example/?key=Key%26Key%25Key1"), + ("wss://share.example/?key=Old&team=1", "wss://share.example/?team=1&key=Key%26Key%25Key1"), + ] { + let (mut s, script) = session(); + ex(&mut s, "collab.share", json!({"server": server, "key": "Key&Key%Key1"})); + on_the_server(&mut s, &script, Some(("K7M2QX9TD", "4FHJ8R2WN"))); + if let Some(p) = s.live_mut().and_then(|l| l.published.as_mut()) { + p.owner = None; + } + s.prefs.online_files.clear(); + assert_eq!(ex(&mut s, "collab.stop", json!({}))["shared"], false); + let sc = script.lock().unwrap(); + let [(asked, _, owner, revoke, false)] = sc.asked.as_slice() else { panic!("asked {:?}", sc.asked) }; + // The address `collab.share {server: "…?key=…"}` would have given, the key escaped. + assert_eq!(asked, asked_with); + assert!(owner.is_empty() && !revoke.is_empty(), "the others' links go, with no owner token"); + } +} + #[test] fn a_server_without_join_codes_leaves_the_links() { let (mut s, script) = session(); diff --git a/crates/engine/src/sharing/live/host.rs b/crates/engine/src/sharing/live/host.rs index 417667abe..2a3133474 100644 --- a/crates/engine/src/sharing/live/host.rs +++ b/crates/engine/src/sharing/live/host.rs @@ -162,7 +162,13 @@ pub(super) fn share(s: &mut Session, p: &Value) -> Result { if server.is_empty() { return Err(EngineError::Disabled(CMD.into(), ONLINE_OFF.into())); } - start_publish(s, CMD, &server, p, true)? + let id = start_publish(s, CMD, &server, p, true)?; + // A file published with the key has no owner token: stopping and sharing again go as + // the server's operator, with the key in the address as `collab.share {server}` takes it. + if let Some(key) = string(p, "key").map(|k| k.trim().to_string()).filter(|k| !k.is_empty()) { + server = with_key(&server, &key); + } + id } }; if let Some(live) = s.live.sessions.get_mut(&id) { @@ -179,6 +185,20 @@ pub(super) fn share(s: &mut Session, p: &Value) -> Result { Ok(s.live_summary()) } +/// `server` with `key` in its query (`?key=…`), escaped so any key reads back the same. It replaces +/// a key the address carries: the one given is the one the file was published with. +fn with_key(server: &str, key: &str) -> String { + let escaped: String = key + .bytes() + .map(|b| if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) { char::from(b).to_string() } else { format!("%{b:02X}") }) + .collect(); + let (base, query) = server.split_once('?').unwrap_or((server, "")); + let mut pairs: Vec<&str> = query.split('&').filter(|p| !p.is_empty() && p.split('=').next() != Some("key")).collect(); + let key = format!("key={escaped}"); + pairs.push(&key); + format!("{base}?{}", pairs.join("&")) +} + /// A way into a session this app hosts: its invite link and the join code that stands for it /// (none when the link can't be put in one: a host without an IPv4 address). fn local_link(link: &str) -> SharedLink { diff --git a/crates/engine/src/sharing/live/join.rs b/crates/engine/src/sharing/live/join.rs index badc1fd91..008e8991e 100644 --- a/crates/engine/src/sharing/live/join.rs +++ b/crates/engine/src/sharing/live/join.rs @@ -201,7 +201,7 @@ pub fn specs() -> Vec { spec!( "collab.share", "Share with a join code", - "{via?: \"online\" (default: the open file is kept on the server in Preferences, `pref.publishServer`, and the server hands out the codes) | \"local\" (this app hosts it for people on the same network; no server), access?: \"edit\" (default) | \"comment\" (online only: view and comment, not edit) | \"view\" (look only: their edits are refused): which code `code` is, server? (online: another server's address, with ?key=… when it needs its key), key? (online: the server's key, when the address has none), name? (online: the file's name there), port?, bind?: \"lan\" (default) | \"local\" (this machine only) | an IP address (local)} → the open file's session as `collab.peers` gives it: `code` is what others type to join (`collab.join {code}`, the Join field), `link` the invite link to give with it and `url` its WebSocket URL (local: the ones that go with `code`, so a view-only code's link and URL let people look only; online: your own link to the file, which edits: `share` has the link that goes with each code). Local: at once, the code carries the host's IPv4 address, port and secret (K7M2Q-…, 20 symbols), and `share` is {via, access, shared, editCode, viewCode, editLink, viewLink}: the edit and view-only ways in, each with its own secret (commentCode and commentLink null). Online: status \"connecting\" first; once live `code` is the server's (K7M-2QX-9TD) and `share` is {via, access, shared, editCode, viewCode, commentCode, editLink, viewLink, commentLink}: links made for others (commentCode and commentLink null from a server older than comment links) (the file's own links in `published` stay yours); `code` stays null when the server is older than join codes (give `share.editLink` / `share.viewLink` instead). Called again while shared: only switches which code `code` is (`access`). Called after `collab.stop` on a file that is still on the server: new links and codes for that same file (nothing is published twice). `collab.stop` stops sharing", + "{via?: \"online\" (default: the open file is kept on the server in Preferences, `pref.publishServer`, and the server hands out the codes) | \"local\" (this app hosts it for people on the same network; no server), access?: \"edit\" (default) | \"comment\" (online only: view and comment, not edit) | \"view\" (look only: their edits are refused): which code `code` is, server? (online: another server's address, with ?key=… when it needs its key), key? (online: the server's key, when the address has none; Stop sharing and sharing again in this session use it too, since such a file has no owner token), name? (online: the file's name there), port?, bind?: \"lan\" (default) | \"local\" (this machine only) | an IP address (local)} → the open file's session as `collab.peers` gives it: `code` is what others type to join (`collab.join {code}`, the Join field), `link` the invite link to give with it and `url` its WebSocket URL (local: the ones that go with `code`, so a view-only code's link and URL let people look only; online: your own link to the file, which edits: `share` has the link that goes with each code). Local: at once, the code carries the host's IPv4 address, port and secret (K7M2Q-…, 20 symbols), and `share` is {via, access, shared, editCode, viewCode, editLink, viewLink}: the edit and view-only ways in, each with its own secret (commentCode and commentLink null). Online: status \"connecting\" first; once live `code` is the server's (K7M-2QX-9TD) and `share` is {via, access, shared, editCode, viewCode, commentCode, editLink, viewLink, commentLink}: links made for others (commentCode and commentLink null from a server older than comment links) (the file's own links in `published` stay yours); `code` stays null when the server is older than join codes (give `share.editLink` / `share.viewLink` instead). Called again while shared: only switches which code `code` is (`access`). Called after `collab.stop` on a file that is still on the server: new links and codes for that same file (nothing is published twice). `collab.stop` stops sharing", false, share ), diff --git a/docs/collaboration-parity.md b/docs/collaboration-parity.md index 18ef2efe9..0998cde7f 100644 --- a/docs/collaboration-parity.md +++ b/docs/collaboration-parity.md @@ -27,6 +27,7 @@ cursors, selections, text carets, cursor chat and spotlights shown live ([`colla | Date | Change | Summary | |---|---|---| +| 2026-11-28 | patch | M9, #2495: Stop sharing failed on a private server for a file shared with the server key typed under Advanced ("that owner token doesn't manage a file of that id here"). Such a file has no owner token, and the key went only with the publish. `collab.share {key}` now keeps the key with the share in this session, in the address as `collab.share {server: "…?key=…"}` would give it, so Stop sharing and sharing again ask as the server's operator. The key is never in a command result. Test: `live_share_tests::stopping_a_file_shared_with_a_separate_key_asks_with_that_key`. Numbers unchanged | | 2026-11-26 | minor | M10, gap 17: shared branches sync across live sessions. Capability-gated on `branches` in `Hello::client_version` (`ServerMsg::Branches` / `Branch`, `ClientMsg::Branch` with `Create`, `Edit`, `UpdateFromMain`, `SetState`), persisted in `SessionState::branches` and the server journal (with fallback decoding for pre-branch `figcraft-server` snapshots). Any editor can open, co-edit, update from main, review, archive and merge another peer's branch (remote merges/archives close open branch tabs on peers and switch back to main); view and comment links are refused; node/entry id spaces, geometry and image entries are validated on every branch mutation; older clients and servers stay compatible (local-only branches). Tests: `collab::branch_tests`, `engine::branch_live_tests`, `figcraft-server::server_tests::shared_branches_sync_and_survive_a_server_restart`, `figcraft-server::disk::tests::decode_snapshot_reads_pre_branch_v1_snapshots`. Numbers unchanged. | | 2026-11-16 | patch | M9, #2365: a server predating reconnect secrets sends a complete `Welcome` ending at `access`; postcard does not honor a missing trailing field through `serde(default)`. The client reads that exact legacy layout, preserves access, and keeps strict size, version and message-boundary checks. Native and browser transports use this reader; reconnects without a secret send a fresh authenticated hello. Covered by codec and connection-driver regressions. A patched 0.15.1 desktop build was also checked against the public service with separate view-only access and annotation reads; writes remained denied. The public server still needs upgrading. Numbers unchanged. | | 2026-11-06 | minor | M9, #1972 review: the opening-page row said **done** but the default differs from the reference. With no opening page set, a file opens on the page that was current when it was saved or published (`Document::current_page`, written by save), which can be any page, where the reference opens on the first page, and a link cannot name a page. Regraded **partial**; setting the opening page is unchanged. Numbers unchanged. | From c83de9d85ef32273c6c1ec9c825ca17db87dcdb1 Mon Sep 17 00:00:00 2001 From: Bryton Cooper Date: Sat, 28 Nov 2026 01:23:45 -0700 Subject: [PATCH 43/48] fix(collab): charge CodeLinks delta in est_deltas_extra_bytes --- crates/collab/src/delta_snapshot/decode.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/collab/src/delta_snapshot/decode.rs b/crates/collab/src/delta_snapshot/decode.rs index cab21be9e..cfe8856a5 100644 --- a/crates/collab/src/delta_snapshot/decode.rs +++ b/crates/collab/src/delta_snapshot/decode.rs @@ -122,6 +122,7 @@ pub(super) fn est_deltas_extra_bytes(deltas: &[FieldDelta], vector_sizes: &[usiz FieldDelta::Effects(v) => v.len().saturating_mul(size_of::()), FieldDelta::Bound(m) | FieldDelta::VarModes(m) | FieldDelta::PluginData(m) | FieldDelta::PropRefs(m) => est_str_map(m), FieldDelta::Annotations(v) => v.len().saturating_mul(size_of::()), + FieldDelta::CodeLinks(v) => v.len().saturating_mul(size_of::()), _ => 0, }; acc.saturating_add(extra) From d9deec7b12dff2889f6a3b7f20261a6e56abc1de Mon Sep 17 00:00:00 2001 From: Bryton Cooper Date: Sat, 28 Nov 2026 01:19:51 -0700 Subject: [PATCH 44/48] perf(doc): share TextData and VectorNetwork copy-on-write via Shared (#1819) --- crates/collab/src/delta_snapshot/decode.rs | 4 +- crates/collab/src/delta_snapshot/encode.rs | 2 +- crates/collab/src/delta_snapshot/fields.rs | 7 +- crates/collab/src/delta_snapshot_tests.rs | 6 +- crates/doc/src/boolean_hit_tests.rs | 6 +- crates/doc/src/colors_tests.rs | 2 +- crates/doc/src/lib.rs | 13 +- crates/doc/src/node.rs | 8 +- crates/doc/src/shared.rs | 105 ++++++++++ crates/doc/src/shared_tests.rs | 195 ++++++++++++++++++ crates/doc/src/tests.rs | 10 +- crates/engine/src/board_code_tests.rs | 8 +- crates/engine/src/board_mindmap_tests.rs | 4 +- crates/engine/src/boards/board/connectors.rs | 2 +- crates/engine/src/boards/board/derived.rs | 8 +- crates/engine/src/boards/board/edit.rs | 2 +- crates/engine/src/boards/board/items.rs | 6 +- crates/engine/src/boolean_cap_tests.rs | 2 +- crates/engine/src/canvas/shapebuilder.rs | 8 +- .../shapebuilder_region_paints_tests.rs | 8 +- crates/engine/src/canvas/textedit.rs | 2 +- crates/engine/src/canvas/tools/click.rs | 4 +- crates/engine/src/canvas/tools/pen.rs | 4 +- crates/engine/src/canvas/vectoredit.rs | 2 +- .../engine/src/canvas/vectoredit/pointer.rs | 2 +- .../src/canvas/vectoredit/regions_tests.rs | 2 +- crates/engine/src/canvas/vectoredit/tests.rs | 4 +- crates/engine/src/cmd/create.rs | 8 +- .../engine/src/cmd/edit/vector_clipboard.rs | 4 +- crates/engine/src/cmd/file/load.rs | 10 +- crates/engine/src/cmd/props.rs | 2 +- crates/engine/src/cmd/structure.rs | 14 +- crates/engine/src/cmd/styles.rs | 4 +- crates/engine/src/cmd/text.rs | 3 +- crates/engine/src/content/synthetic.rs | 2 +- crates/engine/src/content/synthetic_ds.rs | 2 +- crates/engine/src/design/fix.rs | 2 +- crates/engine/src/extensions/widgets.rs | 2 +- crates/engine/src/node_find_tests.rs | 10 +- crates/engine/src/penpot_export_tests.rs | 2 +- crates/engine/src/shapes_behaviour_tests.rs | 2 +- crates/engine/src/text_metrics_local_tests.rs | 2 +- crates/engine/src/vector_behaviour_tests.rs | 4 +- crates/engine/src/vector_fill_rule_tests.rs | 6 +- crates/format/src/fig/assets_tests.rs | 16 +- crates/format/src/fig/board_import_tests.rs | 4 +- crates/format/src/fig/export/assets.rs | 2 +- crates/format/src/fig/export/common.rs | 2 +- crates/format/src/fig/export/layer.rs | 12 +- crates/format/src/fig/export_slot_tests.rs | 6 +- crates/format/src/fig/export_tests.rs | 20 +- crates/format/src/fig/interop_tests.rs | 2 +- crates/format/src/fig/text_list_tests.rs | 2 +- crates/format/src/fig/text_skip_ink_tests.rs | 18 +- crates/format/src/large_tests.rs | 8 +- crates/format/src/penpot.rs | 10 +- crates/format/src/penpot/export_tests.rs | 8 +- crates/format/src/rest.rs | 12 +- .../tests/it/range_hyperlink_round_trip.rs | 4 +- crates/layout/src/behaviour_tests.rs | 2 +- crates/layout/src/lib.rs | 6 +- crates/layout/src/tests.rs | 2 +- crates/pdf/src/export_tests.rs | 6 +- crates/pdf/src/tests.rs | 8 +- crates/render/src/boolean_budget_tests.rs | 2 +- crates/render/src/boolean_cache_tests.rs | 2 +- crates/render/src/lod_tests.rs | 8 +- crates/render/src/paint_behaviour_tests.rs | 2 +- crates/render/src/retained_edit_tests.rs | 2 +- crates/render/src/retained_tests.rs | 4 +- crates/render/src/rtl_list_tests.rs | 2 +- crates/render/src/shadow_silhouette_tests.rs | 4 +- crates/render/src/tests.rs | 12 +- crates/svg/src/import.rs | 2 +- crates/svg/src/import/text.rs | 2 +- crates/svg/src/tests.rs | 18 +- crates/text/src/onpath_tests.rs | 2 +- crates/text/src/tests.rs | 6 +- crates/ui-egui/src/canvas/overlays.rs | 2 +- .../ui-egui/src/panels/typography/glyphs.rs | 2 +- crates/ui-egui/src/region_fill_rows_tests.rs | 2 +- crates/ui-egui/src/widgets/font_preview.rs | 2 +- crates/vectordrawable/src/tests/shapes.rs | 2 +- 83 files changed, 533 insertions(+), 200 deletions(-) create mode 100644 crates/doc/src/shared.rs create mode 100644 crates/doc/src/shared_tests.rs diff --git a/crates/collab/src/delta_snapshot/decode.rs b/crates/collab/src/delta_snapshot/decode.rs index 2579a12dc..36336b65c 100644 --- a/crates/collab/src/delta_snapshot/decode.rs +++ b/crates/collab/src/delta_snapshot/decode.rs @@ -125,7 +125,7 @@ struct DecodeState { doc: Document, positions: Positions, touched: BTreeSet, - vectors: Vec, + vectors: Vec>, vector_sizes: Vec, node_sizes: HashMap, meta: Option, @@ -240,7 +240,7 @@ impl<'de> Visitor<'de> for VectorsSeed<'_> { return Err(self.0.fail(err)); } self.0.vector_sizes.push(size); - self.0.vectors.push(net); + self.0.vectors.push(figcraft_doc::Shared::new(net)); } Ok(()) } diff --git a/crates/collab/src/delta_snapshot/encode.rs b/crates/collab/src/delta_snapshot/encode.rs index 474cea954..437687c95 100644 --- a/crates/collab/src/delta_snapshot/encode.rs +++ b/crates/collab/src/delta_snapshot/encode.rs @@ -143,7 +143,7 @@ fn encode_one_node(node: &Node, pos: String, seen: &HashMap, inte let vref = match &mut stripped.kind { NodeKind::Vector { network } if !network.vertices.is_empty() || !network.segments.is_empty() || !network.regions.is_empty() => { let idx = interner.intern(network)?; - *network = VectorNetwork::default(); + *network = figcraft_doc::Shared::default(); Some(idx) } _ => None, diff --git a/crates/collab/src/delta_snapshot/fields.rs b/crates/collab/src/delta_snapshot/fields.rs index e3ebe097b..240242d6e 100644 --- a/crates/collab/src/delta_snapshot/fields.rs +++ b/crates/collab/src/delta_snapshot/fields.rs @@ -11,7 +11,7 @@ use figcraft_doc::geom::Affine; use figcraft_doc::proto::{Interaction, Overflow, ScrollPosition}; use figcraft_doc::{ Annotation, AutoLayout, BoardItem, BoolOp, ChildLayout, CodeLink, CollectionId, Constraints, Corners, DevResource, DevStatus, Effect, - ExportSetting, Guide, LayoutGrid, MaskType, Measurement, ModeId, Node, NodeKind, Region, Segment, StrokeProps, StyleRefs, VariableId, + ExportSetting, Guide, LayoutGrid, MaskType, Measurement, ModeId, Node, NodeKind, Region, Segment, Shared, StrokeProps, StyleRefs, VariableId, VectorNetwork, Vertex, }; use serde::{Deserialize, Serialize}; @@ -51,7 +51,7 @@ macro_rules! delta_fields { )* } - pub(super) fn apply_field_delta(node: &mut Node, delta: FieldDelta, vectors: &[VectorNetwork]) -> Result<(), Error> { + pub(super) fn apply_field_delta(node: &mut Node, delta: FieldDelta, vectors: &[Shared]) -> Result<(), Error> { match delta { FieldDelta::Kind(v) => node.kind = *v, FieldDelta::VectorRef(idx) => { @@ -278,7 +278,8 @@ fn exact_kind_eq(a: &NodeKind, b: &NodeKind) -> bool { | (NodeKind::Group, NodeKind::Group) | (NodeKind::Rectangle, NodeKind::Rectangle) | (NodeKind::Line, NodeKind::Line) => true, - (NodeKind::Vector { network: na }, NodeKind::Vector { network: nb }) => exact_vector_network_eq(na, nb), + (NodeKind::Vector { network: na }, NodeKind::Vector { network: nb }) => na.ptr_eq(nb) || exact_vector_network_eq(na, nb), + (NodeKind::Text(ta), NodeKind::Text(tb)) => ta.ptr_eq(tb) || eq_exact(&**ta, &**tb), _ => eq_exact(a, b), } } diff --git a/crates/collab/src/delta_snapshot_tests.rs b/crates/collab/src/delta_snapshot_tests.rs index ff6a369fc..4ee754bce 100644 --- a/crates/collab/src/delta_snapshot_tests.rs +++ b/crates/collab/src/delta_snapshot_tests.rs @@ -77,9 +77,9 @@ pub(crate) fn design_system_doc(num_instances: usize) -> (Document, NodeId, Vec< let mut main_children = Vec::new(); for i in 0..6 { let kind = match i { - 0 | 1 => NodeKind::Text(TextData::new(format!("Title {i}"))), - 2 => NodeKind::Vector { network: icon_a.clone() }, - 3 => NodeKind::Vector { network: icon_b.clone() }, + 0 | 1 => NodeKind::Text(TextData::new(format!("Title {i}")).into()), + 2 => NodeKind::Vector { network: icon_a.clone().into() }, + 3 => NodeKind::Vector { network: icon_b.clone().into() }, _ => NodeKind::Rectangle, }; let cid = doc.create(comp, kind, &format!("Part {i}"), i as f64 * 24.0, 8.0, 32.0, 32.0).unwrap(); diff --git a/crates/doc/src/boolean_hit_tests.rs b/crates/doc/src/boolean_hit_tests.rs index 5a8a01128..158eed55d 100644 --- a/crates/doc/src/boolean_hit_tests.rs +++ b/crates/doc/src/boolean_hit_tests.rs @@ -57,7 +57,7 @@ fn ordinary_hit_uses_region_paints_without_layer_fill() { Region { loops: vec![vec![0, 1, 2, 3]], winding: WindingRule::NonZero, fills: Some(Vec::new()), ..Default::default() }, ], }; - let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 10.0, 10.0).unwrap(); + let id = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 10.0, 10.0).unwrap(); d.get_mut(id).unwrap().fills.clear(); assert!(d.node(id).unwrap().fills.is_empty()); assert_eq!(d.hit_test(p, Point::new(5.0, 5.0), 0.0, None), Some(id)); @@ -71,7 +71,7 @@ fn inherited_paint_frames_use_per_region_hit_testing() { let mut network = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)], true); network.regions[0].winding = WindingRule::EvenOdd; network.regions.push(network.regions[0].clone()); - let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 10.0, 10.0).unwrap(); + let id = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 10.0, 10.0).unwrap(); assert_eq!(d.hit_test(p, Point::new(5.0, 5.0), 0.0, None), None, "legacy even-odd loops cancel"); let NodeKind::Vector { network } = &mut d.get_mut(id).unwrap().kind else { panic!("expected vector") }; network.regions[0].paint_space = Some(crate::RegionPaintSpace { width: 10.0, height: 10.0, transform: figcraft_geom::Affine::IDENTITY }); @@ -87,7 +87,7 @@ fn explicitly_unfilled_regions_keep_the_stroke_only_selection_band() { let mut network = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)], true); network.regions[0].fills = Some(Vec::new()); - let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 100.0).unwrap(); + let id = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 100.0, 100.0).unwrap(); let n = d.get_mut(id).unwrap(); n.fills.clear(); n.strokes = vec![figcraft_color::Paint::solid(figcraft_color::Color::BLACK)]; diff --git a/crates/doc/src/colors_tests.rs b/crates/doc/src/colors_tests.rs index ebf659594..84bb21659 100644 --- a/crates/doc/src/colors_tests.rs +++ b/crates/doc/src/colors_tests.rs @@ -13,7 +13,7 @@ fn colourful() -> (Document, NodeId) { let mut d = Document::new("c"); let p = d.first_page().unwrap(); let r = d.create(p, NodeKind::Rectangle, "R", 0.0, 0.0, 10.0, 10.0).unwrap(); - let t = d.create(p, NodeKind::Text(TextData::default()), "T", 0.0, 0.0, 10.0, 10.0).unwrap(); + let t = d.create(p, NodeKind::Text(TextData::default().into()), "T", 0.0, 0.0, 10.0, 10.0).unwrap(); { let n = d.node_mut(r).unwrap(); n.fills = vec![Paint::solid(RED)]; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c83c7eb85..ea546fffa 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -23,6 +23,7 @@ pub mod library; pub mod node; pub mod props; pub mod proto; +pub mod shared; pub mod styles; pub mod text; pub mod vector; @@ -43,6 +44,7 @@ pub use handoff::*; pub use library::*; pub use node::*; pub use props::*; +pub use shared::Shared; pub use styles::*; pub use text::*; pub use vector::*; @@ -978,7 +980,14 @@ impl Document { pt.source = m.0; } } - if let NodeKind::Vector { network } = &mut c.kind { + if let NodeKind::Vector { network } = &mut c.kind + && network + .regions + .iter() + .filter_map(|r| r.fills.as_deref()) + .flatten() + .any(|p| matches!(&p.kind, figcraft_color::PaintKind::Pattern(pt) if map.contains_key(&NodeId(pt.source)))) + { for p in network.regions.iter_mut().filter_map(|r| r.fills.as_mut()).flatten() { if let figcraft_color::PaintKind::Pattern(pt) = &mut p.kind && let Some(m) = map.get(&NodeId(pt.source)) @@ -1379,6 +1388,8 @@ mod proto_expr_tests; #[cfg(test)] mod proto_overlay_anchor_tests; #[cfg(test)] +mod shared_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod vector_radius_tests; diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index fad9d1a90..0514ffa5c 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -6,6 +6,7 @@ use crate::props::{ StrokeProps, }; use crate::proto::{Interaction, Overflow, ScrollPosition}; +use crate::shared::Shared; use crate::styles::{CollectionId, ModeId, StyleRefs, VariableId}; use crate::text::TextData; use crate::vector::VectorNetwork; @@ -78,9 +79,6 @@ pub fn ordered_props<'a>(props: &'a BTreeMap, order: &[String]) } /// What a node is, with per-type data. -// Text sets the size; the lint counts the gap to the next largest variant, which grew only because -// Page's guides moved to the node (#1476). -#[allow(clippy::large_enum_variant)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "camelCase")] pub enum NodeKind { @@ -120,9 +118,9 @@ pub enum NodeKind { }, Line, Vector { - network: VectorNetwork, + network: Shared, }, - Text(TextData), + Text(Shared), BooleanOp { op: BoolOp, }, diff --git a/crates/doc/src/shared.rs b/crates/doc/src/shared.rs new file mode 100644 index 000000000..fc5ab039a --- /dev/null +++ b/crates/doc/src/shared.rs @@ -0,0 +1,105 @@ +//! Copy-on-write `Arc` wrapper for shared layer payloads (`TextData`, `VectorNetwork`). +//! +//! Cloning a [`Shared`] payload is an O(1) atomic reference-count bump, so mirrored layers inside +//! component instances and duplicated subtrees share identical vector networks and text data in +//! memory. Mutating through [`DerefMut`] detaches via [`Arc::make_mut`], leaving every other +//! holder unchanged. Serialization and deserialization are transparent. + +use std::ops::{Deref, DerefMut}; +use std::sync::Arc; + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +/// Copy-on-write reference-counted wrapper around `T`. +#[derive(Debug, Default)] +pub struct Shared(Arc); + +impl Shared { + /// Wrap `value` in a new shared allocation. + pub fn new(value: T) -> Self { + Self(Arc::new(value)) + } + + /// Wrap an existing [`Arc`]. + pub fn from_arc(arc: Arc) -> Self { + Self(arc) + } + + /// Borrow the underlying [`Arc`]. + pub fn as_arc(&self) -> &Arc { + &self.0 + } + + /// Unwrap the underlying [`Arc`]. + pub fn into_arc(self) -> Arc { + self.0 + } + + /// Whether `self` and `other` point to the exact same allocation. + pub fn ptr_eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } + + /// Current strong reference count of the underlying allocation. + pub fn strong_count(&self) -> usize { + Arc::strong_count(&self.0) + } +} + +impl Clone for Shared { + fn clone(&self) -> Self { + Self(Arc::clone(&self.0)) + } +} + +impl Deref for Shared { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +impl DerefMut for Shared { + fn deref_mut(&mut self) -> &mut T { + Arc::make_mut(&mut self.0) + } +} + +impl PartialEq for Shared { + fn eq(&self, other: &Self) -> bool { + *self.0 == *other.0 + } +} + +impl Eq for Shared {} + +impl From for Shared { + fn from(value: T) -> Self { + Self::new(value) + } +} + +impl From> for Shared { + fn from(arc: Arc) -> Self { + Self(arc) + } +} + +impl AsRef for Shared { + fn as_ref(&self) -> &T { + &self.0 + } +} + +impl Serialize for Shared { + fn serialize(&self, serializer: S) -> Result { + self.0.serialize(serializer) + } +} + +impl<'de, T: Deserialize<'de>> Deserialize<'de> for Shared { + fn deserialize>(deserializer: D) -> Result { + T::deserialize(deserializer).map(Self::new) + } +} diff --git a/crates/doc/src/shared_tests.rs b/crates/doc/src/shared_tests.rs new file mode 100644 index 000000000..b2b8d7f34 --- /dev/null +++ b/crates/doc/src/shared_tests.rs @@ -0,0 +1,195 @@ +//! Copy-on-write structural sharing tests for [`Shared`] and `NodeKind` payloads. + +use figcraft_geom::Point; + +use crate::*; + +#[test] +fn node_kind_stays_compact_with_shared_text_and_vector_payloads() { + use std::mem::size_of; + // Before wrapping TextData (352 B) and VectorNetwork (72 B) in Shared, NodeKind was 352 B + // and Node was 1608 B. + assert!(size_of::() <= 144, "NodeKind grew unexpectedly: {} bytes", size_of::()); + assert!(size_of::() <= 1400, "Node grew unexpectedly: {} bytes", size_of::()); +} + +#[test] +fn shared_clone_shares_pointer_and_deref_mut_detaches_without_mutating_source() { + let mut net = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0)], true); + let a = Shared::new(net.clone()); + let mut b = a.clone(); + assert!(a.ptr_eq(&b)); + assert_eq!(a.strong_count(), 2); + + // Mutating through DerefMut detaches b and leaves a untouched. + b.vertices[0].x = 42.0; + assert!(!a.ptr_eq(&b)); + assert_eq!(a.strong_count(), 1); + assert_eq!(b.strong_count(), 1); + assert_eq!(a.vertices[0].x, 0.0); + assert_eq!(b.vertices[0].x, 42.0); + + // Non-mutating reads never detach. + net.vertices[0].x = 42.0; + assert_eq!(*b, net); + let c = b.clone(); + let _len = c.vertices.len(); + assert!(b.ptr_eq(&c)); +} + +#[test] +fn duplicated_text_and_vector_layers_share_payloads_until_edited() { + let mut doc = Document::new("CoW"); + let page = doc.first_page().unwrap(); + let group = doc.create(page, NodeKind::Frame, "Card", 0.0, 0.0, 200.0, 100.0).unwrap(); + let net = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(24.0, 0.0), Point::new(12.0, 24.0)], true); + let vec_id = doc.create(group, NodeKind::Vector { network: net.into() }, "Icon", 0.0, 0.0, 24.0, 24.0).unwrap(); + let txt_id = doc.create(group, NodeKind::Text(TextData::new("Hello").into()), "Title", 32.0, 0.0, 100.0, 20.0).unwrap(); + + let copy = doc.duplicate_into(group, page, None).unwrap(); + let copy_children = doc.node(copy).unwrap().children.clone(); + let (copy_vec, copy_txt) = (copy_children[0], copy_children[1]); + + // Both vector and text payloads share the exact same Arc right after duplication. + match (&doc.node(vec_id).unwrap().kind, &doc.node(copy_vec).unwrap().kind) { + (NodeKind::Vector { network: a }, NodeKind::Vector { network: b }) => assert!(a.ptr_eq(b)), + _ => panic!("expected vector nodes"), + } + match (&doc.node(txt_id).unwrap().kind, &doc.node(copy_txt).unwrap().kind) { + (NodeKind::Text(a), NodeKind::Text(b)) => assert!(a.ptr_eq(b)), + _ => panic!("expected text nodes"), + } + + // Editing the copy's text detaches only the copy's TextData; the vector stays shared. + if let Some(NodeKind::Text(t)) = doc.node_mut(copy_txt).map(|n| &mut n.kind) { + t.characters = "Edited".into(); + } + match (&doc.node(txt_id).unwrap().kind, &doc.node(copy_txt).unwrap().kind) { + (NodeKind::Text(a), NodeKind::Text(b)) => { + assert!(!a.ptr_eq(b)); + assert_eq!(a.characters, "Hello"); + assert_eq!(b.characters, "Edited"); + } + _ => panic!("expected text nodes"), + } + match (&doc.node(vec_id).unwrap().kind, &doc.node(copy_vec).unwrap().kind) { + (NodeKind::Vector { network: a }, NodeKind::Vector { network: b }) => assert!(a.ptr_eq(b)), + _ => panic!("expected vector nodes"), + } +} + +#[test] +fn shared_serialization_is_transparent_in_json() { + let td = TextData::new("Transparent"); + let raw = serde_json::to_string(&td).unwrap(); + let wrapped = serde_json::to_string(&Shared::new(td.clone())).unwrap(); + assert_eq!(raw, wrapped); + let back: Shared = serde_json::from_str(&wrapped).unwrap(); + assert_eq!(*back, td); +} + +#[test] +#[ignore = "benchmark: run with cargo test --release -p figcraft-doc bench_cow_sharing -- --ignored --nocapture"] +fn bench_cow_sharing() { + use std::collections::HashSet; + use std::mem::size_of; + use std::time::Instant; + + let pts: Vec = (0..64) + .map(|i| { + let a = (i as f64) * std::f64::consts::TAU / 64.0; + let r = if i % 2 == 0 { 16.0 } else { 8.0 }; + Point::new(a.cos() * r, a.sin() * r) + }) + .collect(); + let icon = VectorNetwork::from_points(&pts, true); + + let mut doc = Document::new("BenchCoW"); + let page = doc.first_page().unwrap(); + let comp = doc + .create( + page, + NodeKind::Component { description: "Card".into(), props: Default::default(), prop_order: Vec::new() }, + "Card", + 0.0, + 0.0, + 400.0, + 300.0, + ) + .unwrap(); + let mut kids = Vec::new(); + for i in 0..40 { + let kind = match i % 4 { + 0 => NodeKind::Text(TextData::new(format!("Label {i}")).into()), + 1 => NodeKind::Vector { network: icon.clone().into() }, + _ => NodeKind::Rectangle, + }; + kids.push(doc.create(comp, kind, &format!("L{i}"), (i % 8) as f64 * 48.0, (i / 8) as f64 * 56.0, 40.0, 40.0).unwrap()); + } + + let t0 = Instant::now(); + for k in 0..1024 { + let inst = doc + .create( + page, + NodeKind::Instance { component: comp, props: Default::default() }, + "Card", + (k % 32) as f64 * 420.0, + (k / 32) as f64 * 320.0, + 400.0, + 300.0, + ) + .unwrap(); + doc.get_mut(inst).unwrap().source = Some(comp); + for &src_id in &kids { + let mut c = doc.node(src_id).unwrap().clone(); + c.id = doc.alloc_id(); + c.parent = None; + c.children.clear(); + c.source = Some(src_id); + doc.insert(c, inst, None).unwrap(); + } + } + let build_ms = t0.elapsed().as_secs_f64() * 1000.0; + + let mut unique_vec_ptrs = HashSet::new(); + let mut unique_txt_ptrs = HashSet::new(); + let mut total_vecs = 0usize; + let mut total_txts = 0usize; + for n in doc.nodes() { + match &n.kind { + NodeKind::Vector { network } => { + total_vecs += 1; + unique_vec_ptrs.insert(std::sync::Arc::as_ptr(network.as_arc()) as usize); + } + NodeKind::Text(t) => { + total_txts += 1; + unique_txt_ptrs.insert(std::sync::Arc::as_ptr(t.as_arc()) as usize); + } + _ => {} + } + } + + let vec_heap_one = icon.vertices.len() * size_of::() + + icon.segments.len() * size_of::() + + icon.regions.len() * size_of::() + + icon.regions.iter().map(|r| r.loops.iter().map(|l| l.len() * size_of::()).sum::()).sum::(); + let vec_heap_naive = total_vecs * vec_heap_one; + let vec_heap_shared = unique_vec_ptrs.len() * vec_heap_one; + + eprintln!( + "Node={} B (was 1608 B), NodeKind={} B (was 352 B)\n42k build: {:.1} ms, nodes={}\nVectors: {} total -> {} unique Arcs (heap {:.2} MB -> {:.3} MB, {:.1}x)\nTexts: {} total -> {} unique Arcs ({:.1}x)", + size_of::(), + size_of::(), + build_ms, + doc.node_count(), + total_vecs, + unique_vec_ptrs.len(), + vec_heap_naive as f64 / 1_048_576.0, + vec_heap_shared as f64 / 1_048_576.0, + vec_heap_naive as f64 / vec_heap_shared.max(1) as f64, + total_txts, + unique_txt_ptrs.len(), + total_txts as f64 / unique_txt_ptrs.len().max(1) as f64, + ); +} diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 9d922d6c8..7ff7e0524 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -137,7 +137,7 @@ fn region_paints_participate_in_colors_images_and_pattern_remapping() { figcraft_color::Paint::image("region-image", figcraft_color::ImageScaleMode::Fill), figcraft_color::Paint::pattern(source.0), ]); - let vector = d.create(group, NodeKind::Vector { network }, "Vector", 0.0, 0.0, 20.0, 20.0).unwrap(); + let vector = d.create(group, NodeKind::Vector { network: network.into() }, "Vector", 0.0, 0.0, 20.0, 20.0).unwrap(); assert!(used_images(&d).contains("region-image")); let dup = d.duplicate_into(group, p, None).unwrap(); let copied_children = d.node(dup).unwrap().children.clone(); @@ -311,7 +311,7 @@ fn serde_roundtrip_and_repair() { let p = page(&d); let f = d.create(p, NodeKind::Frame, "F", 0.0, 0.0, 100.0, 100.0).unwrap(); d.get_mut(f).unwrap().layout = Some(AutoLayout::default()); - d.create(f, NodeKind::Text(TextData::new("Hi")), "Hi", 0.0, 0.0, 10.0, 10.0).unwrap(); + d.create(f, NodeKind::Text(TextData::new("Hi").into()), "Hi", 0.0, 0.0, 10.0, 10.0).unwrap(); d.create(f, NodeKind::Star { count: 5, inner_ratio: 0.4 }, "S", 0.0, 0.0, 10.0, 10.0).unwrap(); let j = serde_json::to_string(&d).unwrap(); let back: Document = serde_json::from_str(&j).unwrap(); @@ -576,12 +576,12 @@ fn hit_test_even_odd_vector_hole_misses() { }; let mut d = Document::new("x"); let p = page(&d); - let eo = d.create(p, NodeKind::Vector { network: ring(WindingRule::EvenOdd) }, "V", 0.0, 0.0, 200.0, 200.0).unwrap(); + let eo = d.create(p, NodeKind::Vector { network: ring(WindingRule::EvenOdd).into() }, "V", 0.0, 0.0, 200.0, 200.0).unwrap(); assert_eq!(d.hit_test(p, Point::new(20.0, 100.0), 0.0, None), Some(eo)); assert_eq!(d.hit_test(p, Point::new(100.0, 100.0), 0.0, None), None, "the hole is not filled"); let mut d = Document::new("x"); let p = page(&d); - let nz = d.create(p, NodeKind::Vector { network: ring(WindingRule::NonZero) }, "V", 0.0, 0.0, 200.0, 200.0).unwrap(); + let nz = d.create(p, NodeKind::Vector { network: ring(WindingRule::NonZero).into() }, "V", 0.0, 0.0, 200.0, 200.0).unwrap(); assert_eq!(d.hit_test(p, Point::new(100.0, 100.0), 0.0, None), Some(nz)); } @@ -832,7 +832,7 @@ fn clicks_on_a_smoothed_vector_corner_follow_the_drawn_fill() { let smoothed = net.rounded_smoothed(1.0).unwrap(); let mut d = Document::new("x"); let p = page(&d); - let v = d.create(p, NodeKind::Vector { network: net.clone() }, "V", 0.0, 0.0, 1000.0, 1000.0).unwrap(); + let v = d.create(p, NodeKind::Vector { network: net.clone().into() }, "V", 0.0, 0.0, 1000.0, 1000.0).unwrap(); let n = d.node_mut(v).unwrap(); n.corners.smoothing = 1.0; n.strokes.clear(); diff --git a/crates/engine/src/board_code_tests.rs b/crates/engine/src/board_code_tests.rs index 64f734f0b..666111e93 100644 --- a/crates/engine/src/board_code_tests.rs +++ b/crates/engine/src/board_code_tests.rs @@ -21,8 +21,8 @@ fn bx(s: &Session, id: NodeId) -> Rect { 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, + match &node(s, t).kind { + NodeKind::Text(td) => (**td).clone(), other => panic!("not text: {other:?}"), } } @@ -392,8 +392,8 @@ fn key(s: &mut Session, key: &str, shift: bool) { } fn characters(s: &Session, t: NodeId) -> String { - match node(s, t).kind { - NodeKind::Text(td) => td.characters, + match &node(s, t).kind { + NodeKind::Text(td) => td.characters.clone(), other => panic!("not text: {other:?}"), } } diff --git a/crates/engine/src/board_mindmap_tests.rs b/crates/engine/src/board_mindmap_tests.rs index c83fddc22..0bb67a044 100644 --- a/crates/engine/src/board_mindmap_tests.rs +++ b/crates/engine/src/board_mindmap_tests.rs @@ -30,8 +30,8 @@ fn map(s: &mut Session) -> (NodeId, [NodeId; 3], [NodeId; 3]) { fn text_data(s: &Session, n: NodeId) -> figcraft_doc::TextData { let t = text_of(s.doc().unwrap(), n).unwrap(); - match node(s, t).kind { - NodeKind::Text(td) => td, + match &node(s, t).kind { + NodeKind::Text(td) => (**td).clone(), other => panic!("not text: {other:?}"), } } diff --git a/crates/engine/src/boards/board/connectors.rs b/crates/engine/src/boards/board/connectors.rs index 408de045a..7e285f679 100644 --- a/crates/engine/src/boards/board/connectors.rs +++ b/crates/engine/src/boards/board/connectors.rs @@ -85,7 +85,7 @@ pub(super) fn make(doc: &mut Document, page: NodeId, c: Connector, caps: (Stroke if pts.windows(2).all(|w| w.first() == w.get(1)) { return Err(bad(cmd, "the ends are in the same place")); } - let id = add(doc, page, NodeKind::Vector { network: VectorNetwork::default() }, "Connector", (0.0, 0.0), (0.0, 0.0), |n| { + let id = add(doc, page, NodeKind::Vector { network: VectorNetwork::default().into() }, "Connector", (0.0, 0.0), (0.0, 0.0), |n| { n.fills.clear(); n.strokes = vec![Paint::solid(LINE)]; n.stroke.weight = LINE_WEIGHT; diff --git a/crates/engine/src/boards/board/derived.rs b/crates/engine/src/boards/board/derived.rs index e62d41973..7b230cabc 100644 --- a/crates/engine/src/boards/board/derived.rs +++ b/crates/engine/src/boards/board/derived.rs @@ -263,13 +263,15 @@ pub(super) fn place_route(doc: &mut Document, id: NodeId, pts: &[Point], routing _ => VectorNetwork::from_points(&rel.elements().iter().filter_map(PathEl::end_point).collect::>(), false), }; let t = Affine::translate((b.x0, b.y0)); - let same = - n.transform == t && n.width == b.width() && n.height == b.height() && matches!(&n.kind, NodeKind::Vector { network: old } if *old == network); + let same = n.transform == t + && n.width == b.width() + && n.height == b.height() + && matches!(&n.kind, NodeKind::Vector { network: old } if **old == network); if same { return; } if let Some(n) = doc.node_mut(id) { - n.kind = NodeKind::Vector { network }; + n.kind = NodeKind::Vector { network: network.into() }; n.transform = t; (n.width, n.height) = (b.width(), b.height()); } diff --git a/crates/engine/src/boards/board/edit.rs b/crates/engine/src/boards/board/edit.rs index 410699560..c6f8c33c4 100644 --- a/crates/engine/src/boards/board/edit.rs +++ b/crates/engine/src/boards/board/edit.rs @@ -178,7 +178,7 @@ fn reshape(doc: &mut Document, id: NodeId, new: BoardShape) -> Result<()> { if let Some(o) = doc.get(id)?.children.first().copied() && let Some(on) = doc.node_mut(o) { - on.kind = NodeKind::Vector { network: VectorNetwork::from_path(&new.path(w, h)) }; + on.kind = NodeKind::Vector { network: VectorNetwork::from_path(&new.path(w, h)).into() }; (on.width, on.height, on.transform) = (w, h, Affine::IDENTITY); } Ok(()) diff --git a/crates/engine/src/boards/board/items.rs b/crates/engine/src/boards/board/items.rs index 5cc660b84..6fa1bf0fb 100644 --- a/crates/engine/src/boards/board/items.rs +++ b/crates/engine/src/boards/board/items.rs @@ -44,7 +44,7 @@ pub(crate) fn add_text(doc: &mut Document, parent: NodeId, text: &str, size: f64 ..TextData::default() }; td.style.font_size = size; - let id = add(doc, parent, NodeKind::Text(td), name, (0.0, 0.0), (width.max(1.0), size * 1.4), |n| { + let id = add(doc, parent, NodeKind::Text(td.into()), name, (0.0, 0.0), (width.max(1.0), size * 1.4), |n| { n.fills = vec![Paint::solid(color)]; n.child_layout.sizing_h = Sizing::Fill; })?; @@ -297,7 +297,7 @@ fn make_shape( }); n.board = Some(BoardItem::Shape { shape }); })?; - add(doc, id, NodeKind::Vector { network: VectorNetwork::from_path(&shape.path(w, h)) }, "Outline", (0.0, 0.0), size, |n| { + add(doc, id, NodeKind::Vector { network: VectorNetwork::from_path(&shape.path(w, h)).into() }, "Outline", (0.0, 0.0), size, |n| { n.fills = vec![Paint::solid(color)]; n.strokes = vec![Paint::solid(line_shade(color))]; n.stroke.weight = 1.5; @@ -359,7 +359,7 @@ pub(super) fn stamp_cmd(s: &mut Session, p: &Value) -> Result { })?; for part in stamp.mark() { let path = figcraft_geom::BezPath::from_svg(part.d).map_err(|e| EngineError::Other(format!("stamp mark: {e}")))?; - add(doc, id, NodeKind::Vector { network: VectorNetwork::from_path(&path) }, "Mark", (0.0, 0.0), (STAMP_SIZE, STAMP_SIZE), |n| { + add(doc, id, NodeKind::Vector { network: VectorNetwork::from_path(&path).into() }, "Mark", (0.0, 0.0), (STAMP_SIZE, STAMP_SIZE), |n| { if part.filled { n.fills = vec![Paint::solid(Color::WHITE)]; } else { diff --git a/crates/engine/src/boolean_cap_tests.rs b/crates/engine/src/boolean_cap_tests.rs index b9d40e349..5f6e6b71b 100644 --- a/crates/engine/src/boolean_cap_tests.rs +++ b/crates/engine/src/boolean_cap_tests.rs @@ -27,7 +27,7 @@ fn flattening_a_boolean_past_the_caps_is_refused() { .into_iter() .map(|across| { let network = VectorNetwork::from_path(&bars(750, across)); - s.doc_mut().unwrap().create(page, NodeKind::Vector { network }, "Bars", 0.0, 0.0, 3000.0, 3000.0).unwrap() + s.doc_mut().unwrap().create(page, NodeKind::Vector { network: network.into() }, "Bars", 0.0, 0.0, 3000.0, 3000.0).unwrap() }) .collect(); let g = id_of(&s.execute("bool.union", &json!({"ids": ids})).unwrap()["id"]).unwrap(); diff --git a/crates/engine/src/canvas/shapebuilder.rs b/crates/engine/src/canvas/shapebuilder.rs index fea91db25..bb2b8cbb2 100644 --- a/crates/engine/src/canvas/shapebuilder.rs +++ b/crates/engine/src/canvas/shapebuilder.rs @@ -323,12 +323,12 @@ fn reshape_vector_regions(doc: &mut Document, id: NodeId, areas: &[(usize, BezPa } let Some(bounds) = rebuilt.bounds() else { let n = doc.get_mut(id)?; - n.kind = NodeKind::Vector { network: rebuilt }; + n.kind = NodeKind::Vector { network: rebuilt.into() }; return Ok(()); }; rebuilt.translate(-bounds.x0, -bounds.y0); let n = doc.get_mut(id)?; - n.kind = NodeKind::Vector { network: rebuilt }; + n.kind = NodeKind::Vector { network: rebuilt.into() }; n.children.clear(); n.corners = Corners::default(); n.transform *= Affine::translate((bounds.x0, bounds.y0)); @@ -351,7 +351,7 @@ fn reshape(doc: &mut Document, id: NodeId, area: &BezPath) -> Result<()> { } } let n = doc.get_mut(id)?; - n.kind = NodeKind::Vector { network: net }; + n.kind = NodeKind::Vector { network: net.into() }; n.children.clear(); n.corners = Corners::default(); crate::vectoredit::refit(doc, id) @@ -388,7 +388,7 @@ fn create_merged(doc: &mut Document, style: Part, area: &BezPath) -> Result NodeId { append(&mut network, box_path(50.0, 0.0, 100.0, 100.0)); network.regions[0].fills = Some(vec![Paint::solid(Color::from_hex("#ff0000").unwrap())]); network.regions[1].fills = Some(vec![Paint::solid(Color::from_hex("#0000ff").unwrap())]); - s.doc_mut().unwrap().get_mut(id).unwrap().kind = NodeKind::Vector { network }; + s.doc_mut().unwrap().get_mut(id).unwrap().kind = NodeKind::Vector { network: network.into() }; id } @@ -104,7 +104,7 @@ fn legacy_unstyled_nested_evenodd_regions_keep_the_hole_unpainted() { region.fills = None; region.paint_space = None; } - s.doc_mut().unwrap().get_mut(vector).unwrap().kind = NodeKind::Vector { network: net }; + s.doc_mut().unwrap().get_mut(vector).unwrap().kind = NodeKind::Vector { network: net.into() }; let crossing = rect(&mut s, -5.0, 45.0, 15.0, 10.0, "#ffffff"); s.set_selection(vec![vector, crossing]); let a = arrangement(&mut s, &[vector, crossing]).unwrap(); @@ -168,7 +168,7 @@ fn exceeding_arrangement_capacity_never_drops_unprocessed_regions() { part.regions[0].fills = Some(vec![Paint::solid(Color::BLACK)]); append(&mut net, part); } - s.doc_mut().unwrap().get_mut(vector).unwrap().kind = NodeKind::Vector { network: net.clone() }; + s.doc_mut().unwrap().get_mut(vector).unwrap().kind = NodeKind::Vector { network: net.clone().into() }; s.set_selection(vec![vector]); let error = s.execute("shapeBuilder.remove", &json!({"points": [[5, 5]]})).unwrap_err(); assert!(error.to_string().contains("too many fill regions")); @@ -269,7 +269,7 @@ fn removal_preserves_holes_and_transformed_gradient_frames() { { let doc = s.doc_mut().unwrap(); let node = doc.get_mut(vector).unwrap(); - node.kind = NodeKind::Vector { network: outer }; + node.kind = NodeKind::Vector { network: outer.into() }; node.transform = transform; } let before = normalized_paint_world(&s, vector, 0); diff --git a/crates/engine/src/canvas/textedit.rs b/crates/engine/src/canvas/textedit.rs index 9508bfcb8..2c41c7d13 100644 --- a/crates/engine/src/canvas/textedit.rs +++ b/crates/engine/src/canvas/textedit.rs @@ -83,7 +83,7 @@ fn next_editing_session() -> u64 { fn text_of(s: &Session, id: NodeId) -> Result { match &s.doc()?.get(id)?.kind { - NodeKind::Text(t) => Ok(t.clone()), + NodeKind::Text(t) => Ok((**t).clone()), _ => Err(EngineError::Other(format!("{id} is not a text layer"))), } } diff --git a/crates/engine/src/canvas/tools/click.rs b/crates/engine/src/canvas/tools/click.rs index 1e7a9f902..59100ce8d 100644 --- a/crates/engine/src/canvas/tools/click.rs +++ b/crates/engine/src/canvas/tools/click.rs @@ -231,7 +231,7 @@ impl Session { let ds = self.ds_mut()?; let d = ds.doc_mut(); let id = d.alloc_id(); - let mut n = Node::new(id, NodeKind::Text(TextData::default()), "Text", 1.0, 14.0); + let mut n = Node::new(id, NodeKind::Text(TextData::default().into()), "Text", 1.0, 14.0); let pw = d.world_transform(parent); let at = Point::new(ev.x.round(), (ev.y - 7.0).round()); n.transform = pw.inverse() * Affine::translate(at.to_vec2()); @@ -329,7 +329,7 @@ impl Session { let ds = self.ds_mut()?; let d = ds.doc_mut(); let id = d.alloc_id(); - let mut n = Node::new(id, NodeKind::Text(TextData::default()), "Text", pn.width, pn.height); + let mut n = Node::new(id, NodeKind::Text(TextData::default().into()), "Text", pn.width, pn.height); n.name = String::new(); n.transform = pn.transform; n.constraints = pn.constraints; diff --git a/crates/engine/src/canvas/tools/pen.rs b/crates/engine/src/canvas/tools/pen.rs index 097a2bf04..8df275a65 100644 --- a/crates/engine/src/canvas/tools/pen.rs +++ b/crates/engine/src/canvas/tools/pen.rs @@ -218,7 +218,7 @@ impl Session { Some(id) if doc.contains(id) => id, _ => { let id = doc.alloc_id(); - let mut n = Node::new(id, NodeKind::Vector { network: VectorNetwork::default() }, "Vector", 0.0, 0.0); + let mut n = Node::new(id, NodeKind::Vector { network: VectorNetwork::default().into() }, "Vector", 0.0, 0.0); n.fills.clear(); n.strokes = vec![figcraft_color::Paint::solid(figcraft_color::Color::BLACK)]; n.stroke.align = StrokeAlign::Center; @@ -227,7 +227,7 @@ impl Session { } }; let n = doc.get_mut(id)?; - n.kind = NodeKind::Vector { network: net }; + n.kind = NodeKind::Vector { network: net.into() }; n.width = bb.width(); n.height = bb.height(); n.transform = Affine::translate((bb.x0, bb.y0)); diff --git a/crates/engine/src/canvas/vectoredit.rs b/crates/engine/src/canvas/vectoredit.rs index cf00a06de..99d58679a 100644 --- a/crates/engine/src/canvas/vectoredit.rs +++ b/crates/engine/src/canvas/vectoredit.rs @@ -341,7 +341,7 @@ pub fn ensure_vector(doc: &mut Document, id: NodeId) -> Result<()> { } } let node = doc.get_mut(id)?; - node.kind = NodeKind::Vector { network: net }; + node.kind = NodeKind::Vector { network: net.into() }; node.children.clear(); if matches!(n.kind, NodeKind::Line) { node.stroke.align = StrokeAlign::Center; diff --git a/crates/engine/src/canvas/vectoredit/pointer.rs b/crates/engine/src/canvas/vectoredit/pointer.rs index dadb1e3e8..2f32f5aef 100644 --- a/crates/engine/src/canvas/vectoredit/pointer.rs +++ b/crates/engine/src/canvas/vectoredit/pointer.rs @@ -1171,7 +1171,7 @@ impl Session { // The preview starts again from the document before the drag: bring the moved layer. self.preview(|doc, _| { *doc.get_mut(id)? = moved; - edit(doc, id, |net| *net = merged) + edit(doc, id, |net| *net = (*merged).clone()) })?; set_state(self, |e| { e.vertices = vec![if keep > v { keep - 1 } else { keep }]; diff --git a/crates/engine/src/canvas/vectoredit/regions_tests.rs b/crates/engine/src/canvas/vectoredit/regions_tests.rs index a12fc0f84..fa57e02b5 100644 --- a/crates/engine/src/canvas/vectoredit/regions_tests.rs +++ b/crates/engine/src/canvas/vectoredit/regions_tests.rs @@ -51,7 +51,7 @@ fn editing_vector(s: &mut Session, n: VectorNetwork) -> NodeId { let id = crate::params::id_of(&r["id"]).unwrap(); let doc = s.doc_mut().unwrap(); let node = doc.get_mut(id).unwrap(); - node.kind = figcraft_doc::NodeKind::Vector { network: n }; + node.kind = figcraft_doc::NodeKind::Vector { network: n.into() }; node.transform = Affine::IDENTITY; node.fills = vec![figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE)]; super::refit(doc, id).unwrap(); diff --git a/crates/engine/src/canvas/vectoredit/tests.rs b/crates/engine/src/canvas/vectoredit/tests.rs index c5f02d122..636368ee7 100644 --- a/crates/engine/src/canvas/vectoredit/tests.rs +++ b/crates/engine/src/canvas/vectoredit/tests.rs @@ -188,7 +188,7 @@ fn a_handle_and_a_point_are_compared_on_the_page() { let mut seg = figcraft_doc::Segment::line(0, 1); seg.ta = (0.5, -0.9); n.segments.push(seg); - node.kind = figcraft_doc::NodeKind::Vector { network: n }; + node.kind = figcraft_doc::NodeKind::Vector { network: n.into() }; node.transform = figcraft_geom::Affine::scale_non_uniform(10.0, 1.0); } ex(&mut s, "vector.edit.begin", json!({"id": id})); @@ -215,7 +215,7 @@ fn a_handle_on_another_point_is_still_the_handles() { let mut seg = figcraft_doc::Segment::line(0, 1); seg.ta = (10.0, 0.0); n.segments.push(seg); - node.kind = figcraft_doc::NodeKind::Vector { network: n }; + node.kind = figcraft_doc::NodeKind::Vector { network: n.into() }; node.transform = figcraft_geom::Affine::IDENTITY; } ex(&mut s, "vector.edit.begin", json!({"id": id})); diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 48fa80638..b96340c2f 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -173,8 +173,8 @@ pub fn kind_for(t: &str) -> Option<(NodeKind, &'static str)> { "star" => (NodeKind::Star { count: 5, inner_ratio: 0.38 }, "Star"), "line" => (NodeKind::Line, "Line"), "arrow" => (NodeKind::Line, "Arrow"), - "vector" | "path" => (NodeKind::Vector { network: VectorNetwork::default() }, "Vector"), - "text" => (NodeKind::Text(TextData::default()), "Text"), + "vector" | "path" => (NodeKind::Vector { network: VectorNetwork::default().into() }, "Vector"), + "text" => (NodeKind::Text(TextData::default().into()), "Text"), "frame" => (NodeKind::Frame, "Frame"), "section" => (NodeKind::Section { contents_hidden: false }, "Section"), "component" => (NodeKind::Component { description: String::new(), props: Default::default(), prop_order: Vec::new() }, "Component"), @@ -332,7 +332,7 @@ pub fn create(s: &mut Session, p: &Value) -> Result { if let NodeKind::Vector { network } = &mut kind { if let Some(d) = string(p, "path") { let shape = path_network(cmd, &d, asked.0, asked.1)?; - *network = shape.network; + *network = (shape.network).into(); if boolean(p, "closed") == Some(false) { network.regions.clear(); } @@ -355,7 +355,7 @@ pub fn create(s: &mut Session, p: &Value) -> Result { } let (sx, sy) = vector_scale(asked.0, asked.1, bb.width(), bb.height(), "a point set").map_err(|e| bad(cmd, e))?; let local: Vec = pts.iter().map(|q| Point::new((q.x - bb.x0) * sx, (q.y - bb.y0) * sy)).collect(); - *network = VectorNetwork::from_points(&local, boolean(p, "closed").unwrap_or(false)); + *network = VectorNetwork::from_points(&local, boolean(p, "closed").unwrap_or(false)).into(); w = bb.width() * sx; h = bb.height() * sy; offset = (bb.x0, bb.y0); diff --git a/crates/engine/src/cmd/edit/vector_clipboard.rs b/crates/engine/src/cmd/edit/vector_clipboard.rs index f52916ee8..107f60aaf 100644 --- a/crates/engine/src/cmd/edit/vector_clipboard.rs +++ b/crates/engine/src/cmd/edit/vector_clipboard.rs @@ -106,7 +106,7 @@ fn clip_node(doc: &Document, id: NodeId, mut sub: VectorNetwork) -> Option n.transform = doc.world_transform(id) * Affine::translate((b.x0, b.y0)); n.width = b.width(); n.height = b.height(); - n.kind = NodeKind::Vector { network: sub }; + n.kind = NodeKind::Vector { network: sub.into() }; n.parent = None; n.children.clear(); n.name = "Vector".into(); @@ -181,7 +181,7 @@ pub fn clipboard_svg(s: &Session) -> Option { /// frames, groups, instances, …). `doc` is the file the layer was copied from. fn outline_network(doc: &Document, n: &Node) -> Option { let net = match &n.kind { - NodeKind::Vector { network } => network.clone(), + NodeKind::Vector { network } => (**network).clone(), k if k.is_shape() || matches!(k, NodeKind::BooleanOp { .. }) => { let (path, rule) = figcraft_render::node_outline(doc, n)?; let mut net = VectorNetwork::from_path(&path); diff --git a/crates/engine/src/cmd/file/load.rs b/crates/engine/src/cmd/file/load.rs index 74f02cf79..d3242a340 100644 --- a/crates/engine/src/cmd/file/load.rs +++ b/crates/engine/src/cmd/file/load.rs @@ -787,7 +787,7 @@ mod penpot_font_warning_tests { let mut doc = Document::new("External font refs"); let page = doc.first_page().unwrap(); let text = TextData::new("Playball"); - let id = doc.create(page, NodeKind::Text(text), "Custom caption", 0., 0., 120., 30.).unwrap(); + let id = doc.create(page, NodeKind::Text(text.into()), "Custom caption", 0., 0., 120., 30.).unwrap(); doc.node_mut(id).unwrap().plugin_data.insert( "penpot.customFontRefs".into(), r#"[{"id":"custom-123abc","family":"Playball","variants":[{"weight":400,"italic":false}]}]"#.into(), @@ -805,7 +805,7 @@ mod penpot_font_warning_tests { let page = doc.first_page().unwrap(); let mut text = TextData::new("hello world"); text.style.font_family = "Rare Licensed Family".into(); - doc.create(page, NodeKind::Text(text), "Headline", 0.0, 0.0, 200.0, 30.0).unwrap(); + doc.create(page, NodeKind::Text(text.into()), "Headline", 0.0, 0.0, 200.0, 30.0).unwrap(); let warnings = missing_penpot_font_warnings(&doc, &["Inter".into(), "Source Sans Pro".into()]); assert_eq!(warnings.len(), 1); assert!(warnings[0].contains("Rare Licensed Family")); @@ -830,7 +830,7 @@ mod penpot_font_warning_tests { let mut run = t.style.clone(); run.font_family = "Available Font".into(); t.runs.push(StyleRun { start: 0, end: 2, style: run }); - doc.create(page, NodeKind::Text(t), "Full run", 0.0, 0.0, 100.0, 30.0).unwrap(); + doc.create(page, NodeKind::Text(t.into()), "Full run", 0.0, 0.0, 100.0, 30.0).unwrap(); assert!(missing_penpot_font_warnings(&doc, &["Available Font".into()]).is_empty()); } } @@ -875,7 +875,7 @@ mod penpot_svg_v10_tests { let mut run = t.style.clone(); run.font_family = "Run Font".into(); t.runs = (0..50_000).map(|_| StyleRun { start: 0, end: 100_000, style: run.clone() }).collect(); - doc.create(page, NodeKind::Text(t), "Long", 0.0, 0.0, 100.0, 30.0).unwrap(); + doc.create(page, NodeKind::Text(t.into()), "Long", 0.0, 0.0, 100.0, 30.0).unwrap(); let report = font_report_with_families(&doc, &[]); assert_eq!(report["fonts"].as_array().map(Vec::len), Some(1), "{report}"); assert_eq!(report["fonts"][0]["family"], "Run Font"); @@ -921,7 +921,7 @@ mod penpot_svg_v10_tests { let page = doc.first_page().unwrap(); let mut text = TextData::new("Example"); text.style.font_family = "Definitely Never Installed V10 Font Q7".into(); - doc.create(page, NodeKind::Text(text), "Caption", 0.0, 0.0, 100.0, 24.0).unwrap(); + doc.create(page, NodeKind::Text(text.into()), "Caption", 0.0, 0.0, 100.0, 24.0).unwrap(); let report = font_report_with_families(&doc, &["Inter".into()]); assert_eq!(report["missing"], 1); assert_eq!(report["fonts"][0]["family"], "Definitely Never Installed V10 Font Q7"); diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 79310056d..10291c20a 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -1271,7 +1271,7 @@ fn set_path(cmd: &str, doc: &mut Document, id: NodeId, v: &Value, props: &Map Result { net.translate(-bb.x0, -bb.y0); let vid = doc.alloc_id(); let name = first.as_ref().map(|f| f.name.clone()).unwrap_or_else(|| "Vector".into()); - let mut v = Node::new(vid, NodeKind::Vector { network: net }, name, bb.width(), bb.height()); + let mut v = Node::new(vid, NodeKind::Vector { network: net.into() }, name, bb.width(), bb.height()); v.transform = Affine::translate((bb.x0, bb.y0)); if let Some(f) = first { v.fills = output_fills; @@ -620,7 +620,7 @@ fn outline_stroke(s: &mut Session, p: &Value) -> Result { let parent = n.parent.ok_or_else(|| bad("vector.outlineStroke", "page"))?; let idx = doc.index_in_parent(i); let vid = doc.alloc_id(); - let mut v = Node::new(vid, NodeKind::Vector { network: net }, n.name.clone(), bb.width(), bb.height()); + let mut v = Node::new(vid, NodeKind::Vector { network: net.into() }, n.name.clone(), bb.width(), bb.height()); v.transform = n.transform * Affine::translate((bb.x0, bb.y0)); // The stroke's paints (and its colour style) fill the outline. v.fills = n.strokes.clone(); @@ -932,7 +932,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result { net = VectorNetwork::from_path(&simplified); net.regions.clear(); } - *network = net; + *network = net.into(); } } ok() @@ -964,7 +964,7 @@ fn offset_path(s: &mut Session, p: &Value) -> Result { let bounds = result.bounding_box(); result.apply_affine(Affine::translate((-bounds.x0, -bounds.y0))); let node = doc.get_mut(i)?; - node.kind = NodeKind::Vector { network: VectorNetwork::from_path(&result) }; + node.kind = NodeKind::Vector { network: VectorNetwork::from_path(&result).into() }; node.transform *= Affine::translate((bounds.x0, bounds.y0)); node.width = bounds.width(); node.height = bounds.height(); @@ -984,7 +984,7 @@ fn offset_path(s: &mut Session, p: &Value) -> Result { let bb = res.bounding_box(); res.apply_affine(Affine::translate((-bb.x0, -bb.y0))); let nm = doc.get_mut(i)?; - nm.kind = NodeKind::Vector { network: VectorNetwork::from_path(&res) }; + nm.kind = NodeKind::Vector { network: VectorNetwork::from_path(&res).into() }; nm.transform *= Affine::translate((bb.x0, bb.y0)); nm.width = bb.width(); nm.height = bb.height(); @@ -1035,14 +1035,14 @@ fn offset_path(s: &mut Session, p: &Value) -> Result { } let Some(bb) = net.bounds() else { let nm = doc.get_mut(i)?; - nm.kind = NodeKind::Vector { network: net }; + nm.kind = NodeKind::Vector { network: net.into() }; nm.width = 0.0; nm.height = 0.0; continue; }; net.translate(-bb.x0, -bb.y0); let nm = doc.get_mut(i)?; - nm.kind = NodeKind::Vector { network: net }; + nm.kind = NodeKind::Vector { network: net.into() }; nm.transform *= Affine::translate((bb.x0, bb.y0)); nm.width = bb.width(); nm.height = bb.height(); diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index fd6ecfbc3..0c81717b5 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -854,13 +854,13 @@ pub fn sync_text_styles(doc: &mut Document, ids: &[NodeId]) { } let link = t2.text_style_link().flatten().map(str::to_string); if t2 != *t || link != n.styles.text { - updates.push((id, link, t2)); + updates.push((id, link, (*t2).clone())); } } for (id, link, t2) in updates { if let Ok(n) = doc.get_mut(id) { n.styles.text = link; - n.kind = NodeKind::Text(t2); + n.kind = NodeKind::Text(t2.into()); } } } diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index c4f4eaffd..f959ec12b 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -24,7 +24,8 @@ fn style(s: &mut Session, p: &Value, f: impl Fn(&mut TextStyle)) -> Result NodeKind { - NodeKind::Text(figcraft_doc::TextData::new(content)) + NodeKind::Text(figcraft_doc::TextData::new(content).into()) } fn ellipse() -> NodeKind { diff --git a/crates/engine/src/content/synthetic_ds.rs b/crates/engine/src/content/synthetic_ds.rs index be5268355..a16b2446e 100644 --- a/crates/engine/src/content/synthetic_ds.rs +++ b/crates/engine/src/content/synthetic_ds.rs @@ -122,7 +122,7 @@ fn component() -> NodeKind { } fn text(chars: &str) -> NodeKind { - NodeKind::Text(TextData::new(chars)) + NodeKind::Text(TextData::new(chars).into()) } /// Pick a (capped) prefix of a value list. diff --git a/crates/engine/src/design/fix.rs b/crates/engine/src/design/fix.rs index 7e890cdb6..7b53a2d74 100644 --- a/crates/engine/src/design/fix.rs +++ b/crates/engine/src/design/fix.rs @@ -266,7 +266,7 @@ fn apply_radius(n: &mut Node, settings: &Settings) -> Option { /// Run `f` over a text layer's base style and its runs; true when any style changed. fn apply_text(n: &mut Node, f: fn(&mut TextStyle) -> bool) -> Option { let NodeKind::Text(t) = &mut n.kind else { return Some(false) }; - let TextData { style, runs, .. } = t; + let TextData { style, runs, .. } = &mut **t; let mut changed = f(style); for run in runs { changed |= f(&mut run.style); diff --git a/crates/engine/src/extensions/widgets.rs b/crates/engine/src/extensions/widgets.rs index efdd21414..09d3ee9a7 100644 --- a/crates/engine/src/extensions/widgets.rs +++ b/crates/engine/src/extensions/widgets.rs @@ -277,7 +277,7 @@ fn build(s: &mut Session, plugin: &str, w: NodeId, r: &WidgetRender) -> Result<( fn add(doc: &mut Document, parent: NodeId, d: &WidgetNode, cmd: &str, pixels: &mut u64) -> Result<()> { let (kind, name) = match d.kind { WidgetKind::Frame => (NodeKind::Frame, "Frame"), - WidgetKind::Text => (NodeKind::Text(TextData { characters: d.text.clone(), ..TextData::default() }), "Text"), + WidgetKind::Text => (NodeKind::Text((TextData { characters: d.text.clone(), ..TextData::default() }).into()), "Text"), WidgetKind::Rectangle => (NodeKind::Rectangle, "Rectangle"), WidgetKind::Ellipse => (NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }, "Ellipse"), WidgetKind::Image => (NodeKind::Rectangle, "Image"), diff --git a/crates/engine/src/node_find_tests.rs b/crates/engine/src/node_find_tests.rs index cb56d8139..f93757149 100644 --- a/crates/engine/src/node_find_tests.rs +++ b/crates/engine/src/node_find_tests.rs @@ -20,8 +20,8 @@ fn node_find_filters_are_literal_case_insensitive_and_anded() { let mut s = Session::new(); let page = s.page().unwrap(); let frame = add(&mut s, page, NodeKind::Frame, "CAFÉ [Card]"); - let title = add(&mut s, frame, NodeKind::Text(TextData::new("HÉLLO 世界")), "Café Title"); - let other = add(&mut s, frame, NodeKind::Text(TextData::new("Other")), "Title"); + let title = add(&mut s, frame, NodeKind::Text(TextData::new("HÉLLO 世界").into()), "Café Title"); + let other = add(&mut s, frame, NodeKind::Text(TextData::new("Other").into()), "Title"); let rect = add(&mut s, page, NodeKind::Rectangle, "HÉLLO 世界"); found(&mut s, json!({"name": "CAFÉ"}), &[frame, title]); found(&mut s, json!({"name": "[cArD]"}), &[frame]); @@ -39,7 +39,7 @@ fn node_find_filters_are_literal_case_insensitive_and_anded() { fn node_find_matches_a_greek_final_sigma_both_ways() { let mut s = Session::new(); let page = s.page().unwrap(); - let os = add(&mut s, page, NodeKind::Text(TextData::new("ΛΟΓΟΣ")), "ΟΣ"); + let os = add(&mut s, page, NodeKind::Text(TextData::new("ΛΟΓΟΣ").into()), "ΟΣ"); found(&mut s, json!({"name": "Σ"}), &[os]); found(&mut s, json!({"name": "ς"}), &[os]); found(&mut s, json!({"text": "λογοσ"}), &[os]); @@ -85,7 +85,7 @@ fn node_find_instances_match_main_name_and_visit_actual_children_only() { let page = s.page().unwrap(); let main = add(&mut s, page, NodeKind::Component { description: String::new(), props: Default::default(), prop_order: Vec::new() }, "CAFÉ [Button]"); - let original = add(&mut s, main, NodeKind::Text(TextData::new("Original")), "Original"); + let original = add(&mut s, main, NodeKind::Text(TextData::new("Original").into()), "Original"); let inst = idv(&ex(&mut s, "instance.create", json!({"component": main}))); let child = s.doc().unwrap().get(inst).unwrap().children[0]; ex(&mut s, "node.set", json!({"ids": [inst], "props": {"name": "Copy"}})); @@ -142,7 +142,7 @@ fn node_find_accepts_every_canonical_type() { NodeKind::Star { count: 5, inner_ratio: 0.5 }, NodeKind::Line, NodeKind::Vector { network: Default::default() }, - NodeKind::Text(TextData::new("Text")), + NodeKind::Text(TextData::new("Text").into()), NodeKind::BooleanOp { op: BoolOp::Union }, NodeKind::Component { description: String::new(), props: Default::default(), prop_order: Vec::new() }, NodeKind::ComponentSet { description: String::new() }, diff --git a/crates/engine/src/penpot_export_tests.rs b/crates/engine/src/penpot_export_tests.rs index 0e4b15c73..f19eb1d6f 100644 --- a/crates/engine/src/penpot_export_tests.rs +++ b/crates/engine/src/penpot_export_tests.rs @@ -98,7 +98,7 @@ fn missing_provider_fonts_stay_offline_and_text_stays_editable() { let page = source.first_page().unwrap(); let mut text = figcraft_doc::TextData::new("Offline text"); text.style.font_family = "FigCraft Missing Provider Q7".into(); - source.create(page, NodeKind::Text(text), "Label", 0.0, 0.0, 200.0, 30.0).unwrap(); + source.create(page, NodeKind::Text(text.into()), "Label", 0.0, 0.0, 200.0, 30.0).unwrap(); let bytes = figcraft_format::penpot::export(&source).unwrap().0; let data = base64::engine::general_purpose::STANDARD.encode(bytes); for command in ["file.open", "file.import"] { diff --git a/crates/engine/src/shapes_behaviour_tests.rs b/crates/engine/src/shapes_behaviour_tests.rs index d7d35be27..8a10aa3de 100644 --- a/crates/engine/src/shapes_behaviour_tests.rs +++ b/crates/engine/src/shapes_behaviour_tests.rs @@ -236,7 +236,7 @@ fn corner_smoothing_follows_the_documented_rules() { (NodeKind::Star { count: 5, inner_ratio: 0.4 }, true, "stars"), ( NodeKind::Vector { - network: figcraft_doc::VectorNetwork::from_points(&[Point::ZERO, Point::new(10.0, 0.0), Point::new(10.0, 10.0)], true), + network: figcraft_doc::VectorNetwork::from_points(&[Point::ZERO, Point::new(10.0, 0.0), Point::new(10.0, 10.0)], true).into(), }, true, "vector networks that are closed shapes", diff --git a/crates/engine/src/text_metrics_local_tests.rs b/crates/engine/src/text_metrics_local_tests.rs index 34f25fac6..77d47e317 100644 --- a/crates/engine/src/text_metrics_local_tests.rs +++ b/crates/engine/src/text_metrics_local_tests.rs @@ -46,7 +46,7 @@ fn local_samples_wrap_at_their_saved_line_breaks() { continue; } wrapped += usize::from(!saved.starts.is_empty()); - let plain = figcraft_doc::TextData { saved_breaks: None, ..t.clone() }; + let plain = figcraft_doc::TextData { saved_breaks: None, ..(**t).clone() }; let (own, hinted) = (soft_starts(&plain, n.width), soft_starts(t, n.width)); differed_before += usize::from(own != saved.starts); if t.saved_breaks_for(n.width).is_none() { diff --git a/crates/engine/src/vector_behaviour_tests.rs b/crates/engine/src/vector_behaviour_tests.rs index 48fab9c6e..7ab1f08a9 100644 --- a/crates/engine/src/vector_behaviour_tests.rs +++ b/crates/engine/src/vector_behaviour_tests.rs @@ -323,7 +323,7 @@ fn ex_to_vector(doc: &mut figcraft_doc::Document, id: NodeId) { let (path, _) = figcraft_render::node_outline(doc, n).unwrap(); let mut network = VectorNetwork::from_path(&path); network.regions[0].fills = Some(vec![figcraft_color::Paint::solid(figcraft_color::Color::BLACK)]); - doc.get_mut(id).unwrap().kind = NodeKind::Vector { network }; + doc.get_mut(id).unwrap().kind = NodeKind::Vector { network: network.into() }; } /// How far `path` strays from `from`: the largest distance from a point sampled along `path` to @@ -365,7 +365,7 @@ fn simplify_keeps_nearly_collinear_points_near_them() { { let n = s.doc_mut().unwrap().get_mut(id).unwrap(); n.transform = figcraft_geom::Affine::IDENTITY; - n.kind = NodeKind::Vector { network }; + n.kind = NodeKind::Vector { network: network.into() }; } let before = net(&s, id); ex(&mut s, "vector.simplify", json!({"ids": [id], "tolerance": 0.75})); diff --git a/crates/engine/src/vector_fill_rule_tests.rs b/crates/engine/src/vector_fill_rule_tests.rs index eb462ab22..90df92159 100644 --- a/crates/engine/src/vector_fill_rule_tests.rs +++ b/crates/engine/src/vector_fill_rule_tests.rs @@ -16,7 +16,7 @@ fn ex(s: &mut Session, cmd: &str, p: Value) -> Value { fn net(s: &Session, id: NodeId) -> VectorNetwork { match &s.doc().unwrap().node(id).unwrap().kind { - NodeKind::Vector { network } => network.clone(), + NodeKind::Vector { network } => (**network).clone(), other => panic!("not a vector: {other:?}"), } } @@ -46,7 +46,7 @@ fn vector_layer(s: &mut Session, network: VectorNetwork) -> NodeId { { let doc = s.doc_mut().unwrap(); match &mut doc.get_mut(id).unwrap().kind { - NodeKind::Vector { network: net } => *net = network, + NodeKind::Vector { network: net } => *net = network.into(), other => panic!("not a vector: {other:?}"), } } @@ -183,7 +183,7 @@ fn the_rule_switches_every_area_or_only_the_one_asked_for() { { let doc = s.doc_mut().unwrap(); match &mut doc.get_mut(id).unwrap().kind { - NodeKind::Vector { network } => *network = two, + NodeKind::Vector { network } => *network = two.into(), other => panic!("not a vector: {other:?}"), } } diff --git a/crates/format/src/fig/assets_tests.rs b/crates/format/src/fig/assets_tests.rs index 7fffa15cd..f2b7e5dfa 100644 --- a/crates/format/src/fig/assets_tests.rs +++ b/crates/format/src/fig/assets_tests.rs @@ -136,7 +136,7 @@ fn themed() -> Document { ], ); }); - add(&mut doc, frame, NodeKind::Text(TextData::new("Hello")), "Title", (10.0, 80.0), (60.0, 20.0), &|n| { + add(&mut doc, frame, NodeKind::Text(TextData::new("Hello").into()), "Title", (10.0, 80.0), (60.0, 20.0), &|n| { n.fills = vec![solid(0.0, 0.0, 0.0)]; bind( n, @@ -218,7 +218,7 @@ fn same_after_round_trip(doc: &Document, what: &str) -> Vec { let mut styles = d.styles.clone(); for s in &mut styles { // Held the way a layer's paints and text are. - let mut n = Node::new(NodeId(0), NodeKind::Text(TextData::new("")), "", 0.0, 0.0); + let mut n = Node::new(NodeId(0), NodeKind::Text(TextData::new("").into()), "", 0.0, 0.0); match &mut s.kind { StyleKind::Paint { paints } => { n.fills = std::mem::take(paints); @@ -231,8 +231,8 @@ fn same_after_round_trip(doc: &Document, what: &str) -> Vec { } n.fills.clear(); normalize(&mut n, &|i| i); - if let NodeKind::Text(td) = n.kind { - *style = td.style; + if let NodeKind::Text(td) = &n.kind { + *style = td.style.clone(); } } _ => {} @@ -466,7 +466,7 @@ fn styled() -> Document { }); let mut td = TextData::new("Title"); td.style = heading; - add(&mut doc, frame, NodeKind::Text(td), "Title", (10.0, 80.0), (100.0, 32.0), &|n| { + add(&mut doc, frame, NodeKind::Text(td.into()), "Title", (10.0, 80.0), (100.0, 32.0), &|n| { n.fills = vec![solid(0.0, 0.0, 0.0)]; n.styles.text = Some("s-text".into()); }); @@ -568,7 +568,7 @@ fn sized() -> (Document, [NodeId; 3]) { add(&mut doc, main, NodeKind::Rectangle, "Box", (10.0, 10.0), (40.0, 40.0), &|n| { n.constraints = Constraints { horizontal: HConstraint::Scale, vertical: VConstraint::Scale }; }); - add(&mut doc, main, NodeKind::Text(TextData::new("Card")), "Label", (56.0, 20.0), (32.0, 16.0), &|_| {}); + add(&mut doc, main, NodeKind::Text(TextData::new("Card").into()), "Label", (56.0, 20.0), (32.0, 16.0), &|_| {}); let mut g = Gen { r: Lcg(1), doc, image: String::new(), frames: Vec::new(), layers: Vec::new() }; let insts = [(); 3].map(|_| g.instance(main, page, BTreeMap::new())); let mut doc = g.doc; @@ -671,7 +671,7 @@ fn layers_bound_like_their_mains_are_no_overrides_in_another_mode() { n.bound.insert("fill".into(), "v-bg".into()); }, ); - add(&mut doc, main, NodeKind::Text(TextData::new("Chip")), "Chip label", (8.0, 6.0), (40.0, 16.0), &|n| { + add(&mut doc, main, NodeKind::Text(TextData::new("Chip").into()), "Chip label", (8.0, 6.0), (40.0, 16.0), &|n| { n.fills = vec![solid(0.0, 0.0, 0.0)]; n.bound.insert("fill".into(), "v-fg".into()); }); @@ -1266,7 +1266,7 @@ fn checkbox_variable_and_conditional_actions_round_trip() { let frame = doc.create(page, NodeKind::Frame, "Checkbox demo", 0.0, 0.0, 320.0, 180.0).unwrap(); let toggle = doc.create(frame, NodeKind::Frame, "Toggle checkbox", 24.0, 24.0, 44.0, 44.0).unwrap(); let mark = doc.create(toggle, NodeKind::Rectangle, "Checked indicator", 12.0, 12.0, 20.0, 20.0).unwrap(); - let label = doc.create(frame, NodeKind::Text(TextData::new("Unchecked")), "Status", 84.0, 36.0, 120.0, 20.0).unwrap(); + let label = doc.create(frame, NodeKind::Text(TextData::new("Unchecked").into()), "Status", 84.0, 36.0, 120.0, 20.0).unwrap(); doc.node_mut(mark).unwrap().bound.insert("visible".into(), "checked".into()); doc.node_mut(label).unwrap().bound.insert("characters".into(), "status".into()); let set_status = |value| Action::SetVariable { variable: "status".into(), value: json!(value), expr: None }; diff --git a/crates/format/src/fig/board_import_tests.rs b/crates/format/src/fig/board_import_tests.rs index fb4d4ba30..bff5ad32f 100644 --- a/crates/format/src/fig/board_import_tests.rs +++ b/crates/format/src/fig/board_import_tests.rs @@ -574,7 +574,7 @@ fn a_jam_diamond_is_a_native_shape_drawn_by_figcraft() { assert_eq!(frame.children.len(), 2, "the outline and the text: {warnings:?}"); let outline = doc.node(frame.children[0]).unwrap(); let NodeKind::Vector { network } = &outline.kind else { panic!("{:?}", outline.kind) }; - assert_eq!(*network, figcraft_doc::VectorNetwork::from_path(&figcraft_doc::BoardShape::Diamond.path(240.0, 240.0))); + assert_eq!(*network, figcraft_doc::VectorNetwork::from_path(&figcraft_doc::BoardShape::Diamond.path(240.0, 240.0)).into()); assert_eq!(outline.fills[0].solid_color().unwrap().to_rgba8(), [255, 191, 64, 255]); assert!(outline.child_layout.absolute); assert_eq!(outline.constraints.horizontal, figcraft_doc::HConstraint::Scale); @@ -596,7 +596,7 @@ fn a_jam_shape_past_the_size_cap_draws_its_outline_at_the_cap() { assert_eq!((frame.width, frame.height), (1e6, 1e6)); let outline = doc.node(frame.children[0]).unwrap(); let NodeKind::Vector { network } = &outline.kind else { panic!("{:?}", outline.kind) }; - assert_eq!(*network, figcraft_doc::VectorNetwork::from_path(&figcraft_doc::BoardShape::Diamond.path(1e6, 1e6))); + assert_eq!(*network, figcraft_doc::VectorNetwork::from_path(&figcraft_doc::BoardShape::Diamond.path(1e6, 1e6)).into()); } /// 23 of FigJam's 30 shape kinds have a FigCraft outline; the other 7 stay frames and say which. diff --git a/crates/format/src/fig/export/assets.rs b/crates/format/src/fig/export/assets.rs index 16850dfdc..65b5d2083 100644 --- a/crates/format/src/fig/export/assets.rs +++ b/crates/format/src/fig/export/assets.rs @@ -200,7 +200,7 @@ impl<'d> Exporter<'d> { } else { let mut sample = Node::new(NodeId(0), NodeKind::Rectangle, "", 0.0, 0.0); if let StyleKind::Text { style, .. } = &st.kind { - sample.kind = NodeKind::Text(TextData { style: style.as_text_style(), ..TextData::new("Ag") }); + sample.kind = NodeKind::Text((TextData { style: style.as_text_style(), ..TextData::new("Ag") }).into()); } sample.bound.clone_from(&st.bound); self.bound(&sample) diff --git a/crates/format/src/fig/export/common.rs b/crates/format/src/fig/export/common.rs index 904b1b120..3feee81b7 100644 --- a/crates/format/src/fig/export/common.rs +++ b/crates/format/src/fig/export/common.rs @@ -50,7 +50,7 @@ pub(super) fn outlined(n: &Node) -> Option<(Node, String)> { r.winding = WindingRule::NonZero; } let mut v = n.clone(); - v.kind = NodeKind::Vector { network }; + v.kind = NodeKind::Vector { network: network.into() }; v.fills = std::mem::take(&mut v.strokes); v.stroke = Default::default(); v.styles.fill = v.styles.stroke.take(); diff --git a/crates/format/src/fig/export/layer.rs b/crates/format/src/fig/export/layer.rs index 0e5c678d6..1dcb77f03 100644 --- a/crates/format/src/fig/export/layer.rs +++ b/crates/format/src/fig/export/layer.rs @@ -1,8 +1,8 @@ use super::common::{export_setting, layout_grid, outlined, prop_type, variant_pairs}; use super::{ AUX, AutoLayout, BoolOp, Bound, ContentAlign, CrossAlign, Exporter, Fields, HConstraint, Kv, LAYERS, LayoutMode, MAX_DEPTH, MainAlign, MaskType, - Node, NodeId, NodeKind, STASH, Sizing, TextData, TextStyle, VConstraint, WindingRule, arr, b, blend_name, color, e, fl, grid_sizing, guid, int, - matrix, o, position, root_fields, s, u, xy, + Node, NodeId, NodeKind, STASH, Sizing, VConstraint, WindingRule, arr, b, blend_name, color, e, fl, grid_sizing, guid, int, matrix, o, position, + root_fields, s, u, xy, }; impl<'d> Exporter<'d> { @@ -219,7 +219,13 @@ impl<'d> Exporter<'d> { // Text whose own style sets fills paints with them (the layer's fills only show through // runs); a variable bound to the layer's fill colours the layer's. let fills = match &n.kind { - NodeKind::Text(TextData { style: TextStyle { fills: Some(own), .. }, .. }) => self.paints(own, true, &Bound::default()), + NodeKind::Text(t) if t.style.fills.is_some() => { + if let Some(own) = &t.style.fills { + self.paints(own, true, &Bound::default()) + } else { + self.paints(&n.fills, true, &bound) + } + } _ => self.paints(&n.fills, true, &bound), }; let strokes = self.paints(&n.strokes, false, &bound); diff --git a/crates/format/src/fig/export_slot_tests.rs b/crates/format/src/fig/export_slot_tests.rs index 72da737a4..46d9e9a71 100644 --- a/crates/format/src/fig/export_slot_tests.rs +++ b/crates/format/src/fig/export_slot_tests.rs @@ -35,7 +35,7 @@ fn slots_document_with(own_slot: bool) -> Document { ]); let main = doc.create(page, NodeKind::Component { description: String::new(), props, prop_order: Vec::new() }, "Card", 0.0, 0.0, 300.0, 160.0).unwrap(); - let label = doc.create(main, NodeKind::Text(TextData::new("Title")), "Label", 0.0, 0.0, 200.0, 20.0).unwrap(); + let label = doc.create(main, NodeKind::Text(TextData::new("Title").into()), "Label", 0.0, 0.0, 200.0, 20.0).unwrap(); doc.node_mut(label).unwrap().prop_refs.insert("characters".into(), "Label".into()); let slot = doc.create(main, NodeKind::Frame, "Content", 0.0, 30.0, 280.0, 100.0).unwrap(); doc.node_mut(slot).unwrap().prop_refs.insert("slot".into(), "Content".into()); @@ -65,7 +65,7 @@ fn slots_document_with(own_slot: bool) -> Document { n.prop_refs.clear(); n.overrides.insert("slot".into()); n.children.clear(); - doc.create(m, NodeKind::Text(TextData::new("Own")), "Own", 0.0, 0.0, 100.0, 20.0).unwrap(); + doc.create(m, NodeKind::Text(TextData::new("Own").into()), "Own", 0.0, 0.0, 100.0, 20.0).unwrap(); } } doc @@ -115,7 +115,7 @@ fn set_slots_document() -> Document { n.prop_refs.clear(); n.overrides.insert("slot".into()); n.children.clear(); - doc.create(slot, NodeKind::Text(TextData::new("Mine")), "Mine", 0.0, 0.0, 80.0, 20.0).unwrap(); + doc.create(slot, NodeKind::Text(TextData::new("Mine").into()), "Mine", 0.0, 0.0, 80.0, 20.0).unwrap(); doc } diff --git a/crates/format/src/fig/export_tests.rs b/crates/format/src/fig/export_tests.rs index 9cb417078..c91866a53 100644 --- a/crates/format/src/fig/export_tests.rs +++ b/crates/format/src/fig/export_tests.rs @@ -331,10 +331,10 @@ impl Gen { id } 8 => { - let id = self.node(parent, NodeKind::Vector { network: VectorNetwork::default() }, "Vector"); + let id = self.node(parent, NodeKind::Vector { network: VectorNetwork::default().into() }, "Vector"); let n = self.doc.node_mut(id).unwrap(); let net = network(&mut self.r, n.width, n.height); - n.kind = NodeKind::Vector { network: net }; + n.kind = NodeKind::Vector { network: net.into() }; if self.r.chance(40) { (n.stroke.cap_start, n.stroke.cap_end) = (StrokeCap::None, StrokeCap::LineArrow); } @@ -342,7 +342,7 @@ impl Gen { } 9 => { let td = text_data(&mut self.r); - self.node(parent, NodeKind::Text(td), "Text") + self.node(parent, NodeKind::Text(td.into()), "Text") } 10 if on_page => { let id = self.doc.alloc_id(); @@ -412,7 +412,7 @@ impl Gen { fn components(&mut self, page: NodeId) { let comp = self.node(page, NodeKind::Component { description: "A button".into(), props: BTreeMap::new(), prop_order: Vec::new() }, "Button"); let icon = self.node(comp, NodeKind::Rectangle, "Icon"); - let label = self.node(comp, NodeKind::Text(TextData::new("Label")), "Label"); + let label = self.node(comp, NodeKind::Text(TextData::new("Label").into()), "Label"); { let n = self.doc.node_mut(comp).unwrap(); if let NodeKind::Component { props, .. } = &mut n.kind { @@ -855,10 +855,10 @@ fn vector_region_paints_round_trip() { let gradient = Paint::gradient(Gradient::default_for(GradientKind::Linear, Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 })); two.regions[0].fills = Some(vec![half, gradient]); two.regions[1].fills = Some(Vec::new()); - let id = doc.create(page, NodeKind::Vector { network: two }, "Painted", 0.0, 0.0, 100.0, 100.0).unwrap(); + let id = doc.create(page, NodeKind::Vector { network: two.into() }, "Painted", 0.0, 0.0, 100.0, 100.0).unwrap(); doc.node_mut(id).unwrap().fills = vec![Paint::solid(Color::BLACK)]; let inherit = VectorNetwork::from_points(&square, true); - let id2 = doc.create(page, NodeKind::Vector { network: inherit }, "Inherits", 0.0, 0.0, 100.0, 100.0).unwrap(); + let id2 = doc.create(page, NodeKind::Vector { network: inherit.into() }, "Inherits", 0.0, 0.0, 100.0, 100.0).unwrap(); doc.node_mut(id2).unwrap().fills = vec![Paint::solid(Color::BLACK)]; let (back, warnings) = round_trip(&doc, "region paints"); @@ -956,7 +956,7 @@ fn closed_vector_geometry_is_written_with_its_corner_smoothing() { for (v, r) in network.vertices.iter_mut().zip([20.0, 0.0, 10.0, 0.0]) { v.radius = r; } - let id = doc.create(page, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 100.0).unwrap(); + let id = doc.create(page, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 100.0, 100.0).unwrap(); doc.node_mut(id).unwrap().strokes = vec![Paint::solid(Color::BLACK)]; // The vector's written fill and stroke outlines. let outlines = |doc: &Document| -> Vec> { @@ -999,7 +999,7 @@ fn sharp_points_on_a_rounded_vector_stay_sharp() { for (v, r) in network.vertices.iter_mut().zip([8.0, 0.0, 8.0, 0.0]) { v.radius = r; } - let id = doc.create(page, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 100.0).unwrap(); + let id = doc.create(page, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 100.0, 100.0).unwrap(); doc.node_mut(id).unwrap().corners.radii = [8.0; 4]; let (back, _) = round_trip(&doc, "sharp point"); let v = back.nodes().find(|n| matches!(n.kind, NodeKind::Vector { .. })).unwrap(); @@ -1474,7 +1474,7 @@ fn set_with_properties() -> (Document, NodeId) { let v = doc .create(set, NodeKind::Component { description: String::new(), props, prop_order: Vec::new() }, name, 0.0, 60.0 * i as f64, 120.0, 40.0) .unwrap(); - let label = doc.create(v, NodeKind::Text(TextData::new("Button")), "Label", 0.0, 0.0, 60.0, 20.0).unwrap(); + let label = doc.create(v, NodeKind::Text(TextData::new("Button").into()), "Label", 0.0, 0.0, 60.0, 20.0).unwrap(); doc.node_mut(label).unwrap().prop_refs.insert("characters".into(), "Label".into()); // The icon is an instance placed in the variant: like the editor's, its `source` is its // main, which the binding doesn't belong to. @@ -1736,7 +1736,7 @@ fn text_with_thousands_of_distinct_styles_exports_in_linear_time() { td.runs = (0..20_000) .map(|i| StyleRun { start: i, end: i + 1, style: TextStyle { font_size: 8.0 + i as f64 / 100.0, ..TextStyle::default() } }) .collect(); - doc.create(p, NodeKind::Text(td), "T", 0.0, 0.0, 100.0, 100.0).unwrap(); + doc.create(p, NodeKind::Text(td.into()), "T", 0.0, 0.0, 100.0, 100.0).unwrap(); let start = std::time::Instant::now(); let (bytes, _) = export(&doc, None).unwrap(); assert!(!bytes.is_empty()); diff --git a/crates/format/src/fig/interop_tests.rs b/crates/format/src/fig/interop_tests.rs index 4ad81cebc..95967392e 100644 --- a/crates/format/src/fig/interop_tests.rs +++ b/crates/format/src/fig/interop_tests.rs @@ -34,7 +34,7 @@ fn sample() -> Document { n.stroke.weight = 2.0; n.stroke.align = StrokeAlign::Center; }); - add(&mut doc, frame, NodeKind::Text(TextData::new("One\nTwo")), "Text", 60.0, 40.0, &|_| {}); + add(&mut doc, frame, NodeKind::Text(TextData::new("One\nTwo").into()), "Text", 60.0, 40.0, &|_| {}); doc } diff --git a/crates/format/src/fig/text_list_tests.rs b/crates/format/src/fig/text_list_tests.rs index ef0439694..5fa9bfe02 100644 --- a/crates/format/src/fig/text_list_tests.rs +++ b/crates/format/src/fig/text_list_tests.rs @@ -77,7 +77,7 @@ fn the_export_writes_where_a_list_starts() { let mut td = figcraft_doc::TextData::new("two\nthree\nplain\nsix\ndot"); let pl = |list, start_offset| ParaList { list, indent: 0, start_offset, ..ParaList::default() }; td.paragraphs = vec![pl(N, 1), pl(N, 0), pl(P, 0), pl(N, 5), pl(B, 4)]; - doc.create(page, NodeKind::Text(td), "List", 0.0, 0.0, 200.0, 80.0).unwrap(); + doc.create(page, NodeKind::Text(td.into()), "List", 0.0, 0.0, 200.0, 80.0).unwrap(); let (bytes, _) = super::super::export(&doc, None).unwrap(); let a = Archive::open(&bytes).unwrap(); let (schema, message) = decode_canvas(&a.canvas).unwrap(); diff --git a/crates/format/src/fig/text_skip_ink_tests.rs b/crates/format/src/fig/text_skip_ink_tests.rs index b5285e1b6..5c8b24c5e 100644 --- a/crates/format/src/fig/text_skip_ink_tests.rs +++ b/crates/format/src/fig/text_skip_ink_tests.rs @@ -181,7 +181,7 @@ fn export_writes_one_actual_node_value_and_complete_run_values_without_skip_only let mut skipped = text.style.clone(); skipped.set_look(|look| look.skip_ink = true); text.runs = vec![StyleRun { start: 1, end: 3, style: skipped }]; - doc.create(doc.first_page().unwrap(), NodeKind::Text(text), "Label", 0.0, 0.0, 100.0, 30.0).unwrap(); + doc.create(doc.first_page().unwrap(), NodeKind::Text(text.into()), "Label", 0.0, 0.0, 100.0, 30.0).unwrap(); let (bytes, warnings) = export(&doc, None).unwrap(); assert!(warnings.is_empty(), "skip-ink is supported: {warnings:?}"); @@ -203,14 +203,14 @@ fn export_writes_one_actual_node_value_and_complete_run_values_without_skip_only custom.style.set_look(|look| look.skip_ink = true); custom.style.set_look(|look| look.thickness = figcraft_doc::DecorationLength::Pixels(2.0)); let mut custom_doc = Document::new("Unsupported decoration"); - custom_doc.create(custom_doc.first_page().unwrap(), NodeKind::Text(custom), "Custom", 0.0, 0.0, 100.0, 30.0).unwrap(); + custom_doc.create(custom_doc.first_page().unwrap(), NodeKind::Text(custom.into()), "Custom", 0.0, 0.0, 100.0, 30.0).unwrap(); let (_, warnings) = export(&custom_doc, None).unwrap(); assert!(warnings.iter().any(|w| w.contains("text decoration looks")), "custom look warning missing: {warnings:?}"); let mut variable = TextData::new("x"); variable.style.variations.insert("wght".into(), 400.0); let mut variable_doc = Document::new("Variable font warning"); - variable_doc.create(variable_doc.first_page().unwrap(), NodeKind::Text(variable), "Variable", 0.0, 0.0, 100.0, 30.0).unwrap(); + variable_doc.create(variable_doc.first_page().unwrap(), NodeKind::Text(variable.into()), "Variable", 0.0, 0.0, 100.0, 30.0).unwrap(); let (_, warnings) = export(&variable_doc, None).unwrap(); assert!(warnings.iter().any(|w| w.contains("variable font settings")), "variation warning missing: {warnings:?}"); @@ -227,7 +227,15 @@ fn export_writes_one_actual_node_value_and_complete_run_values_without_skip_only bound: Default::default(), }); let id = linked_doc - .create(linked_doc.first_page().unwrap(), NodeKind::Text(TextData { style: local, ..TextData::new("x") }), "Label", 0.0, 0.0, 100.0, 30.0) + .create( + linked_doc.first_page().unwrap(), + NodeKind::Text((TextData { style: local, ..TextData::new("x") }).into()), + "Label", + 0.0, + 0.0, + 100.0, + 30.0, + ) .unwrap(); linked_doc.node_mut(id).unwrap().styles.text = Some("body".into()); let (bytes, warnings) = export(&linked_doc, None).unwrap(); @@ -259,7 +267,7 @@ fn skip_ink_without_an_underline_stays_out_of_the_look_and_exports_the_default() // ...and default native text writes the default, which reads back as the default look. let mut doc = Document::new("Plain"); - doc.create(doc.first_page().unwrap(), NodeKind::Text(TextData::new("x")), "Label", 0.0, 0.0, 100.0, 30.0).unwrap(); + doc.create(doc.first_page().unwrap(), NodeKind::Text(TextData::new("x").into()), "Label", 0.0, 0.0, 100.0, 30.0).unwrap(); let (bytes, _) = export(&doc, None).unwrap(); let archive = super::Archive::open(&bytes).unwrap(); let (schema, body) = super::decode_canvas(&archive.canvas).unwrap(); diff --git a/crates/format/src/large_tests.rs b/crates/format/src/large_tests.rs index 4934b7e2e..07586a8d2 100644 --- a/crates/format/src/large_tests.rs +++ b/crates/format/src/large_tests.rs @@ -26,7 +26,7 @@ fn large(screens: usize) -> Document { 32.0, ) .unwrap(); - let label = d.create(button, NodeKind::Text(TextData::new("OK")), "Label", 8.0, 8.0, 40.0, 16.0).unwrap(); + let label = d.create(button, NodeKind::Text(TextData::new("OK").into()), "Label", 8.0, 8.0, 40.0, 16.0).unwrap(); d.get_mut(label).unwrap().plugin_data.insert("agent".into(), "note".into()); for s in 0..screens { let screen = d.create(page, NodeKind::Frame, &format!("Screen {s}"), (s % 20) as f64 * 400.0, (s / 20) as f64 * 300.0, 360.0, 240.0).unwrap(); @@ -44,7 +44,7 @@ fn large(screens: usize) -> Document { t.align_h = TextAlignH::Center; t.paragraph_spacing = 4.0; t.features.insert("liga".into(), false); - NodeKind::Text(t) + NodeKind::Text(t.into()) } _ => NodeKind::Line, }; @@ -86,7 +86,7 @@ fn large(screens: usize) -> Document { n.source = Some(button); n.overrides.insert("fills".into()); n.prop_refs.insert("visible".into(), "Show".into()); - let l = d.create(inst, NodeKind::Text(TextData::new("Go")), "Label", 8.0, 8.0, 40.0, 16.0).unwrap(); + let l = d.create(inst, NodeKind::Text(TextData::new("Go").into()), "Label", 8.0, 8.0, 40.0, 16.0).unwrap(); d.get_mut(l).unwrap().source = Some(label); } d @@ -131,7 +131,7 @@ fn defaults_are_left_out_and_come_back() { let mut d = Document::new("Defaults"); let p = d.first_page().unwrap(); let r = d.create(p, NodeKind::Rectangle, "Plain", 5.0, 0.0, 10.0, 10.0).unwrap(); - let t = d.create(p, NodeKind::Text(TextData::new("Hi")), "Text", 0.0, 20.0, 10.0, 10.0).unwrap(); + let t = d.create(p, NodeKind::Text(TextData::new("Hi").into()), "Text", 0.0, 20.0, 10.0, 10.0).unwrap(); let v = to_json(&d).unwrap(); let node = |id: figcraft_doc::NodeId| v["nodes"][id.0.to_string()].as_object().unwrap().clone(); let plain = node(r); diff --git a/crates/format/src/penpot.rs b/crates/format/src/penpot.rs index c47b55b18..22a8237c7 100644 --- a/crates/format/src/penpot.rs +++ b/crates/format/src/penpot.rs @@ -3015,7 +3015,9 @@ fn layer_kind( // This parsing crate must not depend on the higher-level SVG/render crates. "svg-raw" => NodeKind::Frame, "circle" | "ellipse" => NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }, - "path" if v.get("content").and_then(Value::as_array).is_some_and(Vec::is_empty) => NodeKind::Vector { network: VectorNetwork::default() }, + "path" if v.get("content").and_then(Value::as_array).is_some_and(Vec::is_empty) => { + NodeKind::Vector { network: VectorNetwork::default().into() } + } "path" => match vector_bezpath(v, warnings) { Some(path) => { let local = shape_matrix(v, x, y, w, h).inverse() * Affine::translate((x, y)) * path; @@ -3029,14 +3031,14 @@ fn layer_kind( let local = Affine::translate(-origin.to_vec2()) * local; let network = VectorNetwork::from_path(&local); vector_source = Some(local); - NodeKind::Vector { network } + NodeKind::Vector { network: network.into() } } None => { warn(warnings, "A Penpot path could not be decoded; kept as a frame".into()); NodeKind::Frame } }, - "text" => NodeKind::Text(text_node(v)), + "text" => NodeKind::Text(text_node(v).into()), other => { warn(warnings, format!("Unsupported Penpot layer type '{other}': imported as frame")); NodeKind::Frame @@ -3363,7 +3365,7 @@ impl LayerImport<'_, '_> { && let Some(path) = vector_source && let Some(node) = self.doc.node_mut(created) { - node.kind = NodeKind::Vector { network: filled_network(&path) }; + node.kind = NodeKind::Vector { network: filled_network(&path).into() }; } let svg = v.get("svgAttrs"); let fill_rule = svg.and_then(|a| a.get("style")).and_then(|s| string(s, "fillRule")).or_else(|| svg.and_then(|a| string(a, "fillRule"))); diff --git a/crates/format/src/penpot/export_tests.rs b/crates/format/src/penpot/export_tests.rs index e3ad744ef..6388085c6 100644 --- a/crates/format/src/penpot/export_tests.rs +++ b/crates/format/src/penpot/export_tests.rs @@ -153,7 +153,7 @@ fn rectangles_ellipses_and_paths_keep_their_geometry() { add(&mut doc, p, NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }, "Circle", 0.0, 0.0, 30.0, 20.0); add(&mut doc, p, NodeKind::Star { count: 5, inner_ratio: 0.4 }, "Star", 200.0, 0.0, 50.0, 50.0); let network = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(40.0, 0.0), Point::new(40.0, 30.0)], false); - let line = add(&mut doc, p, NodeKind::Vector { network }, "Open", 300.0, 0.0, 40.0, 30.0); + let line = add(&mut doc, p, NodeKind::Vector { network: network.into() }, "Open", 300.0, 0.0, 40.0, 30.0); doc.node_mut(line).unwrap().strokes = vec![Paint::solid(Color::BLACK)]; let (back, e, _) = roundtrip(&doc); @@ -185,7 +185,7 @@ fn stroked_closed_vectors_are_written_with_their_corner_smoothing() { for v in &mut network.vertices { v.radius = 20.0; } - let id = add(&mut doc, p, NodeKind::Vector { network }, "Smoothed", 0.0, 0.0, 100.0, 100.0); + let id = add(&mut doc, p, NodeKind::Vector { network: network.into() }, "Smoothed", 0.0, 0.0, 100.0, 100.0); { let n = doc.node_mut(id).unwrap(); n.fills = vec![Paint::solid(Color::BLACK)]; @@ -266,7 +266,7 @@ fn open_path_caps_and_dotted_strokes_survive() { let mut doc = Document::new("Caps"); let p = page(&doc); let network = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(50.0, 0.0)], false); - let id = add(&mut doc, p, NodeKind::Vector { network }, "Arrow", 0.0, 0.0, 50.0, 1.0); + let id = add(&mut doc, p, NodeKind::Vector { network: network.into() }, "Arrow", 0.0, 0.0, 50.0, 1.0); { let n = doc.node_mut(id).unwrap(); n.strokes = vec![Paint::solid(Color::BLACK)]; @@ -398,7 +398,7 @@ fn edited_text_is_rebuilt_with_runs_and_styles() { bold.font_style = "Bold Italic".into(); bold.fills = Some(vec![Paint::solid(Color::from_hex("#ff0000").unwrap())]); text.runs.push(StyleRun { start: 6, end: 10, style: bold }); - let id = add(&mut doc, p, NodeKind::Text(text), "Copy", 0.0, 0.0, 200.0, 60.0); + let id = add(&mut doc, p, NodeKind::Text(text.into()), "Copy", 0.0, 0.0, 200.0, 60.0); doc.node_mut(id).unwrap().fills = vec![Paint::solid(Color::from_hex("#333333").unwrap())]; let (back, e, _) = roundtrip(&doc); diff --git a/crates/format/src/rest.rs b/crates/format/src/rest.rs index c2a8c962c..7e7c80422 100644 --- a/crates/format/src/rest.rs +++ b/crates/format/src/rest.rs @@ -628,13 +628,13 @@ impl<'a> Ctx<'a> { } } // Point counts aren't part of the documented JSON: the outline is exact when present. - "REGULAR_POLYGON" | "STAR" if point_count().is_none() && has_geometry => NodeKind::Vector { network: VectorNetwork::default() }, + "REGULAR_POLYGON" | "STAR" if point_count().is_none() && has_geometry => NodeKind::Vector { network: VectorNetwork::default().into() }, "REGULAR_POLYGON" => NodeKind::Polygon { count: point_count().unwrap_or_else(|| self.default_count(3)) }, "STAR" => NodeKind::Star { count: point_count().unwrap_or_else(|| self.default_count(5)), inner_ratio: num(j, "innerRadius").map_or(0.382, |r| r.clamp(0.01, 1.0)), }, - "VECTOR" => NodeKind::Vector { network: VectorNetwork::default() }, + "VECTOR" => NodeKind::Vector { network: VectorNetwork::default().into() }, "BOOLEAN_OPERATION" => NodeKind::BooleanOp { op: match text(j, "booleanOperation") { Some("SUBTRACT") => BoolOp::Subtract, @@ -643,7 +643,7 @@ impl<'a> Ctx<'a> { _ => BoolOp::Union, }, }, - "TEXT" => NodeKind::Text(text::text_data(self, j)), + "TEXT" => NodeKind::Text(text::text_data(self, j).into()), "COMPONENT" => NodeKind::Component { description: description(&self.component_meta, j), props: BTreeMap::new(), prop_order: Vec::new() }, "COMPONENT_SET" => NodeKind::ComponentSet { description: description(&self.set_meta, j) }, "SLICE" => NodeKind::Slice, @@ -830,7 +830,7 @@ impl<'a> Ctx<'a> { if let Some(net) = net { match net { Some(network) => { - n.kind = NodeKind::Vector { network }; + n.kind = NodeKind::Vector { network: network.into() }; return false; } None => self.warn("invalid or oversized vector networks import as outlines"), @@ -853,7 +853,7 @@ impl<'a> Ctx<'a> { for r in &mut network.regions { r.winding = winding; } - n.kind = NodeKind::Vector { network }; + n.kind = NodeKind::Vector { network: network.into() }; outline } @@ -963,7 +963,7 @@ impl<'a> Ctx<'a> { "grid" } StyleKind::Text { .. } => { - sample.kind = NodeKind::Text(text::text_data(self, node)); + sample.kind = NodeKind::Text(text::text_data(self, node).into()); "text" } }; diff --git a/crates/format/tests/it/range_hyperlink_round_trip.rs b/crates/format/tests/it/range_hyperlink_round_trip.rs index f47e22ae8..2b0935977 100644 --- a/crates/format/tests/it/range_hyperlink_round_trip.rs +++ b/crates/format/tests/it/range_hyperlink_round_trip.rs @@ -17,11 +17,11 @@ fn cleared_range_hyperlink_round_trip() { let mut text = TextData { characters: "AB".into(), ..Default::default() }; text.style.link = Some(url.clone()); text.restyle(1, 2, |style| style.link = None); - document.create(page, NodeKind::Text(text), "Cleared", 0.0, 0.0, 100.0, 30.0).unwrap(); + document.create(page, NodeKind::Text(text.into()), "Cleared", 0.0, 0.0, 100.0, 30.0).unwrap(); let mut control = TextData { characters: "AB".into(), ..Default::default() }; control.restyle(1, 2, |style| style.link = Some(url.clone())); - document.create(page, NodeKind::Text(control), "Explicit", 0.0, 40.0, 100.0, 30.0).unwrap(); + document.create(page, NodeKind::Text(control.into()), "Explicit", 0.0, 40.0, 100.0, 30.0).unwrap(); let expected = vec![Some(url.clone()), None]; assert_eq!(links(&document, "Cleared"), expected); diff --git a/crates/layout/src/behaviour_tests.rs b/crates/layout/src/behaviour_tests.rs index a17a563df..0869497d4 100644 --- a/crates/layout/src/behaviour_tests.rs +++ b/crates/layout/src/behaviour_tests.rs @@ -142,7 +142,7 @@ fn build(c: &Case<'_>) -> (Document, NodeId, Vec, FakeMeasure) { let mut texts = HashMap::new(); let mut ids = Vec::new(); for k in c.kids { - let kind = if k.text.is_some() { NodeKind::Text(TextData::new("T")) } else { NodeKind::Rectangle }; + let kind = if k.text.is_some() { NodeKind::Text(TextData::new("T").into()) } else { NodeKind::Rectangle }; let kid = d.create(id, kind, "K", k.at.0, k.at.1, k.size.0, k.size.1).unwrap(); let n = d.get_mut(kid).unwrap(); if let (Some(t), NodeKind::Text(td)) = (k.text, &mut n.kind) { diff --git a/crates/layout/src/lib.rs b/crates/layout/src/lib.rs index 1d77afe0d..2328e8cf1 100644 --- a/crates/layout/src/lib.rs +++ b/crates/layout/src/lib.rs @@ -134,7 +134,11 @@ pub fn set_size(doc: &mut Document, id: NodeId, w: f64, h: f64) { let sy = if oh > 1e-9 { h / oh } else { 1.0 }; match &mut n.kind { NodeKind::Vector { network } => network.scale(sx, sy), - NodeKind::Text(figcraft_doc::TextData { path: Some(tp), .. }) => tp.scale(sx, sy), + NodeKind::Text(t) if t.path.is_some() => { + if let Some(tp) = &mut t.path { + tp.scale(sx, sy); + } + } _ => {} } n.width = w; diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index df9dd73e5..332a28b42 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -181,7 +181,7 @@ impl Measure for FakeMeasure { } pub(super) fn text(d: &mut Document, parent: NodeId, name: &str) -> NodeId { - d.create(parent, NodeKind::Text(figcraft_doc::TextData::new(name)), name, 0.0, 0.0, 10.0, 10.0).unwrap() + d.create(parent, NodeKind::Text(figcraft_doc::TextData::new(name).into()), name, 0.0, 0.0, 10.0, 10.0).unwrap() } #[test] diff --git a/crates/pdf/src/export_tests.rs b/crates/pdf/src/export_tests.rs index d41f11379..adb3e06d7 100644 --- a/crates/pdf/src/export_tests.rs +++ b/crates/pdf/src/export_tests.rs @@ -147,7 +147,7 @@ fn text_hyperlinks_become_link_annotations() { linked.link = Some(URL.into()); // "docs" (chars 9..13) links. td.runs = vec![StyleRun { start: 9, end: 13, style: linked }]; - let t = d.create(f, NodeKind::Text(td), "T", 10.0, 10.0, 280.0, 40.0).unwrap(); + let t = d.create(f, NodeKind::Text(td.into()), "T", 10.0, 10.0, 280.0, 40.0).unwrap(); d.get_mut(t).unwrap().fills = vec![Paint::solid(Color::BLACK)]; let Some((layout, _)) = figcraft_text::layout_node(d.node(t).unwrap()) else { return }; if layout.glyphs.is_empty() { @@ -183,7 +183,7 @@ fn hostile_links_are_skipped() { td.style.link = Some(url.to_string()); // One off the page entirely. let x = if i == 2 { 500.0 } else { 0.0 }; - d.create(f, NodeKind::Text(td), "T", x, 0.0, 80.0, 20.0).unwrap(); + d.create(f, NodeKind::Text(td.into()), "T", x, 0.0, 80.0, 20.0).unwrap(); } let pdf = export_pdf(&d, &[f], &PdfOptions::default()).unwrap(); assert_eq!(text(&pdf).matches("/Subtype/Link").count(), 0); @@ -296,7 +296,7 @@ fn an_oversized_link_is_dropped_before_it_is_copied_per_line() { let mut td = TextData::new(words.trim_end()); td.style.font_size = 20.0; td.style.link = Some("https://example.com/".to_string() + &"a".repeat(1 << 20)); - let t = d.create(f, NodeKind::Text(td), "T", 10.0, 10.0, 280.0, 3980.0).unwrap(); + let t = d.create(f, NodeKind::Text(td.into()), "T", 10.0, 10.0, 280.0, 3980.0).unwrap(); d.get_mut(t).unwrap().fills = vec![Paint::solid(Color::BLACK)]; let pdf = export_pdf(&d, &[f], &PdfOptions::default()).unwrap(); assert_eq!(text(&pdf).matches("/Subtype/Link").count(), 0); diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 110bfa736..c2e9f2568 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -77,7 +77,7 @@ fn pdf_vector_region_paints_emit_independent_colors() { Region { loops: vec![vec![0, 1, 2, 3]], winding: WindingRule::NonZero, fills: Some(Vec::new()), ..Default::default() }, ], }; - let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 20.0, 10.0).unwrap(); + let id = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 20.0, 10.0).unwrap(); let content = inflated(&export_pdf(&d, &[id], &PdfOptions::default()).unwrap()); assert!(content.contains("1 0 0 rg") && content.contains("0 0 1 rg"), "{content}"); } @@ -94,7 +94,7 @@ fn pdf_vector_region_paints_draw_smoothed_corners() { network.regions[0].fills = Some(vec![Paint::solid(Color::from_hex("FF0000").unwrap())]); let mut d = Document::new("smoothing"); let p = d.first_page().unwrap(); - let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 100.0).unwrap(); + let id = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 100.0, 100.0).unwrap(); let content = |d: &Document| inflated(&export_pdf(d, &[id], &PdfOptions::default()).unwrap()); let plain = content(&d); d.get_mut(id).unwrap().corners.smoothing = 0.6; @@ -145,7 +145,7 @@ pub(crate) fn sample_doc() -> (Document, Vec) { // Text. let mut td = TextData::new("Hello PDF"); td.style.font_size = 24.0; - let t = d.create(f1, NodeKind::Text(td), "T", 16.0, 200.0, 280.0, 32.0).unwrap(); + let t = d.create(f1, NodeKind::Text(td.into()), "T", 16.0, 200.0, 280.0, 32.0).unwrap(); d.get_mut(t).unwrap().fills = vec![Paint::solid(Color::from_hex("111111").unwrap())]; // A child sticking out of the frame (clipped). d.create(f1, NodeKind::Rectangle, "Out", 280.0, 200.0, 100.0, 100.0).unwrap(); @@ -288,7 +288,7 @@ fn hostile_inputs_error_or_skip() { visible: true, }]; } - let t = d.create(f, NodeKind::Text(TextData::new("x")), "T", 0.0, 0.0, 10.0, 10.0).unwrap(); + let t = d.create(f, NodeKind::Text(TextData::new("x").into()), "T", 0.0, 0.0, 10.0, 10.0).unwrap(); if let NodeKind::Text(td) = &mut d.get_mut(t).unwrap().kind { td.style.font_size = f64::NAN; } diff --git a/crates/render/src/boolean_budget_tests.rs b/crates/render/src/boolean_budget_tests.rs index f13190678..0dcae7e6c 100644 --- a/crates/render/src/boolean_budget_tests.rs +++ b/crates/render/src/boolean_budget_tests.rs @@ -28,7 +28,7 @@ fn union_of_bars(n: usize) -> (Document, NodeId, NodeId) { for across in [true, false] { let network = VectorNetwork::from_path(&bars(n, across)); let len = n as f64 * 4.0; - d.create(b, NodeKind::Vector { network }, "Bars", 0.0, 0.0, len, len).unwrap(); + d.create(b, NodeKind::Vector { network: network.into() }, "Bars", 0.0, 0.0, len, len).unwrap(); } d.fit_to_children(b).unwrap(); (d, page, b) diff --git a/crates/render/src/boolean_cache_tests.rs b/crates/render/src/boolean_cache_tests.rs index 51e422425..a3e35a837 100644 --- a/crates/render/src/boolean_cache_tests.rs +++ b/crates/render/src/boolean_cache_tests.rs @@ -233,7 +233,7 @@ fn stroke_only_text_operands_use_glyphs_instead_of_the_text_box() { let b = d.create(page, NodeKind::BooleanOp { op: BoolOp::Union }, "B", 0.0, 0.0, 400.0, 100.0).unwrap(); let mut text = TextData::new("Hi"); text.style.font_size = 32.0; - let id = d.create(b, NodeKind::Text(text), "text", 0.0, 0.0, 400.0, 100.0).unwrap(); + let id = d.create(b, NodeKind::Text(text.into()), "text", 0.0, 0.0, 400.0, 100.0).unwrap(); let n = d.get_mut(id).unwrap(); n.fills.clear(); n.strokes = vec![Paint::solid(Color::BLACK)]; diff --git a/crates/render/src/lod_tests.rs b/crates/render/src/lod_tests.rs index d7cd983c9..223468d92 100644 --- a/crates/render/src/lod_tests.rs +++ b/crates/render/src/lod_tests.rs @@ -48,11 +48,11 @@ fn cards() -> (Document, NodeId) { } let mut title = TextData::new(format!("Card number {i}")); title.style.font_size = 16.0; - d.create(card, NodeKind::Text(title), "Title", 84.0, 36.0, 110.0, 20.0).unwrap(); + d.create(card, NodeKind::Text(title.into()), "Title", 84.0, 36.0, 110.0, 20.0).unwrap(); let mut body = TextData::new("Some body text that wraps onto a second line"); body.auto_resize = figcraft_doc::TextAutoResize::Height; body.style.font_size = 11.0; - d.create(card, NodeKind::Text(body), "Body", 84.0, 60.0, 110.0, 30.0).unwrap(); + d.create(card, NodeKind::Text(body.into()), "Body", 84.0, 60.0, 110.0, 30.0).unwrap(); } (d, page) } @@ -117,7 +117,7 @@ fn region_paints_disable_vector_and_ancestor_splatting() { let parent = d.create(page, NodeKind::Frame, "Parent", 0.0, 0.0, 4.0, 4.0).unwrap(); let mut network = VectorNetwork::default(); network.regions.push(Region { loops: Vec::new(), winding: Default::default(), fills: Some(Vec::new()), ..Default::default() }); - let vector = d.create(parent, NodeKind::Vector { network }, "Styled", 0.0, 0.0, 2.0, 2.0).unwrap(); + let vector = d.create(parent, NodeKind::Vector { network: network.into() }, "Styled", 0.0, 0.0, 2.0, 2.0).unwrap(); let node = d.node(vector).unwrap(); assert!(!lod::splattable(&d, node, 0)); assert!(!lod::splattable(&d, d.node(parent).unwrap(), 0)); @@ -251,7 +251,7 @@ fn greeked_text_stays_inside_its_bounds() { let p = d.first_page().unwrap(); let mut t = TextData::new("Greeked text on a line\nand a second line"); t.style.font_size = 20.0; - let id = d.create(p, NodeKind::Text(t), "T", 100.0, 100.0, 300.0, 60.0).unwrap(); + let id = d.create(p, NodeKind::Text(t.into()), "T", 100.0, 100.0, 300.0, 60.0).unwrap(); let n = d.node(id).unwrap(); assert!(lod::greeked(n, 0.1) && !lod::greeked(n, 0.5)); let v = View { origin: (0.0, 0.0), scale: 0.1, width: 60, height: 30 }; diff --git a/crates/render/src/paint_behaviour_tests.rs b/crates/render/src/paint_behaviour_tests.rs index 30c583d03..1de73777a 100644 --- a/crates/render/src/paint_behaviour_tests.rs +++ b/crates/render/src/paint_behaviour_tests.rs @@ -642,7 +642,7 @@ fn text_strokes_follow_their_alignment() { let (mut d, p) = page(); let mut td = figcraft_doc::TextData::new("I"); td.style.font_size = 120.0; - let t = d.create(p, NodeKind::Text(td), "T", 60.0, 30.0, 1.0, 1.0).unwrap(); + let t = d.create(p, NodeKind::Text(td.into()), "T", 60.0, 30.0, 1.0, 1.0).unwrap(); let n = d.get_mut(t).unwrap(); n.fills.clear(); n.strokes = vec![Paint::solid(hex("#000000"))]; diff --git a/crates/render/src/retained_edit_tests.rs b/crates/render/src/retained_edit_tests.rs index 7437a70ed..b711e70d7 100644 --- a/crates/render/src/retained_edit_tests.rs +++ b/crates/render/src/retained_edit_tests.rs @@ -114,7 +114,7 @@ fn ridge(d: &mut Document, page: NodeId, teeth: usize) -> NodeId { } pts.push(figcraft_geom::Point::new(240.0, 120.0)); let network = figcraft_doc::VectorNetwork::from_points(&pts, true); - let id = d.create(page, NodeKind::Vector { network }, "Ridge", 20.0, 20.0, 240.0, 120.0).unwrap(); + let id = d.create(page, NodeKind::Vector { network: network.into() }, "Ridge", 20.0, 20.0, 240.0, 120.0).unwrap(); d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::from_hex("7FAE9C").unwrap())]; id } diff --git a/crates/render/src/retained_tests.rs b/crates/render/src/retained_tests.rs index 103178542..7a0312d94 100644 --- a/crates/render/src/retained_tests.rs +++ b/crates/render/src/retained_tests.rs @@ -53,7 +53,7 @@ fn scene(cut_sensitive: bool) -> Scene { let mut td = TextData::new("A line of text that overflows its box"); td.auto_resize = TextAutoResize::None; td.style.font_size = 14.0; - let text = d.create(page, NodeKind::Text(td), "T", 20.0, 270.0, 60.0, 20.0).unwrap(); + let text = d.create(page, NodeKind::Text(td.into()), "T", 20.0, 270.0, 60.0, 20.0).unwrap(); if cut_sensitive { let inner = d.create(page, NodeKind::Rectangle, "Inner", 180.0, 150.0, 70.0, 50.0).unwrap(); solid(d.get_mut(inner).unwrap(), "FFFFFF"); @@ -277,7 +277,7 @@ fn overflowing_text_is_drawn_while_its_box_is_out_of_view() { let mut td = TextData::new("Overflowing far to the right of a one pixel box"); td.auto_resize = TextAutoResize::WidthAndHeight; td.style.font_size = 16.0; - let t = d.create(page, NodeKind::Text(td), "T", 100.0, 10.0, 1.0, 20.0).unwrap(); + let t = d.create(page, NodeKind::Text(td.into()), "T", 100.0, 10.0, 1.0, 20.0).unwrap(); let Some((layout, _)) = figcraft_text::layout_node(d.node(t).unwrap()) else { return }; if layout.glyphs.is_empty() || layout.width < 120.0 { return; // no fonts on this machine diff --git a/crates/render/src/rtl_list_tests.rs b/crates/render/src/rtl_list_tests.rs index 3dde82f32..c04dcc973 100644 --- a/crates/render/src/rtl_list_tests.rs +++ b/crates/render/src/rtl_list_tests.rs @@ -17,7 +17,7 @@ fn doc() -> (Document, NodeId, TextData) { td.auto_resize = TextAutoResize::Height; let mut d = Document::new("rtl"); let p = d.first_page().unwrap(); - let id = d.create(p, NodeKind::Text(td.clone()), "T", 0.0, 0.0, W, 40.0).unwrap(); + let id = d.create(p, NodeKind::Text(td.clone().into()), "T", 0.0, 0.0, W, 40.0).unwrap(); (d, id, td) } diff --git a/crates/render/src/shadow_silhouette_tests.rs b/crates/render/src/shadow_silhouette_tests.rs index 80dcf536a..d16ed9855 100644 --- a/crates/render/src/shadow_silhouette_tests.rs +++ b/crates/render/src/shadow_silhouette_tests.rs @@ -37,9 +37,9 @@ fn a_sharp_shadow_under_a_stroked_layer_has_no_light_line_along_the_layers_edge( // its outline) and, where a font loads, a letter. let notch = [(0.0, 0.0), (60.0, 0.0), (60.0, 60.0), (40.0, 60.0), (30.0, 20.0), (20.0, 60.0), (0.0, 60.0)].map(|(x, y)| Point::new(x, y)); let kinds = [ - ("notch", NodeKind::Vector { network: VectorNetwork::from_points(¬ch, true) }), + ("notch", NodeKind::Vector { network: VectorNetwork::from_points(¬ch, true).into() }), ("ellipse", NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }), - ("letter", NodeKind::Text(letter)), + ("letter", NodeKind::Text(letter.into())), ]; let shadow = hex("#000000").to_rgba8(); for (name, kind) in &kinds { diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 7de727dca..d539a675c 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -54,7 +54,7 @@ fn vector_regions_use_their_own_paints_and_empty_regions_do_not_erase() { Region { loops: vec![vec![0, 1, 2, 3]], winding: WindingRule::NonZero, fills: Some(vec![]), ..Default::default() }, ], }; - let id = d.create(page, NodeKind::Vector { network }, "V", 10.0, 10.0, 20.0, 10.0).unwrap(); + let id = d.create(page, NodeKind::Vector { network: network.into() }, "V", 10.0, 10.0, 20.0, 10.0).unwrap(); d.get_mut(id).unwrap().fills.clear(); let pix = render_view(&d, page, &view(40, 30), &Options { background: Some(Color::WHITE), ..Default::default() }).unwrap(); assert_eq!(px(&pix, 15, 15), [255, 0, 0, 255]); @@ -106,7 +106,7 @@ fn region_paint_space_preserves_gradient_image_and_pattern_placement() { region.paint_space = Some(RegionPaintSpace { width: 60.0, height: 30.0, transform: frame }); } let n = d.get_mut(id).unwrap(); - n.kind = NodeKind::Vector { network }; + n.kind = NodeKind::Vector { network: network.into() }; n.transform = Affine::IDENTITY; n.width = 120.0; n.height = 100.0; @@ -145,7 +145,7 @@ fn styled_vector_mask_unions_region_windings_and_excludes_unpainted_regions() { }); } network.regions = regions; - let mask = d.create(group, NodeKind::Vector { network }, "Mask", 0.0, 0.0, 60.0, 20.0).unwrap(); + let mask = d.create(group, NodeKind::Vector { network: network.into() }, "Mask", 0.0, 0.0, 60.0, 20.0).unwrap(); { let n = d.get_mut(mask).unwrap(); n.fills.clear(); @@ -182,7 +182,7 @@ fn inherited_paint_frames_keep_overlapping_regions_in_vector_masks() { paint_space: Some(figcraft_doc::RegionPaintSpace { width: 20.0, height: 20.0, transform: Affine::translate((x, 0.0)) }), }); } - let mask = d.create(group, NodeKind::Vector { network }, "Mask", 0.0, 0.0, 30.0, 20.0).unwrap(); + let mask = d.create(group, NodeKind::Vector { network: network.into() }, "Mask", 0.0, 0.0, 30.0, 20.0).unwrap(); let n = d.get_mut(mask).unwrap(); n.fills = vec![Paint::solid(Color::BLACK)]; n.is_mask = true; @@ -432,7 +432,7 @@ fn text_renders_something() { let p = d.first_page().unwrap(); let mut td = TextData::new("Hello"); td.style.font_size = 32.0; - d.create(p, NodeKind::Text(td), "T", 0.0, 0.0, 200.0, 50.0).unwrap(); + d.create(p, NodeKind::Text(td.into()), "T", 0.0, 0.0, 200.0, 50.0).unwrap(); let pix = render_view(&d, p, &view(200, 60), &Options { background: Some(Color::WHITE), ..Default::default() }).unwrap(); let dark = pix.data().as_chunks::<4>().0.iter().filter(|c| c[0] < 100).count(); if figcraft_text::find_face("Inter", "Regular").is_some() { @@ -455,7 +455,7 @@ fn colour_emoji_draw_their_pixels() { let mut td = TextData::new("\u{1F600}"); (td.style.font_family, td.style.font_style) = (family.clone(), style.clone()); td.style.font_size = 48.0; - d.create(p, NodeKind::Text(td), "T", 0.0, 0.0, 200.0, 64.0).unwrap(); + d.create(p, NodeKind::Text(td.into()), "T", 0.0, 0.0, 200.0, 64.0).unwrap(); let pix = render_view(&d, p, &view(100, 80), &Options { background: Some(Color::WHITE), ..Default::default() }).unwrap(); // The emoji is the only thing in this document that paints saturated colour. let coloured = pix diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index c12bb21ea..6bf349d24 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -420,7 +420,7 @@ fn path(cx: &mut Ctx, p: &usvg::Path, parent: NodeId, base: Affine) { if !filled { network.regions.clear(); } - NodeKind::Vector { network } + NodeKind::Vector { network: network.into() } }; let at = Affine::translate((bb.x0, bb.y0)); // Fill closes every subpath; a stroke only those that close themselves. A filled diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index 6f557fb13..5eeac0259 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -360,7 +360,7 @@ fn add_layer(cx: &mut Ctx, layer: TextLayer<'_, '_, '_>) { } td.normalize(); let name = if t.id().is_empty() { first.text.chars().take(64).collect() } else { layer_name(t.id(), "Text") }; - let mut n = Node::new(cx.doc.alloc_id(), NodeKind::Text(td), name, w, h); + let mut n = Node::new(cx.doc.alloc_id(), NodeKind::Text(td.into()), name, w, h); n.transform = transform; n.fills = base_fill; if let Some(st) = spans.first().and_then(|sp| sp.stroke()) { diff --git a/crates/svg/src/tests.rs b/crates/svg/src/tests.rs index 450373805..258a6749f 100644 --- a/crates/svg/src/tests.rs +++ b/crates/svg/src/tests.rs @@ -49,7 +49,7 @@ fn export_vector_region_paints_independently() { Region { loops: vec![vec![0, 1, 2, 3]], winding: WindingRule::NonZero, fills: Some(Vec::new()), ..Default::default() }, ], }; - let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 20.0, 10.0).unwrap(); + let id = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 20.0, 10.0).unwrap(); let svg = export_svg(&d, &[id], &SvgOptions::default()).unwrap(); assert!(svg.contains("#FF0000") && svg.contains("#0000FF"), "{svg}"); assert_eq!(svg.matches(" (Document, figcraft_doc::NodeId) { style.fills = Some(vec![Paint::solid(Color::from_hex("00FF00").unwrap())]); text.runs.push(StyleRun { start: 1, end: 2, style }); text.normalize(); - let id = d.create(page, NodeKind::Text(text), "Text", 0.0, 0.0, 100.0, 40.0).unwrap(); + let id = d.create(page, NodeKind::Text(text.into()), "Text", 0.0, 0.0, 100.0, 40.0).unwrap(); d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::BLACK)]; (d, id) } @@ -176,7 +176,7 @@ fn title_case_does_not_restart_words_across_fill_runs_in_live_text() { style.fills = Some(vec![Paint::solid(Color::from_hex("00FF00").unwrap())]); text.runs.push(StyleRun { start: 2, end: 3, style }); text.normalize(); - let id = d.create(page, NodeKind::Text(text), "Text", 0.0, 0.0, 200.0, 40.0).unwrap(); + let id = d.create(page, NodeKind::Text(text.into()), "Text", 0.0, 0.0, 200.0, 40.0).unwrap(); d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::BLACK)]; let svg = export_svg(&d, &[id], &SvgOptions { outline_text: false, ..SvgOptions::default() }).unwrap(); assert!(svg.contains(">He") && svg.contains(">l") && svg.contains(">lo"), "{svg}"); @@ -199,7 +199,7 @@ fn live_text_export_drops_xml_forbidden_control_characters() { text.runs.push(StyleRun { start: 5, end: 12, style }); text.normalize(); } - let id = d.create(page, NodeKind::Text(text), "Text", 0.0, 0.0, 600.0, 40.0).unwrap(); + let id = d.create(page, NodeKind::Text(text.into()), "Text", 0.0, 0.0, 600.0, 40.0).unwrap(); d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::BLACK)]; let svg = export_svg(&d, &[id], &SvgOptions { outline_text: false, ..SvgOptions::default() }).unwrap(); assert!(!svg.contains('\u{b}') && !svg.contains('\u{1}'), "{svg:?}"); @@ -223,7 +223,7 @@ fn ids_and_font_families_drop_xml_forbidden_control_characters() { let mut text = TextData::new(format!("a{junk}b")); text.style.font_size = 24.0; text.style.font_family = format!("Font{junk}<&\""); - let id = d.create(page, NodeKind::Text(text), &format!("Layer{junk}"), 0.0, 0.0, 600.0, 40.0).unwrap(); + let id = d.create(page, NodeKind::Text(text.into()), &format!("Layer{junk}"), 0.0, 0.0, 600.0, 40.0).unwrap(); d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::BLACK)]; let svg = export_svg(&d, &[id], &SvgOptions { outline_text: false, include_ids: true, ..SvgOptions::default() }).unwrap(); assert!(!svg.contains(forbidden), "{svg:?}"); @@ -267,7 +267,7 @@ fn point_joins_equal_to_the_layer_join_keep_a_plain_stroke() { } let mut d = Document::new("t"); let p = d.first_page().unwrap(); - let v = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 50.0).unwrap(); + let v = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 100.0, 50.0).unwrap(); let n = d.get_mut(v).unwrap(); n.strokes = vec![Paint::solid(Color::from_hex("000000").unwrap())]; n.stroke.weight = 2.0; @@ -397,7 +397,7 @@ fn a_dash_cap_writes_the_line_cap_of_a_dashed_stroke() { fn a_dashed_line_exports_as_the_canvas_draws_it() { let line = Segment::line(0, 1); let open = VectorNetwork { vertices: vec![Vertex::new(0.0, 0.0), Vertex::new(107.0, 0.0)], segments: vec![line], ..Default::default() }; - let svg = dashed(NodeKind::Vector { network: open }, vec![10.0, 10.0]); + let svg = dashed(NodeKind::Vector { network: open.into() }, vec![10.0, 10.0]); assert_eq!(dash_attrs(&svg), [("10.7 10.7".to_string(), Some("5.35".to_string()))], "{svg}"); } @@ -415,7 +415,7 @@ fn each_subpath_of_a_dashed_vector_exports_its_own_fit() { segments: vec![Segment::line(0, 1), Segment::line(2, 3)], ..Default::default() }; - let svg = dashed(NodeKind::Vector { network: two }, vec![10.0, 10.0]); + let svg = dashed(NodeKind::Vector { network: two.into() }, vec![10.0, 10.0]); assert_eq!(dash_attrs(&svg).len(), 2, "{svg}"); } diff --git a/crates/text/src/onpath_tests.rs b/crates/text/src/onpath_tests.rs index f3bb999fb..e639e2c7b 100644 --- a/crates/text/src/onpath_tests.rs +++ b/crates/text/src/onpath_tests.rs @@ -68,7 +68,7 @@ fn laid_out_glyphs_sit_on_the_path() { let mid = g.warp * Point::new(g.x + g.advance * 0.25, g.y - 5.0); assert_eq!(l.hit(mid.x, mid.y), g.char_start); // A text node on a path keeps its box. - let mut n = figcraft_doc::Node::new(figcraft_doc::NodeId(1), figcraft_doc::NodeKind::Text(t), "t", 10.0, 1000.0); + let mut n = figcraft_doc::Node::new(figcraft_doc::NodeId(1), figcraft_doc::NodeKind::Text(t.into()), "t", 10.0, 1000.0); if let figcraft_doc::NodeKind::Text(t) = &mut n.kind { t.auto_resize = TextAutoResize::WidthAndHeight; } diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index d14b3a3c5..d03589243 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -315,16 +315,16 @@ fn vertical_alignment_in_fixed_box() { let mut t = TextData::new("Hi"); t.auto_resize = figcraft_doc::TextAutoResize::None; t.align_v = figcraft_doc::TextAlignV::Bottom; - let mut n = figcraft_doc::Node::new(figcraft_doc::NodeId(1), figcraft_doc::NodeKind::Text(t.clone()), "t", 100.0, 100.0); + let mut n = figcraft_doc::Node::new(figcraft_doc::NodeId(1), figcraft_doc::NodeKind::Text(t.clone().into()), "t", 100.0, 100.0); let (l, dy) = layout_node(&n).unwrap(); assert!((dy + l.height - 100.0).abs() < 1e-6); t.align_v = figcraft_doc::TextAlignV::Middle; - n.kind = figcraft_doc::NodeKind::Text(t.clone()); + n.kind = figcraft_doc::NodeKind::Text(t.clone().into()); let (l, dy) = layout_node(&n).unwrap(); assert!((dy - (100.0 - l.height) / 2.0).abs() < 1e-6); // Auto height ignores vertical alignment. t.auto_resize = figcraft_doc::TextAutoResize::Height; - n.kind = figcraft_doc::NodeKind::Text(t); + n.kind = figcraft_doc::NodeKind::Text(t.into()); assert_eq!(layout_node(&n).unwrap().1, 0.0); } diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index b82270937..e854a1630 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -868,7 +868,7 @@ mod caret_tests { use figcraft_doc::{Node, NodeId, NodeKind, StyleRun, TextData}; fn text(chars: &str, fills: Vec) -> Node { - let mut n = Node::new(NodeId(1), NodeKind::Text(TextData { characters: chars.into(), ..TextData::default() }), "Text", 100.0, 20.0); + let mut n = Node::new(NodeId(1), NodeKind::Text(TextData { characters: chars.into(), ..TextData::default() }.into()), "Text", 100.0, 20.0); n.fills = fills; n } diff --git a/crates/ui-egui/src/panels/typography/glyphs.rs b/crates/ui-egui/src/panels/typography/glyphs.rs index 5b379f4fa..f09cf1ead 100644 --- a/crates/ui-egui/src/panels/typography/glyphs.rs +++ b/crates/ui-egui/src/panels/typography/glyphs.rs @@ -272,7 +272,7 @@ mod tests { let id = doc.alloc_id(); let mut td = TextData::new("Hello world"); td.restyle(6, 11, |s| s.font_size = 40.0); - doc.insert(Node::new(id, NodeKind::Text(td), "t", 10.0, 10.0), page, None).unwrap(); + doc.insert(Node::new(id, NodeKind::Text(td.into()), "t", 10.0, 10.0), page, None).unwrap(); assert_eq!(target_styles(&doc, &[id], Some((id, 0, 5))).len(), 1); assert_eq!(target_styles(&doc, &[id], Some((id, 4, 8))).len(), 2); assert_eq!(target_styles(&doc, &[id], Some((id, 3, 3))).len(), 2); diff --git a/crates/ui-egui/src/region_fill_rows_tests.rs b/crates/ui-egui/src/region_fill_rows_tests.rs index 5d071bca3..247f3b0c1 100644 --- a/crates/ui-egui/src/region_fill_rows_tests.rs +++ b/crates/ui-egui/src/region_fill_rows_tests.rs @@ -34,7 +34,7 @@ pub(crate) fn two_region_vector(s: &mut Session) -> NodeId { square(&mut n, 60.0, 60.0, 80.0); n.regions = vec![Region { loops: vec![vec![0, 1, 2, 3]], ..Default::default() }, Region { loops: vec![vec![4, 5, 6, 7]], ..Default::default() }]; - node.kind = NodeKind::Vector { network: n }; + node.kind = NodeKind::Vector { network: n.into() }; node.transform = figcraft_geom::Affine::IDENTITY; node.fills = vec![figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE)]; figcraft_engine::vectoredit::refit(doc, id).unwrap(); diff --git a/crates/ui-egui/src/widgets/font_preview.rs b/crates/ui-egui/src/widgets/font_preview.rs index f465041e7..4b8c32050 100644 --- a/crates/ui-egui/src/widgets/font_preview.rs +++ b/crates/ui-egui/src/widgets/font_preview.rs @@ -73,7 +73,7 @@ fn render(ctx: &egui::Context, style: &TextStyle, text: &str, ppp: f64) -> Optio let id = doc.alloc_id(); let mut td = TextData::new(text); td.style = TextStyle { fills: None, link: None, style_id: None, ..style.clone() }; - let mut n = Node::new(id, NodeKind::Text(td), "preview", 1.0, 1.0); + let mut n = Node::new(id, NodeKind::Text(td.into()), "preview", 1.0, 1.0); n.fills = vec![Paint::solid(Color::WHITE)]; let (w, h) = figcraft_text::auto_size(&n)?; n.width = w.min(400.0); diff --git a/crates/vectordrawable/src/tests/shapes.rs b/crates/vectordrawable/src/tests/shapes.rs index e0f789ccf..2d29489cd 100644 --- a/crates/vectordrawable/src/tests/shapes.rs +++ b/crates/vectordrawable/src/tests/shapes.rs @@ -163,7 +163,7 @@ fn text_is_glyph_outlines_one_path_per_styled_run() { style.fills = Some(vec![Paint::solid(hex("00FF00"))]); text.runs.push(StyleRun { start: 1, end: 2, style }); text.normalize(); - let t = d.create(p, NodeKind::Text(text), "Text", 0.0, 0.0, 100.0, 40.0).unwrap(); + let t = d.create(p, NodeKind::Text(text.into()), "Text", 0.0, 0.0, 100.0, 40.0).unwrap(); d.get_mut(t).unwrap().fills = vec![Paint::solid(Color::BLACK)]; let out = export(&d, &[t], Compat::BestEffort); let fills: Vec<_> = paths_of(&out.xml).iter().map(|e| e.get("fillColor").unwrap().to_string()).collect(); From e9a5986e695399b92b9a9f8c08bf6423ca4480de Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 15:01:47 +0700 Subject: [PATCH 45/48] =?UTF-8?q?M8:=20a=20downscaled=20image=20is=20filte?= =?UTF-8?q?red,=20so=20fine=20detail=20doesn't=20turn=20into=20moir=C3=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An image fill shown at half its pixels or fewer (a 0.5x export, the canvas zoomed out) was sampled straight at that size with bicubic filtering and nothing averaging the pixels between samples, so fine detail aliased into moiré bands. It now draws from a copy averaged down to under twice the size it shows at (the image halved, or the canvas's smaller copy halved), cached like the canvas's copies. Every copy averages the finished pixels (premultiplied, after the image's adjustments) and is placed where the image itself would be; the size shown is measured on the axis showing the most device pixels, so an image squeezed on one axis by its crop or its layer keeps the other's pixels. Images shown larger draw as before. Fixes #2664. --- crates/render/src/downscaled_image_tests.rs | 140 ++++++++++++++++++++ crates/render/src/draw.rs | 6 +- crates/render/src/images.rs | 50 ++++++- crates/render/src/lib.rs | 2 + crates/render/src/paint.rs | 29 +++- docs/target-app-parity.md | 3 +- 6 files changed, 218 insertions(+), 12 deletions(-) create mode 100644 crates/render/src/downscaled_image_tests.rs diff --git a/crates/render/src/downscaled_image_tests.rs b/crates/render/src/downscaled_image_tests.rs new file mode 100644 index 000000000..fb5f12792 --- /dev/null +++ b/crates/render/src/downscaled_image_tests.rs @@ -0,0 +1,140 @@ +//! Downscaled images (#2664): an image shown at half its pixels or fewer is drawn from a copy +//! averaged down to under twice that size, so one-pixel detail blends into an even grey instead of +//! aliasing into moiré bands, on the canvas and in exports alike. + +use std::sync::Arc; + +use figcraft_color::{ImageScaleMode, Paint, PaintKind}; +use figcraft_doc::{Document, ImageData, NodeId, NodeKind}; +use figcraft_geom::Affine; + +use crate::{Options, Pixmap, View, encode_png, render_view}; + +/// The image's side: smaller than every canvas copy, so the canvas draws it from itself too. +const SIDE: u32 = 200; + +/// A `SIDE` × `SIDE` checkerboard of one-pixel black and white squares filling a box its size: the +/// document, its page and the box. +fn checkerboard_doc() -> (Document, NodeId, NodeId) { + let mut img = Pixmap::new(SIDE, SIDE).unwrap(); + for (i, c) in (0u32..).zip(img.data_mut().chunks_exact_mut(4)) { + let black = (i % SIDE + i / SIDE).is_multiple_of(2); + c.copy_from_slice(if black { &[0, 0, 0, 255] } else { &[255, 255, 255, 255] }); + } + let mut d = Document::new("downscaled"); + let page = d.first_page().unwrap(); + d.images.insert("fine".into(), ImageData { bytes: Arc::new(encode_png(&img).unwrap()), width: SIDE, height: SIDE }); + let r = d.create(page, NodeKind::Rectangle, "Image", 0.0, 0.0, f64::from(SIDE), f64::from(SIDE)).unwrap(); + d.get_mut(r).unwrap().fills = vec![Paint::image("fine", ImageScaleMode::Fill)]; + (d, page, r) +} + +/// The darkest and lightest red over the image's pixels (but a 2-pixel rim, where it meets the +/// background) drawn at `scale` from `origin`. +fn red_range(d: &Document, page: NodeId, scale: f64, origin: (f64, f64), opts: &Options) -> (u8, u8) { + let side = (f64::from(SIDE) * scale).floor() as u32; + let pix = render_view(d, page, &View { origin, scale, width: side, height: side }, opts).unwrap(); + let inner = 2..side - 2; + inner + .clone() + .flat_map(|y| inner.clone().map(move |x| (x, y))) + .map(|(x, y)| pix.pixel(x, y).unwrap().red()) + .fold((255, 0), |(lo, hi), r| (lo.min(r), hi.max(r))) +} + +#[test] +fn an_image_shown_at_half_its_size_or_less_blends_its_fine_detail_evenly() { + let (d, page, _) = checkerboard_doc(); + let canvas = Options { lod: true, magnified_image_pixels: true, ..Default::default() }; + for (name, opts) in [("export", Options::default()), ("canvas", canvas)] { + for scale in [0.5, 0.37, 0.23] { + for origin in [(0.0, 0.0), (0.3, 0.7)] { + let (lo, hi) = red_range(&d, page, scale, origin, &opts); + assert!(lo >= 104 && hi <= 151, "{name} at {scale} from {origin:?}: reds {lo}..={hi}, not an even mid-grey"); + } + } + } +} + +#[test] +fn an_adjusted_image_shown_smaller_averages_its_adjusted_pixels() { + let (mut d, page, r) = checkerboard_doc(); + // Exposure brightens grey but leaves black black and white white. + if let PaintKind::Image(img) = &mut d.get_mut(r).unwrap().fills[0].kind { + img.filters.exposure = 1.0; + } + let canvas = Options { lod: true, magnified_image_pixels: true, ..Default::default() }; + for (name, opts) in [("export", Options::default()), ("canvas", canvas)] { + let (lo, hi) = red_range(&d, page, 0.37, (0.3, 0.7), &opts); + assert!(lo >= 104 && hi <= 151, "{name}: reds {lo}..={hi}, not the even mid-grey of black and white"); + } +} + +#[test] +fn a_crop_stretching_one_axis_keeps_the_pixels_that_axis_shows() { + // The whole image in a 400 × 2 box: each column two device pixels wide, the rows squeezed 100 + // to 1, so the view's row (at row 50's centre) shows every column black or white in turn. + let (mut d, page, r) = checkerboard_doc(); + let node = d.get_mut(r).unwrap(); + node.width = f64::from(2 * SIDE); + node.height = 2.0; + if let PaintKind::Image(img) = &mut node.fills[0].kind { + img.scale_mode = ImageScaleMode::Crop; + img.crop = Some([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + } + let pix = render_view(&d, page, &View { origin: (0.0, 0.005), scale: 1.0, width: 2 * SIDE, height: 1 }, &Options::default()).unwrap(); + let reds: Vec = (0..2 * SIDE).map(|x| pix.pixel(x, 0).unwrap().red()).collect(); + let (lo, hi) = reds[4..reds.len() - 4].iter().fold((255, 0), |(lo, hi), &r| (lo.min(r), hi.max(r))); + assert!(hi - lo > 64, "columns {lo}..={hi}: blended away, though each shows two device pixels wide"); +} + +/// A one-image document: `img` (`w` × `h`, under `key`: the cache is shared by every test) in a box +/// its size, scaled as `mode`. +fn image_doc(key: &str, img: &Pixmap, mode: ImageScaleMode) -> (Document, NodeId) { + let (w, h) = (img.width(), img.height()); + let mut d = Document::new("downscaled"); + let page = d.first_page().unwrap(); + d.images.insert(key.into(), ImageData { bytes: Arc::new(encode_png(img).unwrap()), width: w, height: h }); + let r = d.create(page, NodeKind::Rectangle, "Image", 0.0, 0.0, f64::from(w), f64::from(h)).unwrap(); + d.get_mut(r).unwrap().fills = vec![Paint::image(key, mode)]; + (d, page) +} + +#[test] +fn a_thin_image_shown_smaller_still_fills_its_box() { + // 200 × 3 at 0.5x: its copy is 100 × 2, proportions a third off from the image's. + let mut img = Pixmap::new(200, 3).unwrap(); + img.fill(tiny_skia::Color::BLACK); + let (d, page) = image_doc("thin", &img, ImageScaleMode::Fit); + let pix = render_view(&d, page, &View { origin: (0.0, 0.0), scale: 0.5, width: 100, height: 1 }, &Options::default()).unwrap(); + let reds: Vec = (0..100).map(|x| pix.pixel(x, 0).unwrap().red()).collect(); + assert!(reds[1..99].iter().all(|&r| r < 8), "the box's row isn't all image (black): {reds:?}"); +} + +#[test] +fn a_transparent_image_shown_smaller_keeps_its_colour() { + // Opaque red columns between transparent ones: averaged, a half-transparent pure red (light red + // over the page's white). + let mut img = Pixmap::new(200, 8).unwrap(); + for (i, c) in (0u32..).zip(img.data_mut().chunks_exact_mut(4)) { + c.copy_from_slice(if (i % 200).is_multiple_of(2) { &[255, 0, 0, 255] } else { &[0, 0, 0, 0] }); + } + let (d, page) = image_doc("half-clear", &img, ImageScaleMode::Fill); + let pix = render_view(&d, page, &View { origin: (0.0, 0.0), scale: 0.37, width: 74, height: 2 }, &Options::default()).unwrap(); + for x in 2..72 { + let c = pix.pixel(x, 1).unwrap(); + assert!(c.red() >= 245 && (100..=155).contains(&c.green()) && c.green().abs_diff(c.blue()) <= 4, "x {x}: {c:?}, not half red over white"); + } +} + +#[test] +fn a_layer_squeezed_on_one_axis_keeps_the_pixels_its_other_axis_shows() { + // The checkerboard's layer squeezed 100 to 1 vertically: each column one device pixel wide, so + // the view's row (at row 50's centre) shows every column black or white in turn. + let (mut d, page, r) = checkerboard_doc(); + d.get_mut(r).unwrap().transform = Affine::scale_non_uniform(1.0, 0.01); + let pix = render_view(&d, page, &View { origin: (0.0, 0.005), scale: 1.0, width: SIDE, height: 1 }, &Options::default()).unwrap(); + let reds: Vec = (0..SIDE).map(|x| pix.pixel(x, 0).unwrap().red()).collect(); + let (lo, hi) = reds[4..reds.len() - 4].iter().fold((255, 0), |(lo, hi), &r| (lo.min(r), hi.max(r))); + assert!(hi - lo > 64, "columns {lo}..={hi}: blended away, though each shows a device pixel wide"); +} diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index d7bd63dd1..94fbbbeaf 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -153,8 +153,12 @@ fn pixels_when_magnified(prep: Prepared, device_scale: f64) -> Prepared { fn fill_with(pix: &mut Pixmap, path: &tiny_skia::Path, paints: &[Paint], w: f64, h: f64, xf: Affine, rule: FillRule, ctx: &Ctx, mask: Option<&Mask>) { let scale = xf.determinant().abs().sqrt(); + // An image picks its copy by the direction shown the most device pixels (a layer can be squeezed). + let [a, b, c, d, ..] = xf.as_coeffs(); + let stretch = crate::paint::max_stretch(a, b, c, d); for p in paints { - let Some(prep) = prepare_at(p, w, h, scale, ctx.doc, ctx.time, ctx.preview) else { continue }; + let k = if matches!(p.kind, PaintKind::Image(_)) { stretch } else { scale }; + let Some(prep) = prepare_at(p, w, h, k, ctx.doc, ctx.time, ctx.preview) else { continue }; let prep = if ctx.magnified_image_pixels && matches!(p.kind, PaintKind::Image(_)) { pixels_when_magnified(prep, scale) } else { prep }; let paint = tiny_skia::Paint { shader: prep.shader(), anti_alias: true, blend_mode: ts_blend(p.blend), ..Default::default() }; if p.blend == BlendMode::PlusDarker { diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 0c68f3b12..78a766fb1 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -4,7 +4,9 @@ //! //! The canvas draws a large image shown smaller than its pixels from a copy scaled down to one of //! [`DISPLAY_SIDES`] (see [`shown`]), so several of them stay decoded within the cache's budget -//! (#1483); exports and every other render draw from the image itself ([`get`]). +//! (#1483); exports draw from the image itself ([`get`]). Wherever an image shows at half its +//! pixels or fewer, it is drawn from a copy averaged down to under twice that size ([`filtered`]), +//! so fine detail blends instead of aliasing into moiré (#2664). //! //! Animated GIFs keep their original bytes like any image; their first frame is the image //! everywhere (canvas, exports). The presenter plays them: [`frame_at`] decodes every frame on @@ -345,8 +347,29 @@ pub fn get(hash: &str, data: Option<&ImageData>, filters: &ImageFilters, profile /// [`get`] for the canvas, where the image shows `side` device pixels on its longer side: an image /// larger than one of [`DISPLAY_SIDES`] that holds `side` comes scaled down to that side (cached /// apart), else as [`get`] gives it. The image's size is the one `data` records (none: the image). +/// Either is halved further while at least twice `side` ([`filtered_side`]). pub fn shown(hash: &str, data: Option<&ImageData>, filters: &ImageFilters, profile: ColorProfile, side: f64) -> Option> { - get_within(hash, data, filters, profile, display_side(data.map_or(0, |d| d.width.max(d.height)), side)) + let long = data.map_or(0, |d| d.width.max(d.height)); + get_within(hash, data, filters, profile, filtered_side(long, display_side(long, side), side)) +} + +/// [`get`] for an image showing `side` device pixels on its longer side: scaled down (cached apart) +/// while it is at least twice that long ([`filtered_side`]), else the image itself. +pub fn filtered(hash: &str, data: Option<&ImageData>, filters: &ImageFilters, profile: ColorProfile, side: f64) -> Option> { + get_within(hash, data, filters, profile, filtered_side(data.map_or(0, |d| d.width.max(d.height)), MAX_SIDE, side)) +} + +/// The largest side to decode an image `long` pixels on its longer side at, decoded at most +/// `max_side` long, to show `side` device pixels long: halved while at least twice `side`, so it is +/// never sampled at half its size or less (each pixel an average of the pixels it covers, not a few +/// samples of them, which turns fine detail into moiré); else `max_side`. +pub(crate) fn filtered_side(long: u32, max_side: u32, side: f64) -> u32 { + let start = long.min(max_side); + let mut s = start; + while s > 1 && f64::from(s) >= 2.0 * side { + s = s.div_ceil(2); + } + if s < start { s } else { max_side } } /// The largest side to decode an image `long` pixels on its longer side at, to show `side` device @@ -362,14 +385,33 @@ fn get_within(hash: &str, data: Option<&ImageData>, filters: &ImageFilters, prof if let Some(p) = cache().lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&key) { return Some(p); } - let (mut p, srgb) = decode_within(&data?.bytes, profile, max_side, MAX_DECODED_BYTES)?; + let (mut p, srgb) = decode_within(&data?.bytes, profile, MAX_SIDE, MAX_DECODED_BYTES)?; // Images with their own profile are in `profile` already (sRGB → sRGB is the identity). finish(&mut p, filters, if srgb { profile } else { ColorProfile::Srgb }); - let p = Arc::new(p); + // A copy averages the finished pixels, as drawing the image smaller does: adjustments clamp, + // and premultiplied colour keeps transparent pixels from darkening their neighbours. + let p = Arc::new(shrink(p, max_side)?); cache().lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(key, p.clone(), MAX_CACHED_BYTES); Some(p) } +/// The size to place `pm`, image `data` or a copy of it, as: the size `data` records when `pm` is +/// that size decoded and scaled to `pm`'s longer side as [`get_within`] does (each side of a copy +/// rounds apart, so its own proportions are off by up to a pixel), else `pm`'s own. +pub(crate) fn source_size(data: Option<&ImageData>, pm: &Pixmap) -> (f64, f64) { + let own = (pm.width(), pm.height()); + let made = |(w, h)| thumbnail_size(w, h, MAX_SIDE).and_then(|(w, h)| thumbnail_size(w, h, own.0.max(own.1))); + let (w, h) = data.map(|d| (d.width, d.height)).filter(|&size| made(size) == Some(own)).unwrap_or(own); + (f64::from(w), f64::from(h)) +} + +/// `p` averaged down to at most `max_side` wide and tall. +fn shrink(p: Pixmap, max_side: u32) -> Option { + let (w, h) = (p.width(), p.height()); + let (nw, nh) = thumbnail_size(w, h, max_side)?; + Pixmap::from_vec(thumbnail_u8((w, h), (nw, nh), false, p.take())?, tiny_skia::IntSize::from_wh(nw, nh)?) +} + /// The filters, then the conversion into the document's colour space. fn finish(p: &mut Pixmap, filters: &ImageFilters, profile: ColorProfile) { if !filters.is_identity() { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 6779fe776..fb635509d 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -679,6 +679,8 @@ mod clip_cover_tests; #[cfg(test)] mod dots_tests; #[cfg(test)] +mod downscaled_image_tests; +#[cfg(test)] mod effect_order_tests; #[cfg(test)] mod effects_behaviour_tests; diff --git a/crates/render/src/paint.rs b/crates/render/src/paint.rs index 56de03464..c62d553c2 100644 --- a/crates/render/src/paint.rs +++ b/crates/render/src/paint.rs @@ -145,13 +145,17 @@ pub fn prepare_at(paint: &Paint, w: f64, h: f64, scale: f64, doc: &Document, tim Some(f) => f.clone(), None => still(img, data, w, h, scale, doc, preview)?, }; - let transform = image_transform(img, f64::from(pm.width()), f64::from(pm.height()), w, h); + let (pw, ph) = (f64::from(pm.width()), f64::from(pm.height())); if img.scale_mode == ImageScaleMode::Tile { + let transform = image_transform(img, pw, ph, w, h); return Some(Prepared::Pattern { pixmap: pm, mode: SpreadMode::Repeat, quality: FilterQuality::Bicubic, opacity: op, transform }); } + // A smaller copy goes where the image itself would. + let (iw, ih) = crate::images::source_size(data, &pm); + let transform = Transform::from_scale((iw / pw) as f32, (ih / ph) as f32).post_concat(image_transform(img, iw, ih, w, h)); // An image covering the whole box fills it to its edges (a transparent border would // fade them where the image is scaled up). - if covers_box(img, f64::from(pm.width()), f64::from(pm.height()), w, h) { + if covers_box(img, iw, ih, w, h) { return Some(Prepared::Pattern { pixmap: pm, mode: SpreadMode::Pad, quality: FilterQuality::Bicubic, opacity: op, transform }); } // Fit/Crop: a transparent 1-px border so Pad spreads transparency, not edge pixels. @@ -169,17 +173,30 @@ pub fn prepare_at(paint: &Paint, w: f64, h: f64, scale: f64, doc: &Document, tim /// The pixmap image paint `img` draws in a `w` × `h` box at `scale` device pixels per unit: on the /// canvas (`preview`) a copy no larger than the image shows ([`crate::images::shown`]), else the -/// image itself. Tiles keep the image: their size is in its pixels. +/// image itself, scaled down where it shows at half its size or less ([`crate::images::filtered`]). +/// Tiles keep the image: their size is in its pixels. +/// shortcut: tiles shown much smaller can still alias; scale their transform with the copy if that turns up. fn still(img: &ImagePaint, data: Option<&ImageData>, w: f64, h: f64, scale: f64, doc: &Document, preview: bool) -> Option> { let (iw, ih) = data.map_or((0, 0), |d| (d.width, d.height)); - if preview && img.scale_mode != ImageScaleMode::Tile && iw > 0 && ih > 0 { + if img.scale_mode != ImageScaleMode::Tile && iw > 0 && ih > 0 { let t = image_transform(img, f64::from(iw), f64::from(ih), w, h); - let side = scale * f64::from(t.sx * t.sy - t.kx * t.ky).abs().sqrt() * f64::from(iw.max(ih)); - return crate::images::shown(&img.image, data, &img.filters, doc.color_profile, side); + // `scale` is the layer's largest stretch, so the product bounds what any direction shows. + let stretch = max_stretch(t.sx.into(), t.ky.into(), t.kx.into(), t.sy.into()); + let side = scale * stretch * f64::from(iw.max(ih)); + let pick = if preview { crate::images::shown } else { crate::images::filtered }; + return pick(&img.image, data, &img.filters, doc.color_profile, side); } crate::images::get(&img.image, data, &img.filters, doc.color_profile) } +/// The most the linear map `[a c; b d]` stretches any direction (its largest singular value): the +/// scale for uniform scaling and rotation, the longer axis for a squeeze. +pub(crate) fn max_stretch(a: f64, b: f64, c: f64, d: f64) -> f64 { + let sum = a * a + b * b + c * c + d * d; + let det = a * d - b * c; + ((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt() +} + /// Whether image paint `img` paints its whole `w` × `h` box opaque: an image without transparent /// pixels that covers the box (or tiles it). /// shortcut: always looks at the image itself (exact, also on the canvas), so a large image with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4e2807c05..6e052d6e9 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-27 · **Change:** minor (M8, #2631: a sharp drop shadow under a stroked layer, text included, is one solid silhouette with no light outline along the layer's edge; M8, #2635: an opaque inside or outside stroke meets the background and the fill with no light fringe or gap at its edges; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); 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) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-28 · **Change:** minor (M8, #2664: an image shown at half its pixels or fewer, on the canvas and in exports, blends its fine detail instead of showing moiré; M8, #2631: a sharp drop shadow under a stroked layer, text included, is one solid silhouette with no light outline along the layer's edge; M8, #2635: an opaque inside or outside stroke meets the background and the fill with no light fringe or gap at its edges; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); 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 @@ -653,6 +653,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-28 | patch | M8, #2664: an image fill shown at half its pixels or fewer (a 0.5x export, the canvas zoomed out) turned fine detail, a knitted sweater, into strong moiré bands: the image was sampled straight at the small size, a few source pixels per output pixel, with nothing averaging the rest. Wherever an image shows at half its size or less, it is now drawn from a copy averaged down to under twice the size it shows at (the image halved, or the canvas's smaller copy halved, cached with the decoded images), so each output pixel blends every pixel it covers. Every smaller copy now averages the finished pixels, premultiplied and after the image's adjustments: averaging first darkened the edges of transparent areas and changed the colours of adjusted images (exposure and the rest clamp), which the canvas's smaller copies did before. A copy is placed where the image itself would be, so a thin image keeps its box (each side of a copy rounds apart), and an image squeezed on one axis (by its crop or its layer) keeps the pixels its other axis shows. Images shown larger draw as before (magnified pixels too). Canvas, PNG, JPG and WebP exports and the paints PDF export rasterises (images PDF and SVG embed are scaled by the viewer); tiled images still draw from the image itself. Tests: `downscaled_image_tests::an_image_shown_at_half_its_size_or_less_blends_its_fine_detail_evenly` (fails on main), `an_adjusted_image_shown_smaller_averages_its_adjusted_pixels`, `a_transparent_image_shown_smaller_keeps_its_colour`, `a_thin_image_shown_smaller_still_fills_its_box`, `a_crop_stretching_one_axis_keeps_the_pixels_that_axis_shows` and `a_layer_squeezed_on_one_axis_keeps_the_pixels_its_other_axis_shows`. | | 2026-11-27 | patch | M8, #2631: a drop shadow under a layer with an outside stroke (text especially, a black stroke over a black shadow) showed a light outline along the layer's edge wherever that edge lay over the shadow, in a letter's counters too. Hiding the shadow behind the layer cut the layer's share of each anti-aliased edge pixel out of the shadow, then the layer's own edge pixel drew that share again over what was left, counting the edge twice. The shadow now keeps, at each pixel, its part outside the layer, scaled by what the layer lets through there, so an opaque edge sits on a full shadow and a translucent fill still hides it. What the shadow is cast from and hidden behind follows what the layer fills (the fill out to the middle of an opaque inside or outside stroke, #2635), and stroked text casts and hides its shadows by its glyph outlines and stroke too (it fell back to its pixels). Canvas, PNG and PDF; SVG text with a stroke now cuts its shadow out behind it as other layers do. Test: `shadow_silhouette_tests::a_sharp_shadow_under_a_stroked_layer_has_no_light_line_along_the_layers_edge` (fails on main). | | 2026-11-27 | patch | M8, #2635: a stroked layer showed a thin light line along the outer edge of an inside stroke (the fill under the stroke's anti-aliased edge showed through it), and what lies behind showed between an outside stroke and the fill. Where the stroke hides what is under it (its top paint an opaque solid colour, normal blend, one weight all round, no dashes, width profile or brush), the fill now reaches the middle of the stroke, so neither edge has the fill or the background showing through: rectangles, frames and ellipses by their inset or grown outline, other shapes and text by their outline less or plus the centred stroke. Translucent, gradient and image strokes and even-odd outlines fill as before. Test: `stroke_fringe_tests::an_opaque_stroke_shows_nothing_lighter_than_its_dark_neighbour_at_either_edge` (fails on main). | | 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. | From 9284c9c3e36bbe3a25e24c61551fc3c2d58cfa8e Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 13:25:51 +0700 Subject: [PATCH 46/48] M3: Cmd/Ctrl+L with nothing selected copies the page's link (#2507) --- crates/ui-egui/src/context_menu_tests.rs | 25 ++++++++++++++++-------- crates/ui-egui/src/menus.rs | 16 ++++++++++----- crates/ui-egui/src/panels/layers.rs | 3 +-- docs/ui-parity.md | 1 + 4 files changed, 30 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/context_menu_tests.rs b/crates/ui-egui/src/context_menu_tests.rs index dce0ad1f4..1c32949f0 100644 --- a/crates/ui-egui/src/context_menu_tests.rs +++ b/crates/ui-egui/src/context_menu_tests.rs @@ -72,17 +72,28 @@ fn the_context_menu_offers_go_to_main_for_an_instance() { assert!(!has_text(&shapes, "Create component"), "not offered for an instance"); } +/// Press Cmd/Ctrl+L on the canvas. +fn cmd_l(u: &mut Ui) { + let held = egui::Modifiers { command: true, mac_cmd: cfg!(target_os = "macos"), ctrl: !cfg!(target_os = "macos"), ..egui::Modifiers::NONE }; + let l = |pressed| egui::Event::Key { key: egui::Key::L, physical_key: Some(egui::Key::L), pressed, repeat: false, modifiers: held }; + u.frame_with(vec![l(true), l(false)], held); +} + +/// With nothing selected, Cmd/Ctrl+L copies the link of the page shown (#2507), not of a layer. #[test] -fn copying_a_link_with_nothing_selected_copies_nothing() { +fn cmd_l_with_nothing_selected_copies_the_pages_link() { let mut s = Session::new(); - s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 200})).unwrap(); + let frame = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 200})).unwrap()); s.execute("select.none", &json!({})).unwrap(); + let page = s.page().unwrap(); let copied = Arc::new(Mutex::new(Vec::new())); let mut u = Ui::new(s); u.app.services = Box::new(Copied(copied.clone())); - crate::menus::invoke(&mut u.app, "edit.copyLink"); - assert!(copied.lock().unwrap().is_empty(), "no link to node 0"); - assert!(u.app.ui.toast.is_none()); + u.frame(vec![]); + cmd_l(&mut u); + assert_ne!(page, frame); + assert_eq!(*copied.lock().unwrap(), [format!("figcraft://node/{}", page.0)]); + assert_eq!(u.app.ui.toast.as_ref().map(|t| t.0.as_str()), Some("Link copied")); } /// With a section selected, a right-click on either frame inside it links that frame, not the @@ -236,8 +247,6 @@ fn cmd_l_copies_the_link_of_the_selected_frame() { let mut u = Ui::new(s); u.app.services = Box::new(Copied(copied.clone())); u.frame(vec![]); - let held = egui::Modifiers { command: true, mac_cmd: cfg!(target_os = "macos"), ctrl: !cfg!(target_os = "macos"), ..egui::Modifiers::NONE }; - let l = |pressed| egui::Event::Key { key: egui::Key::L, physical_key: Some(egui::Key::L), pressed, repeat: false, modifiers: held }; - u.frame_with(vec![l(true), l(false)], held); + cmd_l(&mut u); assert_eq!(copied.lock().unwrap().last().cloned(), Some(format!("figcraft://node/{}", frame.0))); } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index f8a793154..42450a010 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -69,6 +69,14 @@ pub fn record_recent(app: &mut FigApp, key: &str) { r.truncate(figcraft_engine::MAX_RECENT_ACTIONS); } +/// Put `id`'s link (`figcraft://node/`) on the clipboard and say so. It goes through the +/// control-channel fence (`clipboard_set_text`): a synthetic gesture never replaces the user's +/// clipboard. +pub(crate) fn copy_link(app: &mut FigApp, id: figcraft_doc::NodeId) { + app.clipboard_set_text(&format!("figcraft://node/{}", id.0)); + app.toast(tr("Link copied")); +} + /// Run a menu, shortcut or palette action by id: actions that need the UI (dialogs, panels, the /// clipboard) are handled here, the rest go to the engine. pub fn invoke(app: &mut FigApp, id: &str) { @@ -150,11 +158,9 @@ pub fn invoke(app: &mut FigApp, id: &str) { app.toast(tr("Copied as text")); } "edit.copyLink" => { - // Only a selected layer has a link, and the copy goes through the control-channel fence - // (`clipboard_set_text`): a synthetic gesture never replaces the user's clipboard. - if let Some(id) = app.session.selection().first() { - app.clipboard_set_text(&format!("figcraft://node/{}", id.0)); - app.toast(tr("Link copied")); + // The selected layer's link, else the page's (#2507). + if let Some(id) = app.session.selection().first().copied().or_else(|| app.session.page().ok()) { + copy_link(app, id); } } "edit.findReplace" => app.ui.find = Some((String::new(), String::new())), diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 5c39c4375..741babeac 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -346,8 +346,7 @@ fn pages(app: &mut FigApp, ui: &mut Ui) { } // Copy link to page (#2379); a divider can't be linked. if !divider && ui.button(tr("Copy link to page")).clicked() { - app.clipboard_set_text(&format!("figcraft://node/{}", id.0)); - app.toast(tr("Link copied")); + crate::menus::copy_link(app, id); ui.close(); } // The page the file opens on, for everyone (#1817); a divider can't be one. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 54a4e08a9..b114ceecf 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -212,6 +212,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-28 | patch | M3, #2507: Cmd/Ctrl+L with nothing selected copied nothing. It now copies the link of the page shown (`figcraft://node/`, what the pages list's Copy link to page copies), with the same "Link copied" toast; with a selection it still copies the selected layer's link. Test: `context_menu_tests::cmd_l_with_nothing_selected_copies_the_pages_link` | | 2026-11-28 | patch | M12, #2641: the Pencil (and the board's Marker, Highlighter and Eraser) showed a crosshair. Its cursor is now the ink's tip: a dot in the colour its stroke takes there, as wide on screen as the stroke, ringed white and dark; the Eraser's is a ring of its reach. Tests: `cursor_tests::each_tool_has_its_cursor_by_modifier_and_what_is_under_the_pointer`, `cursors_tests::the_ink_tools_show_a_dot_in_the_inks_colour_and_width`. | | 2026-11-28 | patch | M12, #2237: the code block tool takes the `` ` `` key on boards (`tool.codeBlock`), pinned like the other board tool keys (60 undocumented bindings). Test: `shortcut_parity_tests::counts_match_the_docs`. | | 2026-11-28 | patch | M4, #2338: superscript and subscript were the layer's, so a footnote marker such as the "(1)" in "$29/month(1)" couldn't be raised alone. Each character now has a position (none, superscript, subscript): `textPosition` on `text.style` (with `start`/`end`) and `node.set`, and Type settings ▸ Details ▸ Position sets the selected characters while editing, else whole layers, and shows theirs. A character's position wins over the layer's `sups` / `subs`, which move onto the characters the first time a position is set, so a range set to none sits on the line. Text styles keep it (`position` in a style's definition; a style that sets none leaves the characters' own, so older styles don't drop a raised marker), inspect reports `textPosition` and its CSS `vertical-align: super` or `sub`, and `.fig` export warns that it was left out. Tests: `text_behaviour_tests::a_range_of_characters_is_raised_or_lowered_on_its_own`, `typography::variable_tests::details_position_sets_superscript_subscript_or_neither`. | From 806e58ce0f1e29b15c11569f224b805d610745bb Mon Sep 17 00:00:00 2001 From: Patrik Lermon Date: Sat, 28 Nov 2026 09:58:32 +0100 Subject: [PATCH 47/48] i18n(sv): translate 51 new strings Brings the Swedish catalog up to date with upstream main (cf320ee2). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/sv.toml | 51 ++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/crates/ui-egui/locales/sv.toml b/crates/ui-egui/locales/sv.toml index a7dbf1b42..5e0962c53 100644 --- a/crates/ui-egui/locales/sv.toml +++ b/crates/ui-egui/locales/sv.toml @@ -46,6 +46,7 @@ name = "Svenska" "Add a layer or component to tile first" = "Lägg först till ett lager eller en komponent att lägga sida vid sida" "Add a minute" = "Lägg till en minut" "Add a note for developers" = "Lägg till en anteckning för utvecklare" +"Add a rule" = "Lägg till en regel" "Add action" = "Lägg till åtgärd" "Add actions for when no condition holds" = "Lägg till åtgärder för när inget villkor uppfylls" "Add an annotation for developers" = "Lägg till en annotering för utvecklare" @@ -73,6 +74,7 @@ name = "Svenska" "Add properties to make instances configurable" = "Lägg till egenskaper för att göra instanser konfigurerbara" "Add reaction" = "Lägg till reaktion" "Add row" = "Lägg till rad" +"Add rule" = "Lägg till regel" "Add starting point" = "Lägg till startpunkt" "Add stroke" = "Lägg till kontur" "Add variant" = "Lägg till variant" @@ -103,6 +105,7 @@ name = "Svenska" "All comments" = "Alla kommentarer" "All components" = "Alla komponenter" "All fonts" = "Alla typsnitt" +"All libraries" = "Alla bibliotek" "All objects" = "Alla objekt" "All supported properties" = "Alla egenskaper som stöds" "All the fonts this file uses are installed" = "Alla typsnitt som filen använder är installerade" @@ -159,6 +162,7 @@ name = "Svenska" "Auto (space between)" = "Auto (utrymme mellan)" "Auto (space evenly)" = "Auto (jämnt utrymme)" "Auto ({mode})" = "Auto ({mode})" +"Auto: black, or white on a dark background" = "Auto: svart, eller vit på mörk bakgrund" "Auto columns" = "Automatiska kolumner" "Auto gap" = "Automatiskt mellanrum" "Auto height" = "Automatisk höjd" @@ -178,6 +182,7 @@ name = "Svenska" "Back to the values the font style implies" = "Tillbaka till värdena som teckenstilen anger" "Background" = "Bakgrund" "Background blur" = "Bakgrundsoskärpa" +"Bash" = "Bash" "Basics" = "Grunder" "Before" = "Före" "Bend" = "Böj" @@ -186,6 +191,7 @@ name = "Svenska" "Bevel" = "Fasning" "Binary assets added" = "Binära resurser tillagda" "Binary assets removed" = "Binära resurser borttagna" +"Black" = "Svart" "Black & white" = "Svartvitt" "Bleed" = "Utfall" "Bleed marks" = "Utfallsmärken" @@ -226,6 +232,7 @@ name = "Svenska" "Bulleted list" = "Punktlista" "C or Shift+C" = "C eller Shift+C" "C or ⇧C" = "C eller ⇧C" +"C++" = "C++" "Changed {date}" = "Ändrad {date}" "CMYK colour" = "CMYK-färg" "Can view" = "Kan visa" @@ -295,6 +302,7 @@ name = "Svenska" "Close version history" = "Stäng versionshistorik" "Close when clicking outside" = "Stäng vid klick utanför" "Code" = "Kod" +"Code block" = "Kodblock" "Code syntax" = "Kodsyntax" "Collapse" = "Komprimera" "Collection" = "Samling" @@ -361,6 +369,7 @@ name = "Svenska" "Copy fill" = "Kopiera fyllning" "Copy for AI" = "Kopiera för AI" "Copy link" = "Kopiera länk" +"Copy link to page" = "Kopiera länk till sida" "Copy stroke" = "Kopiera kontur" "Copy the {label}" = "Kopiera {label}" "Copy {value}" = "Kopiera {value}" @@ -389,9 +398,13 @@ name = "Svenska" "Crop" = "Beskär" "Crop image" = "Beskär bild" "Crop marks" = "Skärmärken" +"CSS" = "CSS" "Ctrl+arrows" = "Ctrl+piltangenter" "Ctrl+click" = "Ctrl+klick" "Ctrl+click a padding field" = "Ctrl+klicka på ett padding-fält" +"In code" = "I kod" +"Source file" = "Källfil" +"Variant value" = "Variantvärde" "⌘ click a padding field" = "⌘ klicka på ett padding-fält" "Ctrl+scroll" = "Ctrl+rullning" "Current name" = "Aktuellt namn" @@ -449,6 +462,7 @@ name = "Svenska" "Default" = "Standard" "Default content" = "Standardinnehåll" "Default value (the top-left variant)" = "Standardvärde (varianten längst upp till vänster)" +"This variant's value" = "Den här variantens värde" "Delay" = "Fördröjning" "Delete" = "Radera" "Delete category (its annotations stay)" = "Radera kategori (dess anteckningar finns kvar)" @@ -470,6 +484,7 @@ name = "Svenska" "Description" = "Beskrivning" "Description (optional)" = "Beskrivning (valfritt)" "Design" = "Design" +"Design it's a version of" = "Design som detta är en version av" "Design panel" = "Designpanel" "Design system starter" = "Startmall för designsystem" "Desktop" = "Skrivbord" @@ -674,10 +689,12 @@ name = "Svenska" "Getting started" = "Kom igång" "Give the address of a server open to the public, or a server's address with its key (`figcraft-server key` prints it)." = "Ange adressen till en server som är öppen för alla, eller en servers adress med dess nyckel (`figcraft-server key` skriver ut den)." "Glass" = "Glas" +"Go" = "Go" "Go to main component" = "Gå till huvudkomponent" "Go to {name}" = "Gå till {name}" "Grab bag" = "Blandat" "Gradient" = "Gradient" +"GraphQL" = "GraphQL" "Graph paper" = "Rutat papper" "Gray" = "Grå" "Green" = "Grön" @@ -729,6 +746,7 @@ name = "Svenska" "Hue" = "Nyans" "Hug" = "Omslut" "Hug contents" = "Omslut innehåll" +"HTML" = "HTML" "Icon components on a 24 px grid with keylines and a size preview" = "Ikonkomponenter på ett 24 px-rutnät med hjälplinjer och en förhandsgranskning av storlekar" "Icon set starter" = "Startpaket för ikonuppsättning" "If it keeps happening, please report it at {link} with this message." = "Om det fortsätter att hända kan du rapportera det på {link} och bifoga det här meddelandet." @@ -787,6 +805,8 @@ name = "Svenska" "It asks permission to:" = "Den ber om behörighet att:" "Jan" = "jan" "Join" = "Gå med" +"JavaScript" = "JavaScript" +"JSON" = "JSON" "Join code copied" = "Anslutningskoden har kopierats" "Join code or invite link" = "Anslutningskod eller inbjudningslänk" "Join live session" = "Gå med i livesession" @@ -807,6 +827,7 @@ name = "Svenska" "Keep appearance converts every color value to {profile} so colors look the same. Keep values leaves the numbers as they are, so colors shift." = "Behåll utseende konverterar varje färgvärde till {profile} så att färgerna ser likadana ut. Behåll värden lämnar siffrorna som de är, så färgerna förskjuts." "Keep tool selected after use" = "Behåll verktyget markerat efter användning" "Keep values" = "Behåll värden" +"Kotlin" = "Kotlin" "Key/Gamepad" = "Tangent/spelkontroll" "Key/Gamepad {key}" = "Tangent/spelkontroll {key}" "Keyboard shortcuts" = "Kortkommandon" @@ -916,6 +937,7 @@ name = "Svenska" "Merged PRs" = "Sammanslagna PR:er" "Min H" = "Min H" "Min W" = "Min B" +"Mind map" = "Tankekarta" "Minimize" = "Minimera" "Minutes" = "Minuter" "Mirror angle" = "Spegla vinkel" @@ -931,6 +953,7 @@ name = "Svenska" "Mixed" = "Blandat" "Mixed fonts" = "Blandade typsnitt" "Mixed interactions: click + to replace them" = "Blandade interaktioner: klicka på + för att ersätta dem" +"Mobile" = "Mobil" "Mobile app" = "Mobilapp" "Mode" = "Läge" "Model" = "Modell" @@ -962,8 +985,10 @@ name = "Svenska" "Nested instance" = "Kapslad instans" "New board" = "Ny whiteboard" "New design file" = "Ny designfil" +"New from selection" = "Ny från markering" "Newest first" = "Nyaste först" "Next frame" = "Nästa frame" +"Next or previous control" = "Nästa eller föregående kontroll" "Next ready for dev" = "Nästa redo för utveckling" "Next size option" = "Nästa storleksalternativ" "No assets: no export settings, icons or images. Add export settings in the Design tab." = "Inga resurser: inga exportinställningar, ikoner eller bilder. Lägg till exportinställningar på fliken Design." @@ -1115,6 +1140,7 @@ name = "Svenska" "Pause" = "Pausa" "Pink" = "Rosa" "Placed on the current page" = "Placerat på den aktuella sidan" +"Plain text" = "Oformaterad text" "Pages: {pages}" = "Sidor: {pages}" "Paint bucket" = "Färghink" "Pan the canvas" = "Panorera arbetsytan" @@ -1208,6 +1234,7 @@ name = "Svenska" "Published · {people}" = "Publicerad · {people}" "Publishing with the server's key." = "Publicerar med serverns nyckel." "Publishing…" = "Publicerar…" +"Python" = "Python" "Push" = "Skjut" "Push changes to main component" = "Skicka ändringar till huvudkomponenten" "Put text on path" = "Placera text på bana" @@ -1334,9 +1361,12 @@ name = "Svenska" "Row span" = "Radspann" "Rows" = "Rader" "Rows {count}" = "Rader {count}" +"Ruby" = "Ruby" "Rulers" = "Linjaler" +"Rules appear under Annotations, in the Responsive category." = "Regler visas under Annoteringar, i kategorin Responsiv." "Run" = "Kör" "Run {label}" = "Kör {label}" +"Rust" = "Rust" "Save file" = "Spara fil" "Save files automatically" = "Spara filer automatiskt" "Search templates" = "Sök mallar" @@ -1357,6 +1387,7 @@ name = "Svenska" "Scatter" = "Spridning" "Scoping: where pickers offer it" = "Omfång: var väljarna erbjuder den" "Screen" = "Skärm" +"Screen sizes" = "Skärmstorlekar" "Scroll behavior" = "Rullningsbeteende" "Scroll to" = "Rulla till" "Scroll to layer" = "Rulla till lager" @@ -1450,6 +1481,7 @@ name = "Svenska" "Show/Hide UI" = "Visa/dölj gränssnitt" "Side by side" = "Sida vid sida" "Sidebar" = "Sidofält" +"Sidebar becomes a drawer below 768 px" = "Sidofältet blir en utfällbar panel under 768 px" "Simplify stroke" = "Förenkla kontur" "Size" = "Storlek" "Size jitter" = "Storleksvariation" @@ -1465,6 +1497,8 @@ name = "Svenska" "Small caps" = "Kapitäler" "Smart animate" = "Smart animering" "Snap to pixel grid" = "Fäst mot pixelrutnät" +"Snap to pixel grid off" = "Fäst mot pixelrutnät av" +"Snap to pixel grid on" = "Fäst mot pixelrutnät på" "Social and slides" = "Sociala medier och presentationer" "Social media" = "Sociala medier" "Social post sizes" = "Storlekar för inlägg i sociala medier" @@ -1472,6 +1506,8 @@ name = "Svenska" "Solid" = "Enfärgad" "Some variants have the same property values: give each one a unique combination" = "Vissa varianter har samma egenskapsvärden: ge var och en en unik kombination" "Sort" = "Sortera" +"Sort A to Z" = "Sortera A till Ö" +"Sort Z to A" = "Sortera Ö till A" "Sort by" = "Sortera efter" "Sort by date" = "Sortera efter datum" "Sort by page" = "Sortera efter sida" @@ -1503,6 +1539,7 @@ name = "Svenska" "Spotlight me" = "Rikta strålkastaren mot mig" "Spread" = "Spridning" "Square" = "Kvadrat" +"SQL" = "SQL" "Stamp" = "Stämpel" "Stamps" = "Stämplar" "Standard" = "Standard" @@ -1549,9 +1586,11 @@ name = "Svenska" "Stylistic set 3" = "Stiluppsättning 3" "Stylistic set 4" = "Stiluppsättning 4" "Stylistic set 5" = "Stiluppsättning 5" +"Subscript" = "Nedsänkt" "Subtract" = "Subtrahera" "Subtracts" = "Subtraktioner" "Suffix" = "Suffix" +"Superscript" = "Upphöjd" "Suspend snapping while dragging" = "Stäng av fästfunktionen medan du drar" "Swap instance" = "Byt instans" "Swap library: use another library's assets of the same names" = "Byt bibliotek: använd resurser med samma namn från ett annat bibliotek" @@ -1563,6 +1602,7 @@ name = "Svenska" "Swapped {n} assets" = { one = "Bytte {n} resurs", other = "Bytte {n} resurser" } "Swapped {n} assets; {missed} had no match and still use the old library" = { one = "Bytte {n} resurs; {missed} saknade motsvarighet och använder fortfarande det gamla biblioteket", other = "Bytte {n} resurser; {missed} saknade motsvarighet och använder fortfarande det gamla biblioteket" } "Sweep" = "Svep" +"Swift" = "Swift" "System" = "Enligt systemet" "Tab / Shift+Tab" = "Tab / Shift+Tab" "Table" = "Tabell" @@ -1588,6 +1628,7 @@ name = "Svenska" "Huge" = "Enorm" "Text style" = "Textstil" "Text styles" = "Textstilar" +"Text tools" = "Textverktyg" "Texts" = "Texter" "Texture" = "Textur" "The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "Arbetsytan förhandsgranskar färger i sRGB; PNG-, JPG- och WebP-filer som exporteras med filens profil märks med Display P3." @@ -1664,6 +1705,7 @@ name = "Svenska" "Two digits" = "Två siffror" "Type" = "Typ" "Type settings" = "Textinställningar" +"TypeScript" = "TypeScript" "Type the join code you were given, or paste an invite link." = "Skriv anslutningskoden du fick, eller klistra in en inbjudningslänk." "Typography" = "Typografi" "Underline" = "Understrykning" @@ -1753,6 +1795,7 @@ name = "Svenska" "What it's for" = "Vad den är till för" "What this changed from isn't known: it changed before FigCraft kept a copy of ready-for-dev frames. Resolve the change (or mark it ready again) to compare from now on." = "Vad detta ändrades från är okänt: ändringen gjordes innan FigCraft började spara en kopia av frames som är klara för utveckling. Lös ändringen (eller markera den som klar igen) för att kunna jämföra från och med nu." "When marked ready" = "När den märktes som klar" +"While editing text: next or previous text layer" = "Vid textredigering: nästa eller föregående textlager" "While hovering" = "Vid hovring" "While pressing" = "Vid nedtryckning" "White" = "Vit" @@ -1872,6 +1915,7 @@ name = "Svenska" "offer files to save if it asks to (you choose where each one goes)" = "erbjuda filer att spara om den ber om det (du väljer var varje fil hamnar)" "only in a text style or variable" = "endast i en textstil eller variabel" "or" = "eller" +"pattern paints without a source layer were skipped" = "mönsterfyllningar utan källager hoppades över" "point stroke joins were preserved; dashed or variable-width strokes render with the layer join" = "punkternas hörntyper behölls; streckade konturer och konturer med variabel bredd ritas med lagrets hörntyp" "preferred slot component keys cannot be resolved to file nodes and were skipped" = "nycklar för föredragna komponenter i fack kan inte kopplas till lager i filen och hoppades över" "prototype actions of unknown types were skipped" = "prototypåtgärder av okända typer hoppades över" @@ -2066,14 +2110,18 @@ name = "Svenska" "arrange.spacing" = "Avstånd" "arrange.tidy" = "Snygga till" "board.addConnected" = "Lägg till ansluten form" +"board.codeBlock" = "Kodblock" "board.connector" = "Koppling" "board.grid" = "Tavlans rutnät" "board.ink" = "Märkpennsdrag" "board.label" = "Kopplingsetikett" +"board.mindMap" = "Tankekarta" +"board.mindMapAdd" = "Lägg till nod i tankekarta" "board.nextSticky" = "Nästa lapp" "board.reattach" = "Koppla om koppling" "board.reshape" = "Omforma koppling" "board.setColor" = "Whiteboardfärg" +"board.setLanguage" = "Kodspråk" "board.setStyle" = "Whiteboardstil" "board.shape" = "Form med text" "board.stamp" = "Stämpel" @@ -2269,6 +2317,7 @@ name = "Svenska" "inspect.assets" = "Resurser" "inspect.code" = "Kod" "inspect.componentCode" = "Komponentkod" +"inspect.designContext" = "Designkontext" "inspect.properties" = "Egenskaper" "inspect.readyForDev" = "Redo för utveckling" "instance.create" = "Skapa instans" @@ -2350,6 +2399,7 @@ name = "Svenska" "page.rename" = "Byt namn på sida" "page.select" = "Gå till sida" "page.setBackground" = "Sidbakgrund" +"page.setOpening" = "Ange som startsida" "paint.documentColors" = "Dokumentfärger" "plugin.close" = "Stäng plugin-panelen" "plugin.directory.install" = "Installera plugin från katalogen" @@ -2536,6 +2586,7 @@ name = "Svenska" "tool.highlighter" = "Överstrykningspenna" "tool.line" = "Linje" "tool.marker" = "Märkpenna" +"tool.mindMap" = "Verktyget Tankekarta" "tool.move" = "Flytta" "tool.pen" = "Penna" "tool.pencil" = "Blyertspenna" From efd2f88ed57f790d65fc9b7e63a79bf3196aa6b1 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 16:25:15 +0700 Subject: [PATCH 48/48] Build the delta snapshot test's text from a shared TextData --- crates/collab/src/delta_snapshot_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/collab/src/delta_snapshot_tests.rs b/crates/collab/src/delta_snapshot_tests.rs index b6f96da99..fb3a0a075 100644 --- a/crates/collab/src/delta_snapshot_tests.rs +++ b/crates/collab/src/delta_snapshot_tests.rs @@ -382,7 +382,7 @@ fn server_falls_back_to_legacy_snapshot_when_delta_exceeds_decode_budget() { // the server must fall back to `CatchUp::Snapshot` so capable clients still join cleanly. let mut doc = Document::new("HighAmplificationHonest"); let page = doc.first_page().unwrap(); - let src = doc.create(page, NodeKind::Text(TextData::new("T".repeat(256 * 1024))), "Big", 0.0, 0.0, 100.0, 20.0).unwrap(); + let src = doc.create(page, NodeKind::Text(TextData::new("T".repeat(256 * 1024)).into()), "Big", 0.0, 0.0, 100.0, 20.0).unwrap(); let src_snap = doc.node(src).unwrap().clone(); for _ in 0..2000 { let mut m = src_snap.clone();