M11: widgets draw lines and SVG pictures (plugin API 6) (#1727)

A widget description can have a line, 100 long and black and 1 thick unless told
otherwise, and an SVG that comes in as locked layers, scaled to fit a size and
within the widget's 256 layers. The Counter example uses both.
This commit is contained in:
BFlat
2026-10-31 08:13:08 +07:00
committed by GitHub
parent 59c7624569
commit 1c5c9e04c3
14 changed files with 347 additions and 65 deletions
+2 -1
View File
File diff suppressed because one or more lines are too long
+46 -13
View File
@@ -16,7 +16,7 @@
use figcraft_color::{ImageScaleMode, Paint};
use figcraft_doc::{Document, Node, NodeId, NodeKind, TextData};
use figcraft_geom::{Affine, Point};
use figcraft_plugin::widget::{MAX_IMAGE_BYTES, MAX_STATE_BYTES, check_menu, check_state, clean_field};
use figcraft_plugin::widget::{MAX_IMAGE_BYTES, MAX_NODES, MAX_STATE_BYTES, check_menu, check_state, clean_field};
use figcraft_plugin::{Instance, Manifest, RunOutput, UiChange, WidgetHover, WidgetKind, WidgetNode, WidgetRender};
pub use figcraft_plugin::{MenuItem, MenuKind};
use serde_json::{Map, Value, json};
@@ -190,6 +190,7 @@ fn callback(s: &mut Session, p: &InstalledPlugin, w: NodeId, event: Option<Value
let mut out = call_plugin(s, m, &m.name, &mut instance, &input.to_string()).map_err(|(e, _)| e)?;
match out.widget.take() {
Some(r) if m.api < 4 && r.uses_api_4() => return Err(bad("widget.render", format!("{}: fields and menus need plugin API 4", m.name))),
Some(r) if m.api < 6 && r.uses_api_6() => return Err(bad("widget.render", format!("{}: lines and SVG need plugin API 6", m.name))),
Some(r) => build(s, &m.id, w, &r)?,
None if inserting => return Err(bad("widget.insert", format!("{} drew no widget", m.name))),
None => {}
@@ -262,6 +263,10 @@ fn build(s: &mut Session, plugin: &str, w: NodeId, r: &WidgetRender) -> Result<(
for c in &r.root.children {
add(doc, w, c, cmd)?;
}
// An SVG brings as many layers as it describes.
if doc.subtree(w).len() > MAX_NODES {
return Err(bad(cmd, format!("the widget has more than {MAX_NODES} layers")));
}
crate::normalize(doc, &before);
Ok(())
}
@@ -274,19 +279,14 @@ fn add(doc: &mut Document, parent: NodeId, d: &WidgetNode, cmd: &str) -> Result<
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"),
WidgetKind::Line => (NodeKind::Line, "Line"),
WidgetKind::Svg => return add_svg(doc, parent, d, cmd),
};
let name = if d.name.is_empty() { name.to_string() } else { d.name.clone() };
let id = doc.alloc_id();
let mut n = Node::new(id, kind, name, d.width.unwrap_or(100.0), d.height.unwrap_or(100.0));
n.transform = Affine::translate((d.x.unwrap_or(0.0), d.y.unwrap_or(0.0)));
n.locked = true;
if !d.target.is_empty() {
n.plugin_data.insert(TARGET.into(), d.target.clone());
}
if !d.field.is_empty() {
n.plugin_data.insert(FIELD.into(), d.field.clone());
}
set_hover(&mut n, d.hover.as_ref());
let height = if d.kind == WidgetKind::Line { 0.0 } else { d.height.unwrap_or(100.0) };
let mut n = Node::new(id, kind, name, d.width.unwrap_or(100.0), height);
mark(&mut n, d);
if d.kind == WidgetKind::Image {
use base64::Engine as _;
let bytes = base64::engine::general_purpose::STANDARD.decode(d.data.trim()).map_err(|e| bad(cmd, format!("an image's `data`: {e}")))?;
@@ -306,6 +306,38 @@ fn add(doc: &mut Document, parent: NodeId, d: &WidgetNode, cmd: &str) -> Result<
d.children.iter().try_for_each(|c| add(doc, id, c, cmd))
}
/// Add SVG layer `d` inside `parent`: a frame of the picture's own size holding its layers, locked
/// like the rest. A `width` or `height` scales the picture to fit, keeping its proportions.
fn add_svg(doc: &mut Document, parent: NodeId, d: &WidgetNode, cmd: &str) -> Result<()> {
let name = if d.name.is_empty() { "SVG" } else { &d.name };
let id = figcraft_svg::import_svg(doc, d.src.as_bytes(), parent, 0.0, 0.0, name).map_err(|e| bad(cmd, e.to_string()))?;
let n = doc.get(id)?;
let scales = [d.width.map(|w| w / n.width), d.height.map(|h| h / n.height)];
if let Some(k) = scales.into_iter().flatten().reduce(f64::min) {
crate::cmd::arrange::scale_node(doc, id, k)?;
}
for i in doc.subtree(id) {
doc.get_mut(i)?.locked = true;
}
mark(doc.get_mut(id)?, d);
crate::cmd::props::apply(cmd, doc, id, &props(d, false))
}
/// Give layer `n` what description `d` says of every kind of layer: its place, its lock and its
/// layer data.
fn mark(n: &mut Node, d: &WidgetNode) {
let turn = -d.rotation.unwrap_or(0.0).to_radians();
n.transform = Affine::translate((d.x.unwrap_or(0.0), d.y.unwrap_or(0.0))) * Affine::rotate(turn);
n.locked = true;
if !d.target.is_empty() {
n.plugin_data.insert(TARGET.into(), d.target.clone());
}
if !d.field.is_empty() {
n.plugin_data.insert(FIELD.into(), d.field.clone());
}
set_hover(n, d.hover.as_ref());
}
/// Keep layer `n`'s hover style (validated already) with it, or drop the one it had.
fn set_hover(n: &mut Node, hover: Option<&WidgetHover>) {
match hover.and_then(|h| serde_json::to_string(h).ok()) {
@@ -333,10 +365,11 @@ fn props(d: &WidgetNode, root: bool) -> Map<String, Value> {
// A text with a width wraps; one without grows with its text.
set("textAutoResize", json!(if d.width.is_some() { "height" } else { "widthAndHeight" }));
}
WidgetKind::Image => {}
WidgetKind::Image | WidgetKind::Svg => {}
_ => set("fills", json!(d.fill.iter().collect::<Vec<_>>())),
}
if let Some(c) = &d.stroke {
let line = d.kind == WidgetKind::Line;
if let Some(c) = d.stroke.as_deref().or(line.then_some("#000000")) {
set("strokes", json!([c]));
set("strokeWeight", json!(d.stroke_weight.unwrap_or(1.0)));
} else if root {
+2
View File
@@ -623,6 +623,8 @@ mod widget_input_tests;
#[cfg(test)]
mod widget_panel_tests;
#[cfg(test)]
mod widget_shapes_tests;
#[cfg(test)]
mod widgets_tests;
#[cfg(test)]
+148
View File
@@ -0,0 +1,148 @@
//! Lines and SVG in a widget (plugin API 6), as a Figma widget's `Line` and `SVG` draw: a line is
//! 100 long, black and 1 thick by default and turns around its top-left corner; an SVG comes in as
//! locked layers, scaled to fit a size; a click on it reaches the plugin, and one with too many
//! layers leaves the widget as it was.
use std::fmt::Write as _;
use serde_json::{Value, json};
use crate::Session;
use crate::components::tests::{ex, idv, node};
use crate::plugins_tests::{install, undo_len};
use crate::widgets_tests::{W, err};
use figcraft_doc::{NodeId, NodeKind};
use figcraft_geom::rotation_degrees;
const ID: &str = "org.test.shapes";
const ICON: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="24" height="12"><rect width="24" height="12" fill="#ff0000"/><circle cx="6" cy="6" r="4" fill="#00ff00"/></svg>"##;
fn widget(children: Value) -> Value {
json!({"root": {"type": "frame", "width": 200, "height": 100, "fill": "#FFFFFF", "children": children}})
}
/// A session with a plugin of `api` that draws `v` when inserted, `clicked` when clicked.
fn session_with(api: u32, v: &Value, clicked: &Value) -> Session {
let mut w = W::default();
let click = w.has(r#""target":"icon""#);
let (first, second) = (w.render(v), w.render(clicked));
let wasm = w.build(&format!("(if {click} (then {second} (return (i32.const 0)))) {first}"));
let mut s = Session::new();
let m = json!({"id": ID, "name": "Shapes", "version": "1.0.0", "main": "s.wasm", "api": api, "widget": true, "permissions": {"access": "read"}});
install(&mut s, m, &wasm);
s
}
fn insert(s: &mut Session) -> NodeId {
idv(&ex(s, "widget.insert", json!({"plugin": ID, "x": 40, "y": 40})))
}
fn only_child(s: &Session, w: NodeId) -> NodeId {
let children = &node(s, w).children;
assert_eq!(children.len(), 1);
children[0]
}
#[test]
fn a_line_has_the_documented_defaults() {
let v = widget(json!([{"type": "line", "x": 10, "y": 20}]));
let mut s = session_with(6, &v, &v);
let w = insert(&mut s);
let line = only_child(&s, w);
let n = node(&s, line);
assert!(matches!(n.kind, NodeKind::Line));
assert_eq!([n.width, n.height], [100.0, 0.0]);
assert!(n.locked);
assert_eq!(n.strokes.len(), 1);
assert!(matches!(n.strokes[0].kind, figcraft_color::PaintKind::Solid { color: c } if c.to_css_hex() == "#000000"));
assert_eq!(n.stroke.weight, 1.0);
}
#[test]
fn a_line_turns_around_its_top_left_corner() {
let v = widget(json!([{"type": "line", "x": 10, "y": 20, "width": 50, "rotation": 90, "stroke": "#0D99FF", "strokeWeight": 2}]));
let mut s = session_with(6, &v, &v);
let w = insert(&mut s);
let n = node(&s, only_child(&s, w));
assert!((rotation_degrees(n.transform) - 90.0).abs() < 1e-6);
let [.., e, f] = n.transform.as_coeffs();
assert_eq!([e, f], [10.0, 20.0], "the corner stays where the description puts it");
// Counter-clockwise on a y-down canvas: the far end is above the corner.
assert!(n.transform.as_coeffs()[1] < 0.0);
}
#[test]
fn an_svg_comes_in_as_locked_layers_of_its_own_size() {
let v = widget(json!([{"type": "svg", "name": "Icon", "src": ICON, "x": 8, "y": 4, "opacity": 0.5}]));
let mut s = session_with(6, &v, &v);
let w = insert(&mut s);
let icon = only_child(&s, w);
let n = node(&s, icon);
assert_eq!(n.name, "Icon");
assert_eq!([n.width, n.height], [24.0, 12.0]);
assert_eq!(n.opacity, 0.5);
assert_eq!(n.transform.as_coeffs()[4..], [8.0, 4.0]);
let doc = s.doc().unwrap();
let layers = doc.subtree(icon);
assert!(layers.len() > 1, "the picture's shapes are layers: {layers:?}");
assert!(layers.iter().all(|i| doc.node(*i).unwrap().locked), "nothing in it can be picked on its own");
}
#[test]
fn a_size_scales_the_svg_to_fit_keeping_its_proportions() {
for (size, expected) in [
(json!({"width": 48}), [48.0, 24.0]),
(json!({"height": 6}), [12.0, 6.0]),
(json!({"width": 48, "height": 6}), [12.0, 6.0]),
(json!({"width": 48, "height": 100}), [48.0, 24.0]),
] {
let mut d = json!({"type": "svg", "src": ICON});
d.as_object_mut().unwrap().extend(size.as_object().unwrap().clone());
let v = widget(json!([d]));
let mut s = session_with(6, &v, &v);
let w = insert(&mut s);
let n = node(&s, only_child(&s, w));
assert_eq!([n.width, n.height], expected, "{size}");
let circle = *n.children.last().unwrap();
assert!((node(&s, circle).width - expected[0] / 3.0).abs() < 1e-6, "{size}: what's inside scaled too");
}
}
#[test]
fn a_click_on_an_svg_calls_the_plugin_back() {
let v = widget(json!([{"type": "svg", "target": "icon", "src": ICON}]));
let after = widget(json!([{"type": "line", "name": "Clicked"}]));
let mut s = session_with(6, &v, &after);
let w = insert(&mut s);
ex(&mut s, "widget.click", json!({"id": w, "target": "icon"}));
assert_eq!(node(&s, only_child(&s, w)).name, "Clicked");
}
#[test]
fn an_older_plugin_cant_use_them() {
for kind in [json!({"type": "line"}), json!({"type": "svg", "src": ICON})] {
let v = widget(json!([kind]));
let mut s = session_with(5, &v, &v);
let e = err(&mut s, "widget.insert", json!({"plugin": ID, "x": 0, "y": 0}));
assert!(e.contains("need plugin API 6"), "{e}");
}
}
#[test]
fn an_svg_of_too_many_layers_or_junk_leaves_the_widget_as_it_was() {
let mut many = String::from(r#"<svg xmlns="http://www.w3.org/2000/svg" width="300" height="10">"#);
for i in 0..300 {
write!(many, r##"<rect x="{i}" width="1" height="10" fill="#000000"/>"##).unwrap();
}
many.push_str("</svg>");
for (bad, why) in [(many.as_str(), "more than"), ("not an svg", "")] {
let fine = widget(json!([{"type": "line", "name": "Fine", "target": "icon"}]));
let mut s = session_with(6, &fine, &widget(json!([{"type": "svg", "target": "icon", "src": bad}])));
let w = insert(&mut s);
let undo = undo_len(&s);
let e = err(&mut s, "widget.click", json!({"id": w, "target": "icon"}));
assert!(e.contains(why), "{e}");
assert_eq!(node(&s, only_child(&s, w)).name, "Fine");
assert_eq!(undo_len(&s), undo);
}
}
+1 -1
View File
@@ -8,7 +8,7 @@ use serde_json::{Map, Value};
/// The manifest's file name.
pub const MANIFEST_FILE: &str = "figcraft-plugin.json";
/// The plugin API version this build implements (`api` in the manifest).
pub const API_VERSION: u32 = 5;
pub const API_VERSION: u32 = 6;
/// Largest manifest read.
pub const MAX_MANIFEST_BYTES: usize = 256 * 1024;
+2 -2
View File
@@ -441,7 +441,7 @@ fn bad_manifests_are_refused() {
json!({"main": "C:\\plugin.wasm"}),
json!({"main": "plugin.js"}),
json!({"main": "a//b.wasm"}),
json!({"api": 6}),
json!({"api": crate::API_VERSION + 1}),
json!({"api": 0}),
json!({"permissions": {"access": "root"}}),
json!({"permissions": {"commands": ["*.x"]}}),
@@ -469,6 +469,6 @@ fn api_may_be_a_version_string() {
assert_eq!(manifest(json!({"api": "1.0.0"})).unwrap().api, 1);
assert_eq!(manifest(json!({"api": "2"})).unwrap().api, 2);
assert_eq!(manifest(json!({"api": 2})).unwrap().api, 2);
assert!(manifest(json!({"api": "6.0.0"})).is_err());
assert!(manifest(json!({"api": format!("{}.0.0", crate::API_VERSION + 1)})).is_err());
assert!(manifest(json!({"api": "x"})).is_err());
}
+79 -31
View File
@@ -42,6 +42,10 @@ pub enum WidgetKind {
Ellipse,
/// A rectangle filled with an image (PNG, JPEG…) the plugin carries in its module.
Image,
/// API 6: a straight line, its `width` long.
Line,
/// API 6: a picture the plugin describes as SVG text, as layers.
Svg,
}
/// Auto layout direction of a frame.
@@ -118,6 +122,13 @@ pub struct WidgetNode {
/// An image layer's bytes, base64.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub data: String,
/// An SVG layer's text.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub src: String,
/// A line's or SVG's rotation around its top-left corner, in degrees; positive turns
/// counter-clockwise.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rotation: Option<f64>,
/// How the layer looks while the pointer is over it (hosts that don't know it draw the layer
/// as it is).
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -156,8 +167,11 @@ impl WidgetHover {
if self.fill.is_some() && text {
return Err("a text layer's hover takes `color`, not `fill`".into());
}
if self.fill.is_some() && kind == WidgetKind::Image {
return Err("an image layer's hover takes no `fill`".into());
if self.fill.is_some() && matches!(kind, WidgetKind::Image | WidgetKind::Line | WidgetKind::Svg) {
return Err(format!("a {kind:?} layer's hover takes no `fill`"));
}
if self.stroke.is_some() && kind == WidgetKind::Svg {
return Err("an SVG layer's hover takes no `stroke`".into());
}
if *self == WidgetHover::default() {
return Err("`hover` needs a fill, stroke, opacity or color".into());
@@ -233,10 +247,12 @@ impl WidgetRender {
/// Whether it uses what plugin API 4 added (fields or a menu).
pub fn uses_api_4(&self) -> bool {
fn field(n: &WidgetNode) -> bool {
!n.field.is_empty() || n.children.iter().any(field)
}
!self.menu.is_empty() || field(&self.root)
!self.menu.is_empty() || self.root.any(&|n| !n.field.is_empty())
}
/// Whether it uses what plugin API 6 added (lines or SVG).
pub fn uses_api_6(&self) -> bool {
self.root.any(&|n| matches!(n.kind, WidgetKind::Line | WidgetKind::Svg))
}
}
@@ -326,6 +342,59 @@ fn colour(what: &str, c: &mut Option<String>) -> Result<(), String> {
}
impl WidgetNode {
/// Whether this layer or one inside it passes `test`.
fn any(&self, test: &dyn Fn(&WidgetNode) -> bool) -> bool {
test(self) || self.children.iter().any(|c| c.any(test))
}
/// Refuse what doesn't apply to this kind of layer.
fn check_applies(&self) -> Result<(), String> {
let kind = self.kind;
let only = |what: &str, used: bool, allowed: bool| {
if used && !allowed { Err(format!("`{what}` doesn't apply to a {kind:?} layer")) } else { Ok(()) }
};
only("children", !self.children.is_empty(), kind == WidgetKind::Frame)?;
only(
"layout",
self.layout.is_some() || self.gap.is_some() || self.padding.is_some() || self.align.is_some() || self.justify.is_some(),
kind == WidgetKind::Frame,
)?;
only("text", !self.text.is_empty() || self.size.is_some() || self.color.is_some() || self.bold, kind == WidgetKind::Text)?;
only("data", !self.data.is_empty(), kind == WidgetKind::Image)?;
only("field", !self.field.is_empty(), kind == WidgetKind::Text)?;
only("src", !self.src.is_empty(), kind == WidgetKind::Svg)?;
only("rotation", self.rotation.is_some(), matches!(kind, WidgetKind::Line | WidgetKind::Svg))?;
only("height", self.height.is_some(), kind != WidgetKind::Line)?;
only("fill", self.fill.is_some(), !matches!(kind, WidgetKind::Line | WidgetKind::Svg))?;
only("stroke", self.stroke.is_some() || self.stroke_weight.is_some(), kind != WidgetKind::Svg)
}
/// Check an image's or SVG's size, on its own and with the others of the widget.
fn check_bytes(&self, budget: &mut Budget) -> Result<(), String> {
let bytes = match self.kind {
WidgetKind::Image => {
// Base64: four characters for three bytes (checked again when decoded).
let bytes = self.data.trim().len() / 4 * 3;
if self.data.trim().is_empty() || bytes > MAX_IMAGE_BYTES + 3 {
return Err(format!("an image needs `data` (base64) of at most {} KB", MAX_IMAGE_BYTES / 1024));
}
bytes
}
WidgetKind::Svg => {
if self.src.trim().is_empty() || self.src.len() > MAX_IMAGE_BYTES {
return Err(format!("an SVG needs `src` of at most {} KB", MAX_IMAGE_BYTES / 1024));
}
self.src.len()
}
_ => return Ok(()),
};
budget.image_bytes += bytes;
if budget.image_bytes > MAX_IMAGES_BYTES + 3 {
return Err(format!("the images are larger than {} MB together", MAX_IMAGES_BYTES / (1024 * 1024)));
}
Ok(())
}
fn check(&mut self, depth: usize, budget: &mut Budget) -> Result<(), String> {
budget.nodes += 1;
if budget.nodes > MAX_NODES {
@@ -349,25 +418,14 @@ impl WidgetNode {
}
within("strokeWeight", self.stroke_weight, 0.0, 64.0)?;
within("opacity", self.opacity, 0.0, 1.0)?;
within("rotation", self.rotation, -180.0, 180.0)?;
within("size", self.size, 1.0, 256.0)?;
colour("fill", &mut self.fill)?;
colour("stroke", &mut self.stroke)?;
colour("color", &mut self.color)?;
let kind = self.kind;
let only = |what: &str, used: bool, allowed: bool| {
if used && !allowed { Err(format!("`{what}` doesn't apply to a {kind:?} layer")) } else { Ok(()) }
};
only("children", !self.children.is_empty(), kind == WidgetKind::Frame)?;
only(
"layout",
self.layout.is_some() || self.gap.is_some() || self.padding.is_some() || self.align.is_some() || self.justify.is_some(),
kind == WidgetKind::Frame,
)?;
only("text", !self.text.is_empty() || self.size.is_some() || self.color.is_some() || self.bold, kind == WidgetKind::Text)?;
only("data", !self.data.is_empty(), kind == WidgetKind::Image)?;
only("field", !self.field.is_empty(), kind == WidgetKind::Text)?;
self.check_applies()?;
if let Some(h) = &mut self.hover {
h.check(kind)?;
h.check(self.kind)?;
}
if self.text.chars().count() > MAX_TEXT {
return Err(format!("a text is longer than {MAX_TEXT} characters"));
@@ -375,17 +433,7 @@ impl WidgetNode {
if self.text.chars().any(|c| c.is_control() && c != '\n') {
return Err("a text contains control characters".into());
}
if kind == WidgetKind::Image {
// Base64: four characters for three bytes (checked again when decoded).
let bytes = self.data.trim().len() / 4 * 3;
if self.data.trim().is_empty() || bytes > MAX_IMAGE_BYTES + 3 {
return Err(format!("an image needs `data` (base64) of at most {} KB", MAX_IMAGE_BYTES / 1024));
}
budget.image_bytes += bytes;
if budget.image_bytes > MAX_IMAGES_BYTES + 3 {
return Err(format!("the images are larger than {} MB together", MAX_IMAGES_BYTES / (1024 * 1024)));
}
}
self.check_bytes(budget)?;
self.children.iter_mut().try_for_each(|c| c.check(depth + 1, budget))
}
}
+30 -1
View File
@@ -110,7 +110,7 @@ fn widgets_need_api_3() {
assert!(m(2).unwrap_err().contains("API 3"));
let ok = m(3).unwrap();
assert!(ok.widget && ok.commands.is_empty(), "a widget-only plugin has no menu command");
assert!(Manifest::from_value(&json!({"id": "w", "name": "W", "main": "w.wasm", "api": 6})).is_err());
assert!(Manifest::from_value(&json!({"id": "w", "name": "W", "main": "w.wasm", "api": crate::API_VERSION + 1})).is_err());
let v2 = Manifest::from_value(&json!({"id": "p", "name": "P", "main": "p.wasm", "api": 2})).unwrap();
assert!(!v2.widget && v2.commands.len() == 1, "v2 manifests are unchanged");
}
@@ -181,3 +181,32 @@ fn hover_styles_are_checked_and_normalised() {
}
assert!(!w.uses_api_4(), "a hover style needs no new API: older hosts draw the layer as it is");
}
#[test]
fn lines_and_svg_are_checked() {
let parse = |layer: Value| WidgetRender::parse(&json!({"root": {"type": "frame", "children": [layer]}}).to_string());
let svg = "<svg xmlns='http://www.w3.org/2000/svg' width='4' height='4'/>";
assert!(parse(json!({"type": "line", "width": 40, "rotation": -90, "stroke": "#000000", "hover": {"stroke": "#FF0000"}})).unwrap().uses_api_6());
let good = parse(json!({"type": "svg", "src": svg, "width": 8, "rotation": 180, "hover": {"opacity": 0.5}})).unwrap();
assert!(good.uses_api_6() && !good.uses_api_4());
assert!(!parse(json!({"type": "rectangle"})).unwrap().uses_api_6());
for (layer, why) in [
(json!({"type": "line", "height": 4}), "`height`"),
(json!({"type": "line", "fill": "#000000"}), "`fill`"),
(json!({"type": "line", "rotation": 181}), "`rotation`"),
(json!({"type": "line", "hover": {"fill": "#000000"}}), "`fill`"),
(json!({"type": "rectangle", "rotation": 10}), "`rotation`"),
(json!({"type": "rectangle", "src": svg}), "`src`"),
(json!({"type": "svg"}), "`src`"),
(json!({"type": "svg", "src": " "}), "`src`"),
(json!({"type": "svg", "src": "x".repeat(MAX_IMAGE_BYTES + 1)}), "`src`"),
(json!({"type": "svg", "src": svg, "fill": "#000000"}), "`fill`"),
(json!({"type": "svg", "src": svg, "stroke": "#000000"}), "`stroke`"),
(json!({"type": "svg", "src": svg, "strokeWeight": 2}), "`stroke`"),
(json!({"type": "svg", "src": svg, "hover": {"stroke": "#000000"}}), "`stroke`"),
(json!({"type": "svg", "src": svg, "children": [{"type": "line"}]}), "`children`"),
] {
let e = parse(layer.clone()).unwrap_err();
assert!(e.contains(why), "{layer}: {e}");
}
}
+5 -2
View File
@@ -1,6 +1,6 @@
# Where FigCraft falls short of Figma
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (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-10-31 · **Change:** minor (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
@@ -265,9 +265,11 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
256 KB and 4,096 pixels on a side), as wide as a field at most, named by its label.
Widgets open panels (plugin API 5, 2026-10-30): a widget's callback can show its plugin's panel,
whose callbacks get the widget's id and state and redraw it, one undo step each.
Lines and SVG (plugin API 6, 2026-10-31): a widget layer can be a `line` or an `svg`, whose
picture comes in as locked layers, scaled to fit a size.
- **Missing:** a public catalogue and Community files, publisher accounts and signatures, ratings
and install counts, background update checks, the directory in the browser build; widgets have no
timers and draw only frames, text, shapes and images. Figma's own plugins are JavaScript against
timers. Figma's own plugins are JavaScript against
Figma's plugin API and don't run.
- **Impact:** teams that depend on specific Figma plugins (icons, content, accessibility checks)
can't bring them. FigCraft's CLI, control channel and MCP server cover agent automation better
@@ -587,6 +589,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
| Date | Change | Summary |
|---|---|---|
| 2026-10-30 | minor | Gap 7: text reads only the fallback fonts it draws with: a face per fallback family and style, a file's bytes shared between families, the faces worked out once per style (first text laid out: 41 font files and 265 MiB read down to 3 files and 20 MiB on a Linux machine with Noto Sans CJK). Numbers unchanged |
| 2026-10-31 | minor | Gap 6: widgets draw lines and SVG pictures (plugin API 6), so that item leaves the missing list. |
| 2026-10-31 | minor | Gap 24: connector paths can be reshaped by hand (path handles and `board.reshape`), so that item leaves the missing list. Estimate unchanged. Tests: `board_reshape_tests`, `board_line_tests`. |
| 2026-10-31 | minor | Gap 10: library analytics count insertions, and insertions and detachments week by week for a year (Show usage: the past 30 days, 90 days or year; `library.usage {days}`). Styles and variables aren't counted. Estimate unchanged. Tests: `library_actions_tests`, `inserting_library_instances_counts_them` |
| 2026-10-30 | minor | Gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks get the widget and redraw it; the Counter example sets its count from a panel. The entry's duplicated Missing text is merged. Estimate unchanged |
+15 -6
View File
@@ -19,8 +19,9 @@ permissions its manifest asks for, and nothing more.
- **Widgets (API 3).** A plugin can put a layer of its own on the canvas: it describes the layer
(frames with auto layout, text, shapes, images), FigCraft builds it, and a click on one of its
parts calls the plugin back to redraw it from its state, which is kept in the document. Since
API 4 a widget can also have editable text fields and a small property menu, and since API 5 it
can open its plugin's panel, whose buttons and fields redraw it.
API 4 a widget can also have editable text fields and a small property menu, since API 5 it
can open its plugin's panel, whose buttons and fields redraw it, and since API 6 it can draw
lines and SVG pictures.
- **Permissions.** The manifest says whether the plugin only reads the document or may edit it, and
can narrow the commands it may call. FigCraft enforces both.
- **Distribution.** A team's own `figcraft-server` can keep a plugin directory: plugins are
@@ -300,12 +301,13 @@ allocation or copy. This also applies when the configured per-call overhead is z
read is charged for the bytes actually returned, not the requested buffer size. `calls` counts
every ABI import, including calls which only query the reply length.
## ABI (version 5)
## ABI (version 6)
Version 2 adds panels and settings to version 1, version 3 adds widgets, version 4 adds
`save_file` and widget fields and property menus (new keys in the widget description and new
widget events), and version 5 lets a widget open its plugin's panel (no new imports); a module written for an older version runs unchanged and gets the input it always
got. A widget description with a field or a menu from a plugin whose manifest says `3` is refused,
widget events), version 5 lets a widget open its plugin's panel (no new imports), and version 6 adds lines and SVG to the widget description; a module written for an older version runs unchanged and gets the input it always
got. A widget description with a field or a menu from a plugin whose manifest says `3` is refused, as
is one with a line or an SVG from a manifest that says less than `6`,
and a FigCraft that runs an older API refuses a manifest that asks for `4` when it's imported. Strings are UTF-8 `(ptr, len)` pairs in the plugin's linear memory; all values
are `i32`.
@@ -413,7 +415,7 @@ that don't fit their field.
`state` is the widget's new state, a JSON object (left out: it keeps the one it has). `root` is the
widget itself, a frame; FigCraft replaces everything inside it with the layers described and keeps
the widget where it is (and its size, unless the description gives one). Every layer has a `type`
(`frame`, `text`, `rectangle`, `ellipse`, `image`) and may have a `name`, a `target` (clicking it
(`frame`, `text`, `rectangle`, `ellipse`, `image`, and with API 6 `line` and `svg`) and may have a `name`, a `target` (clicking it
calls the plugin back with that name: letters, digits, `.`, `-`, `_`), `x` and `y` (in its frame,
ignored in auto layout), `width` and `height`, `fill` and `stroke` (hex colours), `strokeWeight`,
`radius` (frames, rectangles, images) and `opacity`. A frame may have `layout` (`horizontal` or
@@ -423,6 +425,13 @@ with auto layout it hugs its contents on an axis without a size. A text has `tex
`color` and `bold` (with a `width` it wraps), and with API 4 may have a `field` (a name like a
target's): the text is then an editable field showing its current value. An image has `data`, the image's bytes (PNG, JPEG…)
as base64, usually carried in the module itself; without a size it takes the image's.
With API 6, a line is `width` long (100 without one), with `stroke` (black without one) and
`strokeWeight` (1); it has no height, so a click needs a clickable frame around it. An SVG has `src`,
the picture as SVG text (at most 1 MB, counted with the images), which comes in as layers of a frame
of the picture's size and takes neither `fill` nor `stroke`. A `width` or `height` scales it to fit,
keeping its proportions, and its layers count towards the widget's 256. Both may have `rotation`,
degrees from -180 to 180 around the top-left corner, positive counter-clockwise. A line's `hover`
takes no `fill` and an SVG's only `opacity`.
Any layer, the widget itself too, may have a `hover`: how it looks while the pointer is over
it on the canvas, with `fill` (a text: `color`), `stroke` and `opacity` replacing its own,
for example `"hover": {"fill": "#E0E0E0"}` on a button. It is shown as a live preview, never
+2 -1
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -4,7 +4,7 @@
"version": "1.2.0",
"description": "A widget that counts on the canvas: click its + and − buttons, double-click its label to edit it, and use its menu to reset it, set it in a panel, count in tens or colour it. Everything is kept in the document.",
"main": "counter.wasm",
"api": 5,
"api": 6,
"widget": true,
"permissions": { "access": "read" }
}
+12 -5
View File
@@ -1,7 +1,8 @@
//! Counter: a widget on the canvas with − and + buttons around a count, a label you can edit on the
//! canvas, and a property menu (reset, steps of ten, a colour). Each click, edit or menu choice
//! calls the plugin back with the widget's state; it hands back the new state and the redrawn
//! widget. Its menu's "Set count…" opens a panel (API 5) whose Set button redraws the widget.
//! widget. Its menu's "Set count…" opens a panel (API 5) whose Set button redraws the widget. An SVG
//! icon and a line (API 6) set off its label.
use figcraft_plugin_sdk::{Event, Input, Result, Value, Widget, close_ui, entry, json, render_widget, show_ui};
@@ -11,6 +12,8 @@ const LIMIT: i64 = 999_999;
const COLORS: [&str; 4] = ["#1E1E1E", "#0D99FF", "#14AE5C", "#F24822"];
/// Shown in the label field while it's empty.
const PLACEHOLDER: &str = "Add a label";
/// Four tally marks and a stroke across them.
const ICON: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="none" stroke="#757575" stroke-width="1.2" stroke-linecap="round"><path d="M2 2v8M4.5 2v8M7 2v8M9.5 2v8M1 9l10-6"/></svg>"##;
/// What the widget shows.
#[derive(Debug, PartialEq)]
@@ -63,7 +66,11 @@ fn view(c: &Counter, label: &str) -> Value {
let (minus, plus) = if c.big { ("−10", "+10") } else { ("−", "+") };
json!({"type": "frame", "name": "Counter", "layout": "vertical", "gap": 6, "padding": 12, "radius": 12, "align": "min",
"fill": "#FFFFFF", "stroke": "#D9D9D9", "children": [
{"type": "text", "name": "Label", "field": "label", "text": text, "size": 12, "color": ink},
{"type": "frame", "name": "Header", "layout": "horizontal", "gap": 6, "children": [
{"type": "svg", "name": "Icon", "src": ICON},
{"type": "text", "name": "Label", "field": "label", "text": text, "size": 12, "color": ink},
]},
{"type": "line", "name": "Rule", "width": 120, "stroke": "#E6E6E6"},
{"type": "frame", "name": "Row", "layout": "horizontal", "gap": 12, "children": [
button("decrement", "Decrease", minus),
{"type": "text", "name": "Count", "text": c.count.to_string(), "size": 24, "bold": true, "color": c.color},
@@ -156,10 +163,10 @@ mod tests {
assert_eq!(c(1).next(&widget(None, Some("color"), json!("#123456"))).color, COLORS[0], "only the colours offered");
assert_eq!(Counter::from_state(&json!({"count": 3, "color": "junk"})), c(3));
let v = view(&c(3), "Score");
assert_eq!((v["children"][0]["text"].clone(), v["children"][1]["children"][1]["text"].clone()), (json!("Score"), json!("3")));
assert_eq!(view(&c(3), " ")["children"][0]["text"], PLACEHOLDER);
assert_eq!((v["children"][0]["children"][1]["text"].clone(), v["children"][2]["children"][1]["text"].clone()), (json!("Score"), json!("3")));
assert_eq!(view(&c(3), " ")["children"][0]["children"][1]["text"], PLACEHOLDER);
assert_eq!(menu(&c(0))[2]["checked"], false);
assert_eq!(v["children"][1]["children"][0]["hover"], json!({"fill": "#E0E0E0"}), "buttons darken under the pointer");
assert_eq!(v["children"][2]["children"][0]["hover"], json!({"fill": "#E0E0E0"}), "buttons darken under the pointer");
assert!(run(Input::default()).is_err(), "it only runs as a widget");
let ev = |control: &str, count: Value| Event { control: control.into(), values: json!({"count": count}), ..Event::default() };
assert_eq!(from_panel(c(3), &ev("set", json!(42.0))).count, 42);