style: Update calc() serialization to the spec.

This commit is contained in:
Emilio Cobos Álvarez 2017-08-17 21:20:07 +02:00
parent d17f27640b
commit f8a6eccda2
No known key found for this signature in database
GPG key ID: 056B727BB9C1027C
5 changed files with 89 additions and 25 deletions

View file

@ -11,7 +11,7 @@ use values::CSSFloat;
use values::animated::ToAnimatedZero;
/// A computed percentage.
#[derive(Clone, ComputeSquaredDistance, Copy, Debug, Default, HasViewportPercentage, PartialEq)]
#[derive(Clone, ComputeSquaredDistance, Copy, Debug, Default, HasViewportPercentage, PartialEq, PartialOrd)]
#[cfg_attr(feature = "servo", derive(Deserialize, HeapSizeOf, Serialize))]
pub struct Percentage(pub CSSFloat);
@ -27,6 +27,12 @@ impl Percentage {
pub fn hundred() -> Self {
Percentage(1.)
}
/// Returns the absolute value for this percentage.
#[inline]
pub fn abs(&self) -> Self {
Percentage(self.0.abs())
}
}
/// https://drafts.csswg.org/css-transitions/#animtype-percentage

View file

@ -90,16 +90,24 @@ impl HasViewportPercentage for CalcLengthOrPercentage {
}
impl ToCss for CalcLengthOrPercentage {
/// https://drafts.csswg.org/css-values/#calc-serialize
#[allow(unused_assignments)]
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
use num_traits::Zero;
let mut first_value = true;
macro_rules! first_value_check {
() => {
($val:expr) => {
if !first_value {
dest.write_str(" + ")?;
} else {
first_value = false;
dest.write_str(if $val < Zero::zero() {
" - "
} else {
" + "
})?;
} else if $val < Zero::zero() {
dest.write_str("-")?;
}
first_value = false;
};
}
@ -107,8 +115,8 @@ impl ToCss for CalcLengthOrPercentage {
( $( $val:ident ),* ) => {
$(
if let Some(val) = self.$val {
first_value_check!();
val.to_css(dest)?;
first_value_check!(val);
val.abs().to_css(dest)?;
dest.write_str(stringify!($val))?;
}
)*
@ -117,7 +125,9 @@ impl ToCss for CalcLengthOrPercentage {
dest.write_str("calc(")?;
serialize!(ch, em, ex, rem, vh, vmax, vmin, vw);
// NOTE(emilio): The order here it's very intentional, and alphabetic
// per the spec linked above.
serialize!(ch, em, ex);
#[cfg(feature = "gecko")]
{
@ -125,16 +135,20 @@ impl ToCss for CalcLengthOrPercentage {
}
if let Some(val) = self.absolute {
first_value_check!();
val.to_css(dest)?;
first_value_check!(val);
// FIXME(emilio): Au::abs() would be nice.
let abs = if val < Zero::zero() { -val } else { val };
abs.to_css(dest)?;
}
serialize!(rem, vh, vmax, vmin, vw);
if let Some(val) = self.percentage {
first_value_check!();
val.to_css(dest)?;
first_value_check!(val.0);
val.abs().to_css(dest)?;
}
write!(dest, ")")
dest.write_str(")")
}
}