lightningcss/values/
alpha.rs

1//! CSS alpha values, used to represent opacity.
2
3use super::percentage::NumberOrPercentage;
4use crate::error::{ParserError, PrinterError};
5use crate::printer::Printer;
6use crate::traits::{Parse, ToCss};
7#[cfg(feature = "visitor")]
8use crate::visitor::Visit;
9use cssparser::*;
10
11/// A CSS [`<alpha-value>`](https://www.w3.org/TR/css-color-4/#typedef-alpha-value),
12/// used to represent opacity.
13///
14/// Parses either a `<number>` or `<percentage>`, but is always stored and serialized as a number.
15#[derive(Debug, Clone, PartialEq)]
16#[cfg_attr(feature = "visitor", derive(Visit))]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(transparent))]
18#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
19#[cfg_attr(feature = "into_owned", derive(static_self::IntoOwned))]
20pub struct AlphaValue(pub f32);
21
22impl<'i> Parse<'i> for AlphaValue {
23  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
24    match NumberOrPercentage::parse(input)? {
25      NumberOrPercentage::Percentage(percent) => Ok(AlphaValue(percent.0)),
26      NumberOrPercentage::Number(number) => Ok(AlphaValue(number)),
27    }
28  }
29}
30
31impl ToCss for AlphaValue {
32  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
33  where
34    W: std::fmt::Write,
35  {
36    self.0.to_css(dest)
37  }
38}