M10: SwiftUI, Compose and Flutter code export writes every colour and gradient fill, in paint order (#2271)

Part of #2271. The native targets took ONE colour from a layer (`first_fill`: the bottom visible solid, or a gradient's first stop) and dropped every other fill, so a frame with white, a gradient and 50% black came out as flat white.

Now SwiftUI, Compose and Flutter write every visible solid and gradient fill of a frame, group, rectangle or ellipse, in paint order, and a gradient as a gradient. A shared `visible_fills` gives each target the same list (document order, bottom first); each target only formats it.

- SwiftUI: chained `.background(...)`, top fill first, since each one goes behind the ones before it. A rectangle or ellipse fills with the bottom paint and lays a copy of the shape over it (`.overlay`) for each paint above, bottom first.
- Compose: chained `Modifier.background(...)`, bottom fill first, since each one draws over the ones before it. A linear gradient snaps to one of eight directions (a modifier doesn't know pixels); radial and angular ones sit at the box's centre.
- Flutter: a `BoxDecoration` paints one colour or gradient, so the Container keeps the top fill and each fill under it becomes a `DecoratedBox` around the widget, the bottom fill outermost. The drop shadow goes on the outermost box so it never lies over a lower fill. An instance's call is now made once, in `flutter_placed`.

A layer with one solid fill gives the same code as before, variable names included (only the paint at index 0, when solid, takes the `fill` variable's name). A lone gradient used to come out as its first stop's colour and is now a gradient.

Still not written: image and pattern fills in the native targets, ArkUI (one background and one gradient per component, so a stack needs extra nodes) and text with several fills. Figma's iOS and Android output was not measured: the order follows how each platform paints.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Model-Effort: Opus 5.5 drove; Fable 5.2 briefed; Sonnet 5.5 wrote at medium
This commit is contained in:
Trevor BrownandClaude Sonnet 5.5 committed 2026-11-12 17:04:23 -05:00
1 parent 0d6ce1124c
commit e276b1e4ff
5 files changed
+423 -33

No files matched your search

+56 -3
View File
@@ -1,6 +1,7 @@
use super::swift::one_line;
use super::{
CodeLang, Color, Ctx, LayoutMode, Node, NodeId, NodeKind, PADDING, drop_shadow, first_fill, indent, literal, named, num, radius, stroke_color,
CodeLang, Color, Ctx, GradientKind, LayoutMode, Node, NodeId, NodeKind, PADDING, Paint, PaintKind, drop_shadow, first_fill, gradient_axis,
gradient_stops, indent, literal, named, native_gradient_kind, num, radius, stroke_color, visible_fills,
};
use figcraft_doc::Document;
@@ -22,14 +23,66 @@ fn bound_dp(doc: &Document, n: &Node, fields: &[&str], value: f64) -> String {
bound(doc, n, fields, format!("{}.dp", num(value)))
}
/// One end of a linear brush's axis along one direction: `sign` is 0 for none, 1 for with the
/// axis and -1 against it. `Float.POSITIVE_INFINITY` stands for the far edge, which a modifier
/// can't know in pixels.
fn compose_edge(sign: i8) -> (&'static str, &'static str) {
match sign {
0 => ("0f", "0f"),
s if s > 0 => ("0f", "Float.POSITIVE_INFINITY"),
_ => ("Float.POSITIVE_INFINITY", "0f"),
}
}
/// A direction's sign: its component counts as none when it is at most tan 22.5 degrees of the other.
fn compose_sign(v: f64, other: f64) -> i8 {
if v.abs() <= 0.4142 * other.abs() {
0
} else if v > 0.0 {
1
} else {
-1
}
}
/// A gradient fill as a Compose `Brush` for a `w` x `h` layer. A linear gradient snaps to the
/// nearest of eight directions; radial and angular ones sit at the box's centre.
fn compose_gradient(g: &figcraft_color::Gradient, w: f64, h: f64, opacity: f32) -> String {
let stops = gradient_stops(g, opacity).into_iter().map(|(at, c)| format!("{}f to {}", num(at), kotlin_color(c))).collect::<Vec<_>>().join(", ");
match native_gradient_kind(g) {
GradientKind::Linear => {
let (dx, dy) = gradient_axis(g, w, h);
let (sx, sy) = if dx == 0.0 && dy == 0.0 { (0, 1) } else { (compose_sign(dx, dy), compose_sign(dy, dx)) };
let ((x0, x1), (y0, y1)) = (compose_edge(sx), compose_edge(sy));
format!("Brush.linearGradient({stops}, start = Offset({x0}, {y0}), end = Offset({x1}, {y1}))")
}
GradientKind::Angular => format!("Brush.sweepGradient({stops})"),
_ => format!("Brush.radialGradient({stops})"),
}
}
/// One paint (the one at document index `i`) as the first argument of `background`; `None` for an
/// image or pattern. Only a solid at index 0 takes the `fill` variable's name.
fn compose_paint(doc: &Document, n: &Node, i: usize, p: &Paint) -> Option<String> {
match &p.kind {
PaintKind::Solid { .. } => {
let c = kotlin_color(p.solid_color()?);
Some(if i == 0 { bound(doc, n, &["fill"], c) } else { c })
}
PaintKind::Gradient(g) => Some(compose_gradient(g, n.width, n.height, p.opacity)),
PaintKind::Image(_) | PaintKind::Pattern(_) => None,
}
}
/// The Modifier chain for a layer (size, shadow, background, border, alpha, padding).
fn modifier(doc: &Document, n: &Node, shape: &str, padding: bool) -> String {
let mut m = format!("Modifier.size({}, {})", bound_dp(doc, n, &["width"], n.width), bound_dp(doc, n, &["height"], n.height));
if let Some(s) = drop_shadow(n) {
m.push_str(&format!(".shadow({}.dp, {shape})", num(s.radius / 2.0)));
}
if let Some(c) = first_fill(n) {
m.push_str(&format!(".background({}, {shape})", bound(doc, n, &["fill"], kotlin_color(c))));
// Each background draws and lets the rest of the chain draw over it: bottom fill first.
for b in visible_fills(n).filter_map(|(i, p)| compose_paint(doc, n, i, p)) {
m.push_str(&format!(".background({b}, {shape})"));
}
if let Some(c) = stroke_color(n) {
m.push_str(&format!(
+103 -17
View File
@@ -2,8 +2,9 @@ use figcraft_doc::AutoLayout;
use super::swift::one_line;
use super::{
CodeLang, CrossAlign, Ctx, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, Param, Sizing, TextAlignH, TextDecoration,
drop_shadow, first_fill, kotlin_color, literal, num, radius, stroke_color,
CodeLang, CrossAlign, Ctx, GradientKind, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, Paint, PaintKind, Param,
Sizing, TextAlignH, TextDecoration, drop_shadow, first_fill, gradient_axis, gradient_stops, kotlin_color, literal, native_gradient_kind, num,
radius, stroke_color, visible_fills,
};
// ------------------------------------------------------------------ Flutter (Dart)
@@ -74,22 +75,72 @@ fn flutter_padding(n: &Node) -> Option<String> {
})
}
/// A gradient's colours and stops, the tail of every Flutter gradient constructor.
fn flutter_colors(g: &figcraft_color::Gradient, opacity: f32) -> String {
let stops = gradient_stops(g, opacity);
let colors = stops.iter().map(|(_, c)| kotlin_color(*c)).collect::<Vec<_>>().join(", ");
let at = stops.iter().map(|(at, _)| num(*at)).collect::<Vec<_>>().join(", ");
format!("colors: [{colors}], stops: [{at}]")
}
/// A point of the unit box as Flutter's `Alignment`, which runs from -1 to 1.
fn flutter_alignment(p: (f64, f64)) -> String {
format!("Alignment({}, {})", num(2.0 * p.0 - 1.0), num(2.0 * p.1 - 1.0))
}
/// A gradient fill on a layer of `w` x `h` as a Flutter gradient.
fn flutter_gradient(g: &figcraft_color::Gradient, w: f64, h: f64, opacity: f32) -> String {
let (dx, dy) = gradient_axis(g, w, h);
let (tail, from) = (flutter_colors(g, opacity), flutter_alignment(g.from));
match native_gradient_kind(g) {
GradientKind::Linear => format!("LinearGradient(begin: {from}, end: {}, {tail})", flutter_alignment(g.to)),
GradientKind::Angular => format!("SweepGradient(center: {from}, {tail}, transform: GradientRotation({}))", num(dy.atan2(dx))),
_ => {
// Flutter's radius is a fraction of the box's shorter side.
let (reach, side) = (dx.hypot(dy), w.min(h));
let radius = if reach > 0.0 && side > 0.0 { reach / side } else { 0.5 };
format!("RadialGradient(center: {from}, radius: {}, {tail})", num(radius))
}
}
}
/// One paint as a `BoxDecoration` part (`color: ...` or `gradient: ...`); `None` for an image or
/// pattern, which no native target writes yet.
fn flutter_paint(n: &Node, p: &Paint) -> Option<String> {
match &p.kind {
PaintKind::Solid { .. } => Some(format!("color: {}", kotlin_color(p.solid_color()?))),
PaintKind::Gradient(g) => Some(format!("gradient: {}", flutter_gradient(g, n.width, n.height, p.opacity))),
PaintKind::Image(_) | PaintKind::Pattern(_) => None,
}
}
/// Whether a layer is written as a `Container`: the layers with a box to paint.
fn paints_a_box(n: &Node) -> bool {
matches!(n.kind, NodeKind::Ellipse { .. } | NodeKind::Rectangle | NodeKind::Group) || n.kind.is_frame_like()
}
/// A layer's fills as `BoxDecoration` parts, bottom first.
fn flutter_fill_parts(n: &Node) -> Vec<String> {
visible_fills(n).filter_map(|(_, p)| flutter_paint(n, p)).collect()
}
/// A layer's fill, shape, corner radius, stroke and shadow as a `BoxDecoration`; `None` when it has
/// none of them. `pad` is the indentation of the constructor itself.
fn box_decoration(n: &Node, pad: &str) -> Option<String> {
/// none of them. `pad` is the indentation of the constructor itself; `fill` is the one fill part
/// this decoration paints, and `stroke` and `shadow` say whether it carries those.
fn box_decoration(n: &Node, pad: &str, fill: Option<&str>, stroke: bool, shadow: bool) -> Option<String> {
let mut parts: Vec<String> = Vec::new();
if let Some(c) = first_fill(n) {
parts.push(format!("color: {}", kotlin_color(c)));
if let Some(f) = fill {
parts.push(f.to_string());
}
if matches!(n.kind, NodeKind::Ellipse { .. }) {
parts.push("shape: BoxShape.circle".into());
} else if radius(n) > 0.0 {
parts.push(format!("borderRadius: BorderRadius.circular({})", num(radius(n))));
}
if let Some(c) = stroke_color(n) {
if let Some(c) = stroke_color(n).filter(|_| stroke) {
parts.push(format!("border: Border.all(color: {}, width: {})", kotlin_color(c), num(n.stroke.weight)));
}
if let Some(s) = drop_shadow(n) {
if let Some(s) = drop_shadow(n).filter(|_| shadow) {
parts.push(format!(
"boxShadow: [BoxShadow(color: {}, blurRadius: {}, offset: Offset({}, {}))]",
kotlin_color(s.color),
@@ -105,6 +156,42 @@ fn box_decoration(n: &Node, pad: &str) -> Option<String> {
Some(format!("BoxDecoration(\n{}{pad})", parts.iter().map(|p| format!("{inner}{p},\n")).collect::<String>()))
}
/// What a `Container` paints itself: its own fill (the top one), and whether it carries the shadow
/// (only when no `DecoratedBox` does).
struct Painted {
fill: Option<String>,
shadow: bool,
}
/// Opens a `DecoratedBox` for each fill under the top one, the bottom fill outermost, and returns
/// what is left for the `Container`. The outermost box carries the drop shadow: a decoration paints
/// its shadow first, so on the `Container` it would lie over the lower fills.
fn flutter_fill_boxes(n: &Node, depth: &mut usize, close: &mut Vec<String>, out: &mut String) -> Painted {
let mut parts = flutter_fill_parts(n);
let top = parts.pop();
let shadow = parts.is_empty();
for (at, part) in parts.iter().enumerate() {
let (pad, inner) = (flutter_indent(*depth), flutter_indent(*depth + 1));
if close.is_empty() {
out.push_str(&pad);
}
let deco = box_decoration(n, &inner, Some(part), false, at == 0).unwrap_or_default();
out.push_str(&format!("DecoratedBox(\n{inner}decoration: {deco},\n{inner}child: "));
close.push(format!("\n{pad})"));
*depth += 1;
}
Painted { fill: top, shadow }
}
/// The call an instance below the root is (an instance swap parameter is a widget); `None` for
/// every other layer.
fn flutter_call(ctx: &Ctx, n: &Node, depth: usize) -> Option<String> {
match ctx.param(n, "mainComponent").filter(|_| n.id != ctx.root) {
Some(p) => Some(p.ident.clone()),
None => ctx.call(n, CodeLang::Flutter, depth).map(|(code, _)| code),
}
}
/// Flutter for a layer and its subtree at `depth`. A layer a boolean parameter shows sits behind an
/// `if (…)`: Dart's lists take conditions, so the element itself carries it.
pub(crate) fn flutter(ctx: &Ctx, id: NodeId, depth: usize, out: &mut String, place: Place) {
@@ -150,9 +237,13 @@ fn flutter_placed(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, place: Pl
close.push(format!("\n{pad})"));
depth += 1;
}
// An instance is a call, made once: it gets no fill boxes, so this is its final depth.
let call = flutter_call(ctx, n, depth);
let painted =
if call.is_none() && paints_a_box(n) { flutter_fill_boxes(n, &mut depth, &mut close, out) } else { Painted { fill: None, shadow: true } };
// A wrapper leaves its line open ("child: "), so the widget carries no indentation of its own.
let mut body = String::new();
flutter_widget(ctx, n, depth, &mut body);
flutter_widget(ctx, n, depth, call, &painted, &mut body);
out.push_str(if close.is_empty() { body.as_str() } else { body.trim_start() });
for c in close.iter().rev() {
out.push_str(c);
@@ -161,13 +252,8 @@ fn flutter_placed(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, place: Pl
/// A layer's own look and its subtree as a Flutter widget at `depth`: a complete expression whose
/// closing parenthesis sits at `depth`.
fn flutter_widget(ctx: &Ctx, n: &Node, depth: usize, out: &mut String) {
fn flutter_widget(ctx: &Ctx, n: &Node, depth: usize, call: Option<String>, painted: &Painted, out: &mut String) {
let (pad, inner) = (flutter_indent(depth), flutter_indent(depth + 1));
// Nested instances are calls; an instance swap parameter is a widget.
let call = match ctx.param(n, "mainComponent").filter(|_| n.id != ctx.root) {
Some(p) => Some(p.ident.clone()),
None => ctx.call(n, CodeLang::Flutter, depth).map(|(code, _)| code),
};
if let Some(call) = call {
out.push_str(call.trim_end_matches('\n'));
return;
@@ -216,7 +302,7 @@ fn flutter_widget(ctx: &Ctx, n: &Node, depth: usize, out: &mut String) {
}
NodeKind::Ellipse { .. } | NodeKind::Rectangle => {
out.push_str(&format!("{pad}Container(\n{inner}width: {},\n{inner}height: {},\n", num(n.width), num(n.height)));
if let Some(d) = box_decoration(n, &inner) {
if let Some(d) = box_decoration(n, &inner, painted.fill.as_deref(), true, painted.shadow) {
out.push_str(&format!("{inner}decoration: {d},\n"));
}
out.push_str(&format!("{pad})"));
@@ -232,7 +318,7 @@ fn flutter_widget(ctx: &Ctx, n: &Node, depth: usize, out: &mut String) {
if !padded_inside && let Some(p) = flutter_padding(n) {
out.push_str(&format!("{inner}padding: {p},\n"));
}
if let Some(d) = box_decoration(n, &inner) {
if let Some(d) = box_decoration(n, &inner, painted.fill.as_deref(), true, painted.shadow) {
out.push_str(&format!("{inner}decoration: {d},\n"));
}
if children.is_empty() && slot.is_none() {
+47 -10
View File
@@ -1,5 +1,6 @@
use super::{
CodeLang, Color, Ctx, LayoutMode, Node, NodeId, NodeKind, PADDING, drop_shadow, first_fill, indent, literal, named, num, radius, stroke_color,
CodeLang, Color, Ctx, Document, GradientKind, LayoutMode, Node, NodeId, NodeKind, PADDING, Paint, PaintKind, drop_shadow, first_fill,
gradient_axis, gradient_stops, indent, literal, named, native_gradient_kind, num, radius, stroke_color, visible_fills,
};
// ------------------------------------------------------------------ SwiftUI
@@ -8,6 +9,47 @@ fn swift_color(c: Color) -> String {
format!("Color(red: {}, green: {}, blue: {}, opacity: {})", num(f64::from(c.r)), num(f64::from(c.g)), num(f64::from(c.b)), num(f64::from(c.a)))
}
fn swift_point(p: (f64, f64)) -> String {
format!("UnitPoint(x: {}, y: {})", num(p.0), num(p.1))
}
/// A gradient fill on a layer of `w` x `h` as a SwiftUI gradient.
fn swift_gradient(g: &figcraft_color::Gradient, w: f64, h: f64, opacity: f32) -> String {
let stops = gradient_stops(g, opacity)
.into_iter()
.map(|(at, c)| format!("Gradient.Stop(color: {}, location: {})", swift_color(c), num(at)))
.collect::<Vec<_>>()
.join(", ");
let (dx, dy) = gradient_axis(g, w, h);
match native_gradient_kind(g) {
GradientKind::Linear => format!("LinearGradient(stops: [{stops}], startPoint: {}, endPoint: {})", swift_point(g.from), swift_point(g.to)),
GradientKind::Angular => {
format!("AngularGradient(stops: [{stops}], center: {}, angle: .degrees({}))", swift_point(g.from), num(dy.atan2(dx).to_degrees()))
}
_ => format!("RadialGradient(stops: [{stops}], center: {}, startRadius: 0, endRadius: {})", swift_point(g.from), num(dx.hypot(dy))),
}
}
/// One paint (the one at document index `i`) as SwiftUI; `None` for an image or pattern, which no
/// native target writes yet. Only a solid at index 0 takes the `fill` variable's name.
fn swift_paint(doc: &Document, n: &Node, i: usize, p: &Paint) -> Option<String> {
match &p.kind {
PaintKind::Solid { .. } => {
let c = swift_color(p.solid_color()?);
Some(if i == 0 { named(doc, n, "iOS", &["fill"], c) } else { c })
}
PaintKind::Gradient(g) => Some(swift_gradient(g, n.width, n.height, p.opacity)),
PaintKind::Image(_) | PaintKind::Pattern(_) => None,
}
}
/// The modifiers filling a rectangle or ellipse: the bottom paint fills the `shape`, and each paint
/// above it is a copy of the shape laid over it.
fn swift_shape_fills(doc: &Document, n: &Node, shape: &str) -> Vec<String> {
let paints = visible_fills(n).filter_map(|(i, p)| swift_paint(doc, n, i, p));
paints.enumerate().map(|(at, c)| if at == 0 { format!(".fill({c})") } else { format!(".overlay({shape}.fill({c}))") }).collect()
}
fn swift_weight(w: u16) -> &'static str {
match w {
0..=150 => ".thin",
@@ -84,16 +126,12 @@ fn swift_layer(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, extra: &[Str
}
NodeKind::Ellipse { .. } => {
out.push_str(&format!("{pad}Ellipse()\n"));
if let Some(c) = &fill {
mods.push(format!(".fill({c})"));
}
mods.extend(swift_shape_fills(doc, n, "Ellipse()"));
mods.push(format!(".frame(width: {w}, height: {h})"));
}
NodeKind::Rectangle => {
out.push_str(&format!("{pad}RoundedRectangle(cornerRadius: {corner})\n"));
if let Some(c) = &fill {
mods.push(format!(".fill({c})"));
}
mods.extend(swift_shape_fills(doc, n, &format!("RoundedRectangle(cornerRadius: {corner})")));
mods.push(format!(".frame(width: {w}, height: {h})"));
}
k if k.is_frame_like() || matches!(k, NodeKind::Group) => {
@@ -142,9 +180,8 @@ fn swift_layer(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, extra: &[Str
}
}
mods.push(format!(".frame(width: {w}, height: {h}, alignment: .topLeading)"));
if let Some(c) = &fill {
mods.push(format!(".background({c})"));
}
// Each background goes behind the ones before it, so the top fill is written first.
mods.extend(visible_fills(n).rev().filter_map(|(i, p)| swift_paint(doc, n, i, p)).map(|c| format!(".background({c})")));
if radius(n) > 0.0 {
mods.push(format!(".clipShape(RoundedRectangle(cornerRadius: {corner}))"));
}