Skip to main content

parcel_css/values/
resolution.rs

1//! CSS resolution values.
2
3use super::length::serialize_dimension;
4use super::number::CSSNumber;
5use crate::compat::Feature;
6use crate::error::{ParserError, PrinterError};
7use crate::printer::Printer;
8use crate::traits::{Parse, ToCss};
9use cssparser::*;
10
11/// A CSS [`<resolution>`](https://www.w3.org/TR/css-values-4/#resolution) value.
12#[derive(Debug, Clone, PartialEq)]
13#[cfg_attr(
14  feature = "serde",
15  derive(serde::Serialize, serde::Deserialize),
16  serde(tag = "type", content = "value", rename_all = "kebab-case")
17)]
18pub enum Resolution {
19  /// A resolution in dots per inch.
20  Dpi(CSSNumber),
21  /// A resolution in dots per centimeter.
22  Dpcm(CSSNumber),
23  /// A resolution in dots per px.
24  Dppx(CSSNumber),
25}
26
27impl<'i> Parse<'i> for Resolution {
28  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
29    // TODO: calc?
30    let location = input.current_source_location();
31    match *input.next()? {
32      Token::Dimension { value, ref unit, .. } => {
33        match_ignore_ascii_case! { unit,
34          "dpi" => Ok(Resolution::Dpi(value)),
35          "dpcm" => Ok(Resolution::Dpcm(value)),
36          "dppx" | "x" => Ok(Resolution::Dppx(value)),
37          _ => Err(location.new_unexpected_token_error(Token::Ident(unit.clone())))
38        }
39      }
40      ref t => Err(location.new_unexpected_token_error(t.clone())),
41    }
42  }
43}
44
45impl ToCss for Resolution {
46  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
47  where
48    W: std::fmt::Write,
49  {
50    let (value, unit) = match self {
51      Resolution::Dpi(dpi) => (*dpi, "dpi"),
52      Resolution::Dpcm(dpcm) => (*dpcm, "dpcm"),
53      Resolution::Dppx(dppx) => {
54        if let Some(targets) = dest.targets {
55          if Feature::XResolutionUnit.is_compatible(targets) {
56            (*dppx, "x")
57          } else {
58            (*dppx, "dppx")
59          }
60        } else {
61          (*dppx, "x")
62        }
63      }
64    };
65
66    serialize_dimension(value, unit, dest)
67  }
68}
69
70impl std::ops::Add<CSSNumber> for Resolution {
71  type Output = Self;
72
73  fn add(self, other: CSSNumber) -> Resolution {
74    match self {
75      Resolution::Dpi(dpi) => Resolution::Dpi(dpi + other),
76      Resolution::Dpcm(dpcm) => Resolution::Dpcm(dpcm + other),
77      Resolution::Dppx(dppx) => Resolution::Dppx(dppx + other),
78    }
79  }
80}