Implement builtin functions saturate() and desaturate()

This commit is contained in:
ConnorSkees 2020-02-14 09:05:57 -05:00
parent c7c1ad5fe5
commit be84350d19
3 changed files with 66 additions and 0 deletions

View File

@ -203,4 +203,28 @@ pub(crate) fn register(f: &mut BTreeMap<String, Builtin>) {
};
Some(Value::Color(color.darken(amount)))
});
decl!(f "saturate", |args, _| {
let color = match arg!(args, 0, "color").eval() {
Value::Color(c) => c,
_ => todo!("non-color given to builtin function `saturate()`")
};
let amount = match arg!(args, 1, "amount").eval() {
Value::Dimension(n, Unit::None) => n,
Value::Dimension(n, Unit::Percent) => n / Number::from(100),
_ => todo!("expected either unitless or % number for amount"),
};
Some(Value::Color(color.saturate(amount)))
});
decl!(f "desaturate", |args, _| {
let color = match arg!(args, 0, "color").eval() {
Value::Color(c) => c,
_ => todo!("non-color given to builtin function `desaturate()`")
};
let amount = match arg!(args, 1, "amount").eval() {
Value::Dimension(n, Unit::None) => n,
Value::Dimension(n, Unit::Percent) => n / Number::from(100),
_ => todo!("expected either unitless or % number for amount"),
};
Some(Value::Color(color.desaturate(amount)))
});
}

View File

@ -157,6 +157,16 @@ impl Color {
Color::from_hsla(hue, saturation, luminance - amount, alpha)
}
pub fn saturate(&self, amount: Number) -> Self {
let (hue, saturation, luminance, alpha) = self.as_hsla();
Color::from_hsla(hue, saturation + amount, luminance, alpha)
}
pub fn desaturate(&self, amount: Number) -> Self {
let (hue, saturation, luminance, alpha) = self.as_hsla();
Color::from_hsla(hue, saturation - amount, luminance, alpha)
}
pub fn alpha(&self) -> Number {
self.alpha.clone()
}

View File

@ -252,3 +252,35 @@ test!(
// blocked on recognizing when to use 3-hex over 6-hex
"a {\n color: #220000;\n}\n"
);
// blocked on better parsing of call args
// test!(
// saturate_named_args,
// "a {\n color: saturate($color: hsl(25, 100%, 80%), $amount: 30%);\n}\n",
// "a {\n color: #ff6a00;\n}\n"
// );
test!(
saturate_basic,
"a {\n color: saturate(hsl(120, 30%, 90%), 20%);\n}\n",
"a {\n color: #d9f2d9;\n}\n"
);
test!(
saturate_3_hex,
"a {\n color: saturate(#855, 20%);\n}\n",
"a {\n color: #9e3f3f;\n}\n"
);
// blocked on better parsing of call args
// test!(
// desaturate_named_args,
// "a {\n color: desaturate($color: hsl(25, 100%, 80%), $amount: 30%);\n}\n",
// "a {\n color: #ff6a00;\n}\n"
// );
test!(
desaturate_basic,
"a {\n color: desaturate(hsl(120, 30%, 90%), 20%);\n}\n",
"a {\n color: #e3e8e3;\n}\n"
);
test!(
desaturate_3_hex,
"a {\n color: desaturate(#855, 20%);\n}\n",
"a {\n color: #726b6b;\n}\n"
);