Skip to main content

rspack_lightningcss/properties/
effects.rs

1//! CSS properties related to filters and effects.
2
3use crate::error::{ParserError, PrinterError};
4use crate::macros::enum_property;
5use crate::targets::{Browsers, Targets};
6use crate::traits::{FallbackValues, IsCompatible, Parse, ToCss, Zero};
7use crate::values::color::ColorFallbackKind;
8use crate::values::number::NonNegative;
9use crate::values::{angle::Angle, color::CssColor, length::Length, percentage::NumberOrPercentage, url::Url};
10#[cfg(feature = "visitor")]
11use crate::visitor::Visit;
12use cssparser::*;
13use smallvec::SmallVec;
14
15/// A [filter](https://drafts.fxtf.org/filter-effects-1/#filter-functions) function.
16#[derive(Debug, Clone, PartialEq)]
17#[cfg_attr(feature = "visitor", derive(Visit))]
18#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
19#[cfg_attr(
20  feature = "serde",
21  derive(serde::Serialize, serde::Deserialize),
22  serde(tag = "type", content = "value", rename_all = "kebab-case")
23)]
24#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
25pub enum Filter<'i> {
26  /// A `blur()` filter.
27  Blur(NonNegative<Length>),
28  /// A `brightness()` filter.
29  Brightness(NonNegative<NumberOrPercentage>),
30  /// A `contrast()` filter.
31  Contrast(NonNegative<NumberOrPercentage>),
32  /// A `grayscale()` filter.
33  Grayscale(NonNegative<NumberOrPercentage>),
34  /// A `hue-rotate()` filter.
35  HueRotate(Angle),
36  /// An `invert()` filter.
37  Invert(NonNegative<NumberOrPercentage>),
38  /// An `opacity()` filter.
39  Opacity(NonNegative<NumberOrPercentage>),
40  /// A `saturate()` filter.
41  Saturate(NonNegative<NumberOrPercentage>),
42  /// A `sepia()` filter.
43  Sepia(NonNegative<NumberOrPercentage>),
44  /// A `drop-shadow()` filter.
45  DropShadow(DropShadow),
46  /// A `url()` reference to an SVG filter.
47  #[cfg_attr(feature = "serde", serde(borrow))]
48  Url(Url<'i>),
49}
50
51impl<'i> Parse<'i> for Filter<'i> {
52  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
53    if let Ok(url) = input.try_parse(Url::parse) {
54      return Ok(Filter::Url(url));
55    }
56
57    let location = input.current_source_location();
58    let function = input.expect_function()?;
59    match_ignore_ascii_case! { &function,
60      "blur" => {
61        input.parse_nested_block(|input| {
62          Ok(Filter::Blur(input.try_parse(NonNegative::<Length>::parse).unwrap_or(NonNegative::zero())))
63        })
64      },
65      "brightness" => {
66        input.parse_nested_block(|input| {
67          Ok(Filter::Brightness(input.try_parse(NonNegative::<NumberOrPercentage>::parse).unwrap_or(NonNegative(NumberOrPercentage::Number(1.0)))))
68        })
69      },
70      "contrast" => {
71        input.parse_nested_block(|input| {
72          Ok(Filter::Contrast(input.try_parse(NonNegative::<NumberOrPercentage>::parse).unwrap_or(NonNegative(NumberOrPercentage::Number(1.0)))))
73        })
74      },
75      "grayscale" => {
76        input.parse_nested_block(|input| {
77          Ok(Filter::Grayscale(input.try_parse(NonNegative::<NumberOrPercentage>::parse).unwrap_or(NonNegative(NumberOrPercentage::Number(1.0)))))
78        })
79      },
80      "hue-rotate" => {
81        input.parse_nested_block(|input| {
82          // Spec has an exception for unitless zero angles: https://github.com/w3c/fxtf-drafts/issues/228
83          Ok(Filter::HueRotate(input.try_parse(Angle::parse_with_unitless_zero).unwrap_or(Angle::zero())))
84        })
85      },
86      "invert" => {
87        input.parse_nested_block(|input| {
88          Ok(Filter::Invert(input.try_parse(NonNegative::<NumberOrPercentage>::parse).unwrap_or(NonNegative(NumberOrPercentage::Number(1.0)))))
89        })
90      },
91      "opacity" => {
92        input.parse_nested_block(|input| {
93          Ok(Filter::Opacity(input.try_parse(NonNegative::<NumberOrPercentage>::parse).unwrap_or(NonNegative(NumberOrPercentage::Number(1.0)))))
94        })
95      },
96      "saturate" => {
97        input.parse_nested_block(|input| {
98          Ok(Filter::Saturate(input.try_parse(NonNegative::<NumberOrPercentage>::parse).unwrap_or(NonNegative(NumberOrPercentage::Number(1.0)))))
99        })
100      },
101      "sepia" => {
102        input.parse_nested_block(|input| {
103          Ok(Filter::Sepia(input.try_parse(NonNegative::<NumberOrPercentage>::parse).unwrap_or(NonNegative(NumberOrPercentage::Number(1.0)))))
104        })
105      },
106      "drop-shadow" => {
107        input.parse_nested_block(|input| {
108          Ok(Filter::DropShadow(DropShadow::parse(input)?))
109        })
110      },
111      _ => Err(location.new_unexpected_token_error(
112        cssparser::Token::Ident(function.clone())
113      ))
114    }
115  }
116}
117
118impl<'i> ToCss for Filter<'i> {
119  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
120    match self {
121      Filter::Blur(val) => {
122        dest.write_str("blur(")?;
123        if *val != NonNegative::zero() {
124          val.to_css(dest)?;
125        }
126        dest.write_char(')')?;
127        Ok(())
128      }
129      Filter::Brightness(val) => {
130        dest.write_str("brightness(")?;
131        let v: f32 = (&val.0).into();
132        if v != 1.0 {
133          val.to_css(dest)?;
134        }
135        dest.write_char(')')?;
136        Ok(())
137      }
138      Filter::Contrast(val) => {
139        dest.write_str("contrast(")?;
140        let v: f32 = (&val.0).into();
141        if v != 1.0 {
142          val.to_css(dest)?;
143        }
144        dest.write_char(')')?;
145        Ok(())
146      }
147      Filter::Grayscale(val) => {
148        dest.write_str("grayscale(")?;
149        let v: f32 = (&val.0).into();
150        if v != 1.0 {
151          val.to_css(dest)?;
152        }
153        dest.write_char(')')?;
154        Ok(())
155      }
156      Filter::HueRotate(val) => {
157        dest.write_str("hue-rotate(")?;
158        if !val.is_zero() {
159          val.to_css(dest)?;
160        }
161        dest.write_char(')')?;
162        Ok(())
163      }
164      Filter::Invert(val) => {
165        dest.write_str("invert(")?;
166        let v: f32 = (&val.0).into();
167        if v != 1.0 {
168          val.to_css(dest)?;
169        }
170        dest.write_char(')')?;
171        Ok(())
172      }
173      Filter::Opacity(val) => {
174        dest.write_str("opacity(")?;
175        let v: f32 = (&val.0).into();
176        if v != 1.0 {
177          val.to_css(dest)?;
178        }
179        dest.write_char(')')?;
180        Ok(())
181      }
182      Filter::Saturate(val) => {
183        dest.write_str("saturate(")?;
184        let v: f32 = (&val.0).into();
185        if v != 1.0 {
186          val.to_css(dest)?;
187        }
188        dest.write_char(')')?;
189        Ok(())
190      }
191      Filter::Sepia(val) => {
192        dest.write_str("sepia(")?;
193        let v: f32 = (&val.0).into();
194        if v != 1.0 {
195          val.to_css(dest)?;
196        }
197        dest.write_char(')')?;
198        Ok(())
199      }
200      Filter::DropShadow(val) => {
201        dest.write_str("drop-shadow(")?;
202        val.to_css(dest)?;
203        dest.write_char(')')?;
204        Ok(())
205      }
206      Filter::Url(url) => url.to_css(dest),
207    }
208  }
209}
210
211impl<'i> Filter<'i> {
212  fn get_fallback(&self, kind: ColorFallbackKind) -> Self {
213    match self {
214      Filter::DropShadow(shadow) => Filter::DropShadow(shadow.get_fallback(kind)),
215      _ => self.clone(),
216    }
217  }
218}
219
220impl IsCompatible for Filter<'_> {
221  fn is_compatible(&self, _browsers: Browsers) -> bool {
222    true
223  }
224}
225
226/// A [`drop-shadow()`](https://drafts.fxtf.org/filter-effects-1/#funcdef-filter-drop-shadow) filter function.
227#[derive(Debug, Clone, PartialEq)]
228#[cfg_attr(feature = "visitor", derive(Visit))]
229#[cfg_attr(
230  feature = "serde",
231  derive(serde::Serialize, serde::Deserialize),
232  serde(rename_all = "camelCase")
233)]
234#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
235#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
236pub struct DropShadow {
237  /// The color of the drop shadow.
238  pub color: CssColor,
239  /// The x offset of the drop shadow.
240  pub x_offset: Length,
241  /// The y offset of the drop shadow.
242  pub y_offset: Length,
243  /// The blur radius of the drop shadow.
244  pub blur: NonNegative<Length>,
245}
246
247impl<'i> Parse<'i> for DropShadow {
248  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
249    let mut color = None;
250    let mut lengths = None;
251
252    loop {
253      if lengths.is_none() {
254        let value = input.try_parse::<_, _, ParseError<ParserError<'i>>>(|input| {
255          let horizontal = Length::parse(input)?;
256          let vertical = Length::parse(input)?;
257          let blur = input.try_parse(NonNegative::<Length>::parse).unwrap_or(NonNegative::zero());
258          Ok((horizontal, vertical, blur))
259        });
260
261        if let Ok(value) = value {
262          lengths = Some(value);
263          continue;
264        }
265      }
266
267      if color.is_none() {
268        if let Ok(value) = input.try_parse(CssColor::parse) {
269          color = Some(value);
270          continue;
271        }
272      }
273
274      break;
275    }
276
277    let lengths = lengths.ok_or(input.new_error(BasicParseErrorKind::QualifiedRuleInvalid))?;
278    Ok(DropShadow {
279      color: color.unwrap_or(CssColor::current_color()),
280      x_offset: lengths.0,
281      y_offset: lengths.1,
282      blur: lengths.2,
283    })
284  }
285}
286
287impl ToCss for DropShadow {
288  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
289    self.x_offset.to_css(dest)?;
290    dest.write_char(' ')?;
291    self.y_offset.to_css(dest)?;
292
293    if self.blur != NonNegative::zero() {
294      dest.write_char(' ')?;
295      self.blur.to_css(dest)?;
296    }
297
298    if self.color != CssColor::current_color() {
299      dest.write_char(' ')?;
300      self.color.to_css(dest)?;
301    }
302
303    Ok(())
304  }
305}
306
307impl DropShadow {
308  fn get_fallback(&self, kind: ColorFallbackKind) -> DropShadow {
309    DropShadow {
310      color: self.color.get_fallback(kind),
311      ..self.clone()
312    }
313  }
314}
315
316/// A value for the [filter](https://drafts.fxtf.org/filter-effects-1/#FilterProperty) and
317/// [backdrop-filter](https://drafts.fxtf.org/filter-effects-2/#BackdropFilterProperty) properties.
318#[derive(Debug, Clone, PartialEq)]
319#[cfg_attr(feature = "visitor", derive(Visit))]
320#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
321#[cfg_attr(
322  feature = "serde",
323  derive(serde::Serialize, serde::Deserialize),
324  serde(tag = "type", content = "value", rename_all = "kebab-case")
325)]
326#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
327pub enum FilterList<'i> {
328  /// The `none` keyword.
329  None,
330  /// A list of filter functions.
331  #[cfg_attr(feature = "serde", serde(borrow))]
332  Filters(SmallVec<[Filter<'i>; 1]>),
333}
334
335impl<'i> Parse<'i> for FilterList<'i> {
336  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
337    if input.try_parse(|input| input.expect_ident_matching("none")).is_ok() {
338      return Ok(FilterList::None);
339    }
340
341    let mut filters = SmallVec::new();
342    while let Ok(filter) = input.try_parse(Filter::parse) {
343      filters.push(filter);
344    }
345
346    Ok(FilterList::Filters(filters))
347  }
348}
349
350impl<'i> ToCss for FilterList<'i> {
351  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
352    match self {
353      FilterList::None => {
354        dest.write_str("none")?;
355        Ok(())
356      }
357      FilterList::Filters(filters) => {
358        let mut first = true;
359        for filter in filters {
360          if first {
361            first = false;
362          } else {
363            dest.whitespace()?;
364          }
365          filter.to_css(dest)?;
366        }
367        Ok(())
368      }
369    }
370  }
371}
372
373impl<'i> FallbackValues for FilterList<'i> {
374  fn get_fallbacks(&mut self, targets: Targets) -> Vec<Self> {
375    let mut res = Vec::new();
376    let mut fallbacks = ColorFallbackKind::empty();
377    if let FilterList::Filters(filters) = self {
378      for shadow in filters.iter() {
379        if let Filter::DropShadow(shadow) = &shadow {
380          fallbacks |= shadow.color.get_necessary_fallbacks(targets);
381        }
382      }
383
384      if fallbacks.contains(ColorFallbackKind::RGB) {
385        res.push(FilterList::Filters(
386          filters
387            .iter()
388            .map(|filter| filter.get_fallback(ColorFallbackKind::RGB))
389            .collect(),
390        ));
391      }
392
393      if fallbacks.contains(ColorFallbackKind::P3) {
394        res.push(FilterList::Filters(
395          filters
396            .iter()
397            .map(|filter| filter.get_fallback(ColorFallbackKind::P3))
398            .collect(),
399        ));
400      }
401
402      if fallbacks.contains(ColorFallbackKind::LAB) {
403        for filter in filters.iter_mut() {
404          *filter = filter.get_fallback(ColorFallbackKind::LAB);
405        }
406      }
407    }
408
409    res
410  }
411}
412
413impl IsCompatible for FilterList<'_> {
414  fn is_compatible(&self, _browsers: Browsers) -> bool {
415    true
416  }
417}
418
419enum_property! {
420  /// A [`<blend-mode>`](https://www.w3.org/TR/compositing-1/#ltblendmodegt) value.
421  pub enum BlendMode {
422    /// The default blend mode; the top layer is drawn over the bottom layer.
423    Normal,
424    /// The source and destination are multiplied.
425    Multiply,
426    /// Multiplies the complements of the backdrop and source, then complements the result.
427    Screen,
428    /// Multiplies or screens, depending on the backdrop color.
429    Overlay,
430    /// Selects the darker of the backdrop and source.
431    Darken,
432    /// Selects the lighter of the backdrop and source.
433    Lighten,
434    /// Brightens the backdrop to reflect the source.
435    ColorDodge,
436    /// Darkens the backdrop to reflect the source.
437    ColorBurn,
438    /// Multiplies or screens, depending on the source color.
439    HardLight,
440    /// Darkens or lightens, depending on the source color.
441    SoftLight,
442    /// Subtracts the darker from the lighter.
443    Difference,
444    /// Similar to difference, but with lower contrast.
445    Exclusion,
446    /// The hue of the source with the saturation and luminosity of the backdrop.
447    Hue,
448    /// The saturation of the source with the hue and luminosity of the backdrop.
449    Saturation,
450    /// The hue and saturation of the source with the luminosity of the backdrop.
451    Color,
452    /// The luminosity of the source with the hue and saturation of the backdrop.
453    Luminosity,
454    /// Adds the source to the backdrop, producing a darker result.
455    PlusDarker,
456    /// Adds the source to the backdrop, producing a lighter result.
457    PlusLighter,
458  }
459}