Swatches: CSS export writes gradient midpoints and curves as stops

A gradient swatch saved as CSS wrote only its own stops, so CSS put an
off-center midpoint at the center and mixed a Perceptual or hue gradient
in a straight line between its stops. CSS mixes hex colors evenly in sRGB
between two stops (https://www.w3.org/TR/css-color-4/#interpolation-space),
so the export now writes the midpoints and the curve as stops of their
own, each with its color and opacity, also on repeated, reflected and
mirrored conic swatches. A gradient that would need more than
MAX_SPREAD_STOPS stops that way is written with its own stops.
This commit is contained in:
dotCooCoo
2026-11-15 22:40:49 -08:00
parent ed6f22a84c
commit dd669d33fa
3 changed files with 109 additions and 6 deletions
+15 -6
View File
@@ -192,14 +192,23 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
// A mirrored conic turns counterclockwise, and CSS only turns clockwise: its stops
// are written mirrored about the seam instead.
let mirrored = g.gradient.kind == GradientKind::Conic && g.geom.is_some_and(|geom| geom.is_mirrored());
let stop = |s: &crate::GradientStop| {
let at = if mirrored { 1.0 - s.offset } else { s.offset };
format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0)
let stop = |&(t, c, o): &(f32, Color, f32)| {
let at = if mirrored { 1.0 - t } else { t };
format!("{} {}%", css_color(&c, o), at * 100.0)
};
// Stops that repeat or reflect run that many times across the box.
// Stops that repeat or reflect run that many times across the box. CSS mixes
// hex colors evenly in sRGB between two stops
// (https://www.w3.org/TR/css-color-4/#interpolation-space), so an off-center
// midpoint and the curve of a Perceptual or hue gradient are written as stops
// of their own, each with its color and opacity. A gradient that would need
// more than `MAX_SPREAD_STOPS` stops that way is written with its own stops.
let unrolled = g.gradient.unrolled();
let stops: Vec<String> =
if mirrored { unrolled.stops.iter().rev().map(stop).collect() } else { unrolled.stops.iter().map(stop).collect() };
let expanded: Vec<(f32, Color, f32)> = if unrolled.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_none() {
unrolled.expanded_stops()
} else {
unrolled.stops.iter().map(|s| (s.offset, s.color, s.opacity)).collect()
};
let stops: Vec<String> = if mirrored { expanded.iter().rev().map(stop).collect() } else { expanded.iter().map(stop).collect() };
match g.gradient.kind {
GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")),
// CSS sweeps clockwise from straight up; the angle is counted counterclockwise
+93
View File
@@ -284,6 +284,99 @@ fn css_writes_spread_gradient_swatches_with_their_stops_repeated() {
}
}
/// The color and opacity a written CSS gradient value has at `p` (0..1 along its stops), by the
/// CSS rule (https://www.w3.org/TR/css-images-3/#coloring-gradient-line): between two stops the
/// color mixes evenly with premultiplied alpha, in sRGB for hex colors
/// (https://www.w3.org/TR/css-color-4/#interpolation-space); before the first stop and after the
/// last the end colors hold.
fn css_gradient_at(value: &str, p: f64) -> ([f64; 3], f64) {
let list = value.split_once(", ").map_or("", |(_, rest)| rest).trim_end_matches(')');
let stops: Vec<([f64; 3], f64, f64)> = list
.split(", ")
.map(|stop| {
let (hex, at) = stop.split_once(' ').unwrap_or_else(|| panic!("stop {stop:?}"));
let byte = |i: usize| hex.get(1 + 2 * i..3 + 2 * i).map_or(255.0, |h| f64::from(u8::from_str_radix(h, 16).unwrap()));
let at: f64 = at.trim_end_matches('%').parse().unwrap();
([byte(0), byte(1), byte(2)].map(|v| v / 255.0), byte(3) / 255.0, at / 100.0)
})
.collect();
let p = p.clamp(stops[0].2, stops[stops.len() - 1].2);
let i = stops.windows(2).position(|w| p <= w[1].2).unwrap_or(0);
let ((c0, a0, p0), (c1, a1, p1)) = (stops[i], stops[i + 1]);
let w = if p1 > p0 { (p - p0) / (p1 - p0) } else { 1.0 };
let a = a0 + (a1 - a0) * w;
let c = std::array::from_fn(|k| if a > 0.0 { (c0[k] * a0 + (c1[k] * a1 - c0[k] * a0) * w) / a } else { 0.0 });
(c, a)
}
/// A gradient swatch's CSS draws, by the CSS rule, the colors and opacity the swatch has: an
/// off-center midpoint and the curve of a Perceptual or hue gradient are written as stops of their
/// own, also on a reflected and a mirrored conic swatch.
#[test]
fn css_gradient_swatches_draw_their_midpoints_and_curves() {
let check = |label: &str, gp: GradientPaint, at: &dyn Fn(f64) -> f64| {
let lib = SwatchLibrary {
name: "x".into(),
swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(gp.clone())), global: false, spot: false }],
groups: vec![],
};
let text = written(&lib, PaletteFormat::Css);
let value = text.lines().find_map(|l| l.trim().strip_prefix("--x: ")).unwrap_or_else(|| panic!("{text}")).trim_end_matches(';');
for i in 0..64 {
let p = (f64::from(i) + 0.5) / 64.0;
let (css, css_alpha) = css_gradient_at(value, p);
let (color, opacity) = gp.gradient.sample(at(p) as f32);
let want = color.to_rgb();
let off = (0..3).map(|k| (css[k] - f64::from(want[k])).abs()).fold((css_alpha - f64::from(opacity)).abs(), f64::max);
assert!(off < 2.0 / 255.0, "{label} at {p}: {css:?} {css_alpha} vs {want:?} {opacity}: {value}");
}
};
let ramp = |method| Gradient {
method,
..Gradient::new(
GradientKind::Linear,
vec![GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::rgb8(255, 0, 0)) }, GradientStop::new(1.0, Color::rgb8(0, 0, 255))],
)
};
for method in crate::GradientMethod::ALL {
check(&format!("{method:?}"), GradientPaint::new(ramp(method)), &|p| p);
}
// Opacity through an off-center midpoint, on one color so premultiplying does not change it.
let fade = Gradient::new(
GradientKind::Linear,
vec![
GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::BLACK) },
GradientStop { opacity: 0.0, ..GradientStop::new(1.0, Color::BLACK) },
],
);
check("fade", GradientPaint::new(fade), &|p| p);
let reflected = Gradient { spread: crate::GradientSpread::Reflect, repeats: 2, ..ramp(crate::GradientMethod::Classic) };
let spread = reflected.spreader();
check("reflect", GradientPaint::new(reflected), &spread);
let mut conic = GradientPaint::new(Gradient { kind: GradientKind::Conic, ..ramp(crate::GradientMethod::HueClockwise) });
conic.geom = Some(crate::GradientGeom { start: kurbo::Point::ZERO, end: kurbo::Point::new(0.0, -10.0), aspect: -1.0, focal: None });
check("mirrored conic", conic, &|p| 1.0 - p);
}
/// A gradient swatch whose curve would need more than `MAX_SPREAD_STOPS` stops is written with its
/// own stops.
#[test]
fn css_gradient_swatches_keep_their_stop_count_bounded() {
let n = 4000;
let stops = (0..n)
.map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { Color::rgb8(255, 0, 0) } else { Color::rgb8(0, 255, 255) }))
.collect();
let g = Gradient { method: crate::GradientMethod::HueClockwise, ..Gradient::new(GradientKind::Linear, stops) };
assert!(g.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_some(), "the curve needs more stops than allowed");
let lib = SwatchLibrary {
name: "x".into(),
swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(GradientPaint::new(g))), global: false, spot: false }],
groups: vec![],
};
let text = written(&lib, PaletteFormat::Css);
assert_eq!(text.matches('%').count(), n, "one stop for each of the gradient's own");
}
#[test]
fn holds_counts_the_swatches_each_format_writes() {
// `sample()` holds the spot color Ink, the linear gradient Fade, the pattern Tiles and two solid colors in a group.
+1
View File
@@ -1644,6 +1644,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
Double-clicking the Objects on Path tool opens Objects on Path Tool Options ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)): the nine-point Pivot grid and the Rotate field set the attachment point and angle of the objects attached next, and groups already attached keep theirs; Reset puts the center and 0° back. Save keeps the options across tool switches and saves them with the preferences (`tool.setOption {tool: "objectsOnPath"}`).
- **Paint and appearance (M3):**
- **CSS swatch libraries:** fractional linear and radial gradient stop positions are preserved, so nearby stops such as 12.5% and 12.890625% remain distinct instead of collapsing to 13%. Reference: [CSS Images 3 color stops](https://www.w3.org/TR/css-images-3/#color-stop-syntax). The original synthetic regression is `palette_io::tests::css_preserves_fractional_gradient_stop_positions` in `crates/color/src/palette_io.rs`. Scores and hours are unchanged.
- **CSS swatch libraries:** a gradient swatch's off-center midpoints and the curve of a Perceptual, Hue Clockwise or Hue Counterclockwise gradient are written as stops of their own, each with its color and opacity, also on repeated, reflected and mirrored conic swatches, so the CSS value draws the colors the swatch has. CSS mixes hex colors evenly in sRGB between two stops ([CSS Color 4 interpolation space](https://www.w3.org/TR/css-color-4/#interpolation-space), [CSS Images 3 gradient line](https://www.w3.org/TR/css-images-3/#coloring-gradient-line)). Regression: `palette_io::tests::css_gradient_swatches_draw_their_midpoints_and_curves`.
- **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries, seven gradient libraries (among them Organic Fades, soft perceptually mixed multi-stop fades that thin out to transparent, and Holographic, seven opaque linear foils of narrow pastel and pearl bands and seven radial glows that fade out to a clear edge) and three pattern libraries (Geometric Patterns; Grit Textures with eight seamless grain, speckle, stipple, scratch and fleck tiles; and Optical Effects with eight of VectorCraft's own seamless wave, ring, warped-check, stripe, chevron and lens tiles; their swatches bring their patterns) in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate.
Right-clicking a swatch in either list or thumbnail view selects it without applying paint and offers Swatch Options…, Duplicate Swatch and Delete Swatch for that item. None, [Registration] and missing swatches disable these actions. Existing active-item multiselection is retained; actions still target only the clicked item. Evidence: `panels::swatches::tests::context_menu` harness tests cover all five views, selection, dialog dispatch, duplicate/delete and Undo. All 39 Swatches tests pass; the regression fails with the menu hooks removed. Rendered headless list and thumbnail menus were inspected, and a fresh local deep CodeRabbit review reported zero findings. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged.
Validation on 2026-11-15: native Windows formatting, workspace Clippy and all 39 focused Swatches tests passed. Windows full CI stopped at unchanged engine tests `tests::package::a_confined_package_names_files_outside_the_read_root_by_name` (slash-sensitive report assertion) and `tests::plugins::plugin_storage_behind_a_link_is_left_alone` (storage-link setup returned AlreadyExists). Both cases pass in the Linux/WSL full CI run, which passed all 13 gates. No engine or CI workflow changes are included.