mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-18 08:53:33 +00:00
Merge pull request #7963 from dotCooCoo/feat/recolor-group-storage
Recolor Artwork: a Color Groups list selects, saves, adds and deletes color groups
This commit is contained in:
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Recolor Artwork",
|
||||
["Edit", "Edit Colors"],
|
||||
None,
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null] (what `group` is rewritten with, a null removing the group's swatch at its place; default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what `group` is rewritten with, a null removing the group's swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the swatches it adds nothing; refused for a swatch that is not a colour); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -1680,12 +1680,26 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(Value::Array(cs)) => Some(cs),
|
||||
Some(_) => return Err(bad(C, "`groupColors` must be an array")),
|
||||
};
|
||||
// A null in groupColors removes the group's swatch at its place.
|
||||
// A null in groupColors removes the group's swatch at its place, and "keep" leaves the swatch
|
||||
// at its place its color, without the Global Adjust.
|
||||
let own: Vec<Option<Color>> = match group {
|
||||
Some(g) => {
|
||||
s.doc()?.doc.swatch_groups.iter().find(|x| x.name == g).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default()
|
||||
}
|
||||
None => vec![],
|
||||
};
|
||||
let new: Vec<Option<Color>> = match group_colors {
|
||||
Some(cs) => cs
|
||||
.iter()
|
||||
.map(|v| match v {
|
||||
.enumerate()
|
||||
.map(|(i, v)| match v {
|
||||
Value::Null => Ok(None),
|
||||
// Past the group's swatches it adds nothing.
|
||||
Value::String(k) if k == "keep" => match own.get(i) {
|
||||
Some(Some(c)) => Ok(Some(*c)),
|
||||
Some(None) => Err(bad(C, format!("the swatch at place {i} of groupColors is not a colour to keep"))),
|
||||
None => Ok(None),
|
||||
},
|
||||
v => color_value(v)
|
||||
.map(|c| adjust.apply(c))
|
||||
.map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c)))))
|
||||
|
||||
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Color Group",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; built-in swatches can't change; a color the swatch already has keeps its model), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}",
|
||||
"{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; a null removes the swatch at that place; built-in swatches can't change; a color the swatch already has keeps its model, and a key that names the swatch's color, rounded to the key's steps, keeps the swatch's color unrounded), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}",
|
||||
has_doc,
|
||||
swatch_edit_group
|
||||
),
|
||||
@@ -1340,21 +1340,45 @@ pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option<Colo
|
||||
fn swatch_edit_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.editGroup";
|
||||
let group = str_param(p, "group").ok_or_else(|| bad(C, "missing `group`"))?;
|
||||
let colors: Vec<Color> = p
|
||||
// A null removes the swatch at that place.
|
||||
let colors: Vec<Option<Color>> = p
|
||||
.get("colors")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(|| bad(C, "missing `colors`"))?
|
||||
.iter()
|
||||
.map(|v| color_value(v).ok_or_else(|| bad(C, format!("bad colour {v}"))))
|
||||
.map(|v| if v.is_null() { Ok(None) } else { color_value(v).map(Some).ok_or_else(|| bad(C, format!("bad colour {v}"))) })
|
||||
.collect::<Result<_>>()?;
|
||||
super::paint::check_keep_model(p, C)?;
|
||||
// A color its swatch already has keeps its model. The others take the document's.
|
||||
// A color its swatch already has keeps its model. The others take the document's. A color key
|
||||
// (`recolor.colors`) names a color rounded to its steps, so a key of the swatch's own color
|
||||
// gives the swatch that color, unrounded.
|
||||
let old: Vec<Option<Color>> =
|
||||
s.doc()?.doc.swatch_groups.iter().find(|g| g.name == group).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default();
|
||||
let colors: Vec<Color> =
|
||||
colors.into_iter().enumerate().map(|(i, c)| if old.get(i) == Some(&Some(c)) { c } else { super::paint::new_color(s, p, c) }).collect();
|
||||
let entries = p.get("colors").and_then(Value::as_array);
|
||||
let is_key = |i: usize| entries.and_then(|a| a.get(i)).and_then(Value::as_str).and_then(vectorcraft_color::recolor::ColorKey::parse);
|
||||
let mut colors: Vec<Option<Color>> = colors
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, c)| {
|
||||
c.map(|c| match old.get(i).copied().flatten() {
|
||||
Some(o) if o == c || is_key(i).is_some_and(|k| k == vectorcraft_color::recolor::ColorKey::of(&o)) => o,
|
||||
_ => super::paint::new_color(s, p, c),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
// A null past the group's swatches removes nothing.
|
||||
while colors.len() > old.len() && colors.last() == Some(&None) {
|
||||
colors.pop();
|
||||
}
|
||||
let rename = str_param(p, "rename");
|
||||
let colors: Vec<Option<Color>> = colors.into_iter().map(Some).collect();
|
||||
// The group's own colors, in order, under its own name change nothing: no undo step.
|
||||
if let Some(g) = s.doc()?.doc.swatch_groups.iter().find(|g| g.name == group)
|
||||
&& rename.map(str::trim).is_none_or(|n| n.is_empty() || n == group)
|
||||
&& old.len() == colors.len()
|
||||
&& old.iter().zip(&colors).all(|(o, c)| c.is_some() && o == c)
|
||||
{
|
||||
return Ok(json!({"name": group, "swatches": g.swatches.iter().map(|w| w.name.clone()).collect::<Vec<_>>(), "relinked": 0}));
|
||||
}
|
||||
let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?;
|
||||
e.defaults(s)?;
|
||||
Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked}))
|
||||
|
||||
@@ -489,6 +489,17 @@ fn edit_group_relinks_art_and_apply_rewrites_the_group_with_the_art() {
|
||||
run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["#010203", "cmyk 0 0 0 20"]}));
|
||||
let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone();
|
||||
assert_eq!(g.swatches.iter().map(|w| w.paint.color().unwrap()).collect::<Vec<_>>(), [Color::rgb8(1, 2, 3), Color::cmyk(0.0, 0.0, 0.0, 0.2)]);
|
||||
// "keep" leaves a swatch its color, without the Global Adjust that the other colors take.
|
||||
let adjust = json!({"brightness": -50});
|
||||
run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["keep", "#ffffff"], "globalAdjust": adjust}));
|
||||
let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone();
|
||||
let colors: Vec<Color> = g.swatches.iter().map(|w| w.paint.color().unwrap()).collect();
|
||||
assert_eq!(colors[0], Color::rgb8(1, 2, 3));
|
||||
assert_ne!(colors[1].to_hex(), "#ffffff", "the other color takes the Global Adjust");
|
||||
// Past the group's swatches it adds nothing.
|
||||
run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["keep", "keep", "keep"]}));
|
||||
let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone();
|
||||
assert_eq!(g.swatches.iter().map(|w| w.paint.color().unwrap()).collect::<Vec<_>>(), colors);
|
||||
}
|
||||
|
||||
/// Art linked to a global swatch of the group that `recolor.apply` rewrites stays linked when the
|
||||
|
||||
@@ -423,6 +423,71 @@ fn edit_color_group_numbers_extra_colors_after_the_names_it_keeps() {
|
||||
assert_eq!(*doc(&s), before);
|
||||
}
|
||||
|
||||
/// `swatch.editGroup` with the group's own colors, in order, and its own name (or a blank one)
|
||||
/// records no undo step; a new order, a new color or a new name records one.
|
||||
#[test]
|
||||
fn edit_color_group_with_its_own_colors_records_no_undo_step() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": ["#ff0000", "#00ff00"], "keepModel": true}));
|
||||
let undo = undo_len(&s);
|
||||
for p in [
|
||||
json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"]}),
|
||||
json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"], "rename": "Mine"}),
|
||||
json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"], "rename": " "}),
|
||||
] {
|
||||
let r = run(&mut s, "swatch.editGroup", p.clone());
|
||||
assert_eq!(r, json!({"name": "Mine", "swatches": ["R=255 G=0 B=0", "R=0 G=255 B=0"], "relinked": 0}), "{p}");
|
||||
assert_eq!(undo_len(&s), undo, "{p}: no undo step");
|
||||
}
|
||||
run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#00ff00", "#ff0000"]}));
|
||||
assert_eq!(undo_len(&s), undo + 1, "a new order is a step");
|
||||
run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#00ff00", "#ff0000"], "rename": "Yours"}));
|
||||
assert_eq!(undo_len(&s), undo + 2, "a new name is a step");
|
||||
}
|
||||
|
||||
/// `swatch.editGroup` with the color keys of the group's own colors records no undo step when a
|
||||
/// color lies between the keys' steps, and a rename keeps that color unrounded; a color given as a
|
||||
/// value is taken as it is.
|
||||
#[test]
|
||||
fn edit_color_group_with_its_own_color_keys_keeps_the_colors() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": [{"c": 60.005, "m": 0, "y": 0, "k": 0}, "#00ff00"], "keepModel": true}));
|
||||
let colors = |s: &Session| -> Vec<Color> {
|
||||
doc(s).swatch_groups.iter().find(|g| g.name == "Mine" || g.name == "Yours").unwrap().swatches.iter().filter_map(|w| w.paint.color()).collect()
|
||||
};
|
||||
let own = colors(&s);
|
||||
let keys: Vec<String> = own.iter().map(|c| vectorcraft_color::recolor::ColorKey::of(c).to_string()).collect();
|
||||
assert_ne!(crate::cmd::color_value(&json!(keys[0])), Some(own[0]), "the key rounds the color");
|
||||
let undo = undo_len(&s);
|
||||
run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": keys}));
|
||||
assert_eq!(undo_len(&s), undo, "the group's own colors record no step");
|
||||
run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": keys, "rename": "Yours"}));
|
||||
assert_eq!(undo_len(&s), undo + 1, "a new name is a step");
|
||||
assert_eq!(colors(&s), own, "the colors are kept unrounded");
|
||||
// A color given as a value, not a key, is taken exactly, also within a key's step.
|
||||
let Color::Cmyk { c, .. } = own[0] else { panic!("a CMYK swatch: {:?}", own[0]) };
|
||||
let nudged = Color::cmyk(c - 0.000_002, 0.0, 0.0, 0.0);
|
||||
assert_eq!(vectorcraft_color::recolor::ColorKey::of(&nudged), vectorcraft_color::recolor::ColorKey::of(&own[0]));
|
||||
let p = json!({"group": "Yours", "colors": [{"c": c - 0.000_002, "m": 0, "y": 0, "k": 0}, "#00ff00"], "keepModel": true});
|
||||
run(&mut s, "swatch.editGroup", p);
|
||||
assert_eq!(undo_len(&s), undo + 2, "a new value is a step");
|
||||
assert_eq!(colors(&s)[0], nudged);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_color_group_with_a_null_removes_that_swatch() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": ["#ff0000", "#00ff00", "#0000ff"], "keepModel": true}));
|
||||
let undo = undo_len(&s);
|
||||
let r = run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#ff0000", null, "#0000ff"]}));
|
||||
assert_eq!(r["swatches"], json!(["R=255 G=0 B=0", "R=0 G=0 B=255"]));
|
||||
assert_eq!(names(&s, Some("Mine")), ["R=255 G=0 B=0", "R=0 G=0 B=255"]);
|
||||
assert_eq!(undo_len(&s), undo + 1, "a removed swatch is a step");
|
||||
run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#ff0000", "#0000ff", null]}));
|
||||
assert_eq!(undo_len(&s), undo + 1, "a null past the swatches removes nothing and records no step");
|
||||
assert!(s.execute("swatch.editGroup", &json!({"group": "Mine", "colors": ["#ff0000", "nope"]})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unused_leaves_out_linked_colours_gradients_and_patterns_in_use() {
|
||||
let mut s = session();
|
||||
|
||||
Reference in New Issue
Block a user