Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge #510: Color parsing: one scale per colour, not per component

aiongg3fedc862f6d9
diff --cc crates/engine/src/cmd/style.rs
index cdfcd14e5,296a8d07b..ef46dbe1b
--- a/crates/engine/src/cmd/style.rs
+++ b/crates/engine/src/cmd/style.rs
@@@ -828,16 -716,18 +828,22 @@@ pub fn parse_color(v: &Value) -> Option
use designcraft_color::Color;
match v {
Value::String(s) => Color::from_hex(s),
+ // One scale per colour, not per component: {c: 0.7, y: 12.2} is C 0.7 %, Y 12.2 %. Only a colour whose
+ // components are all within 0..1 is read as fractions (the older form).
Value::Array(a) if a.len() >= 3 => {
- let f = |i: usize| a[i].as_f64().map(|x| if x > 1.0 { x / 255.0 } else { x } as f32);
- Some(Color::rgb(f(0)?, f(1)?, f(2)?))
+ let v = [a[0].as_f64()?, a[1].as_f64()?, a[2].as_f64()?];
+ let scale = if v.iter().any(|&x| x > 1.0) { 255.0 } else { 1.0 };
+ Some(Color::rgb((v[0] / scale) as f32, (v[1] / scale) as f32, (v[2] / scale) as f32))
}
Value::Object(o) => {
- let g = |k: &str| o.get(k).and_then(Value::as_f64).map(|x| if x > 1.0 { x / 100.0 } else { x } as f32);
+ if o.contains_key("gray") {
- return Some(Color::gray(g("gray")?));
++ let gray = o.get("gray").and_then(Value::as_f64)?;
++ return Some(Color::gray(if gray > 1.0 { gray / 100.0 } else { gray } as f32));
+ }
- Some(Color::cmyk(g("c")?, g("m")?, g("y")?, g("k")?))
+ let g = |k: &str| o.get(k).and_then(Value::as_f64);
+ let v = [g("c")?, g("m")?, g("y")?, g("k")?];
+ let scale = if v.iter().any(|&x| x > 1.0) { 100.0 } else { 1.0 };
+ Some(Color::cmyk((v[0] / scale) as f32, (v[1] / scale) as f32, (v[2] / scale) as f32, (v[3] / scale) as f32))
}
_ => None,
}