Skip to main content

rspack_lightningcss/values/
alpha.rs

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