Properly implement weighted inversion

This commit is contained in:
ConnorSkees 2020-02-16 16:53:28 -05:00
parent ca0e2d47cb
commit 948c489785
3 changed files with 14 additions and 12 deletions

View File

@ -150,7 +150,7 @@ pub(crate) fn register(f: &mut BTreeMap<String, Builtin>) {
decl!(f "invert", |args, _| { decl!(f "invert", |args, _| {
max_args!(args, 2); max_args!(args, 2);
let weight = match arg!(args, 1, "weight"=Value::Dimension(Number::from(100), Unit::Percent)) { let weight = match arg!(args, 1, "weight"=Value::Dimension(Number::from(100), Unit::Percent)) {
Value::Dimension(n, _) => n / Number::from(100), Value::Dimension(n, u) => bound!("amount", n, u, 0, 100) / Number::from(100),
v => return Err(format!("$weight: {} is not a number.", v).into()), v => return Err(format!("$weight: {} is not a number.", v).into()),
}; };
match arg!(args, 0, "color") { match arg!(args, 0, "color") {

View File

@ -424,18 +424,15 @@ impl Color {
} }
pub fn invert(&self, weight: Number) -> Self { pub fn invert(&self, weight: Number) -> Self {
let weight = if weight > Number::from(1) { if weight == Number::from(0) {
Number::from(1) return self.clone();
} else if weight < Number::from(0) { }
Number::from(0) let red = Number::from(u8::max_value()) - self.red();
} else { let green = Number::from(u8::max_value()) - self.green();
weight let blue = Number::from(u8::max_value()) - self.blue();
};
let red = Number::from(u8::max_value()) - self.red() * weight.clone();
let green = Number::from(u8::max_value()) - self.green() * weight.clone();
let blue = Number::from(u8::max_value()) - self.blue() * weight;
let repr = repr(&red, &green, &blue, &self.alpha()); let repr = repr(&red, &green, &blue, &self.alpha());
Color::new_rgba(red, green, blue, self.alpha(), repr) let inverse = Color::new_rgba(red, green, blue, self.alpha(), repr);
inverse.mix(self.clone(), weight)
} }
pub fn complement(&self) -> Self { pub fn complement(&self) -> Self {

View File

@ -263,6 +263,11 @@ test!(
"a {\n color: invert(white, 20%);\n}\n", "a {\n color: invert(white, 20%);\n}\n",
"a {\n color: #cccccc;\n}\n" "a {\n color: #cccccc;\n}\n"
); );
test!(
invert_weight_percent_turquoise,
"a {\n color: invert(turquoise, 23%);\n}\n",
"a {\n color: #5db4ab;\n}\n"
);
test!( test!(
invert_weight_no_unit, invert_weight_no_unit,
"a {\n color: invert(white, 20);\n}\n", "a {\n color: invert(white, 20);\n}\n",