Skip to main content

rspack_lightningcss/properties/
masking.rs

1//! CSS properties related to clipping and masking.
2
3use super::background::{BackgroundRepeat, BackgroundSize};
4use super::border_image::{BorderImage, BorderImageRepeat, BorderImageSideWidth, BorderImageSlice};
5use super::PropertyId;
6use crate::context::PropertyHandlerContext;
7use crate::declaration::{DeclarationBlock, DeclarationList};
8use crate::error::{ParserError, PrinterError};
9use crate::macros::{define_list_shorthand, define_shorthand, enum_property, property_bitflags};
10use crate::prefixes::Feature;
11use crate::properties::Property;
12use crate::targets::{Browsers, Targets};
13use crate::traits::{FallbackValues, IsCompatible, Parse, PropertyHandler, Shorthand, ToCss};
14use crate::values::image::ImageFallback;
15use crate::values::length::LengthOrNumber;
16use crate::values::number::NonNegative;
17use crate::values::rect::Rect;
18use crate::values::{image::Image, position::Position, shape::BasicShape, url::Url};
19use crate::vendor_prefix::VendorPrefix;
20#[cfg(feature = "visitor")]
21use crate::visitor::Visit;
22use cssparser::*;
23use itertools::izip;
24use smallvec::SmallVec;
25
26enum_property! {
27  /// A value for the [mask-type](https://www.w3.org/TR/css-masking-1/#the-mask-type) property.
28  pub enum MaskType {
29    /// The luminance values of the mask is used.
30    Luminance,
31    /// The alpha values of the mask is used.
32    Alpha,
33  }
34}
35
36enum_property! {
37  /// A value for the [mask-mode](https://www.w3.org/TR/css-masking-1/#the-mask-mode) property.
38  pub enum MaskMode {
39    /// The luminance values of the mask image is used.
40    Luminance,
41    /// The alpha values of the mask image is used.
42    Alpha,
43    /// If an SVG source is used, the value matches the `mask-type` property. Otherwise, the alpha values are used.
44    MatchSource,
45  }
46}
47
48impl Default for MaskMode {
49  fn default() -> MaskMode {
50    MaskMode::MatchSource
51  }
52}
53
54enum_property! {
55  /// A value for the [-webkit-mask-source-type](https://github.com/WebKit/WebKit/blob/6eece09a1c31e47489811edd003d1e36910e9fd3/Source/WebCore/css/CSSProperties.json#L6578-L6587)
56  /// property.
57  ///
58  /// See also [MaskMode](MaskMode).
59  pub enum WebKitMaskSourceType {
60    /// Equivalent to `match-source` in the standard `mask-mode` syntax.
61    Auto,
62    /// The luminance values of the mask image is used.
63    Luminance,
64    /// The alpha values of the mask image is used.
65    Alpha,
66  }
67}
68
69impl From<MaskMode> for WebKitMaskSourceType {
70  fn from(mode: MaskMode) -> WebKitMaskSourceType {
71    match mode {
72      MaskMode::Luminance => WebKitMaskSourceType::Luminance,
73      MaskMode::Alpha => WebKitMaskSourceType::Alpha,
74      MaskMode::MatchSource => WebKitMaskSourceType::Auto,
75    }
76  }
77}
78
79enum_property! {
80  /// A [`<geometry-box>`](https://www.w3.org/TR/css-masking-1/#typedef-geometry-box) value
81  /// as used in the `mask-clip` and `clip-path` properties.
82  pub enum GeometryBox {
83    /// The painted content is clipped to the content box.
84    BorderBox,
85    /// The painted content is clipped to the padding box.
86    PaddingBox,
87    /// The painted content is clipped to the border box.
88    ContentBox,
89    /// The painted content is clipped to the margin box.
90    MarginBox,
91    /// The painted content is clipped to the object bounding box.
92    FillBox,
93    /// The painted content is clipped to the stroke bounding box.
94    StrokeBox,
95    /// Uses the nearest SVG viewport as reference box.
96    ViewBox,
97  }
98}
99
100impl Default for GeometryBox {
101  fn default() -> GeometryBox {
102    GeometryBox::BorderBox
103  }
104}
105
106/// A value for the [mask-clip](https://www.w3.org/TR/css-masking-1/#the-mask-clip) property.
107#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
108#[cfg_attr(feature = "visitor", derive(Visit))]
109#[cfg_attr(
110  feature = "serde",
111  derive(serde::Serialize, serde::Deserialize),
112  serde(tag = "type", content = "value", rename_all = "kebab-case")
113)]
114#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
115#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
116pub enum MaskClip {
117  /// A geometry box.
118  GeometryBox(GeometryBox),
119  /// The painted content is not clipped.
120  NoClip,
121}
122
123impl IsCompatible for MaskClip {
124  fn is_compatible(&self, browsers: Browsers) -> bool {
125    match self {
126      MaskClip::GeometryBox(g) => g.is_compatible(browsers),
127      MaskClip::NoClip => true,
128    }
129  }
130}
131
132impl Into<MaskClip> for GeometryBox {
133  fn into(self) -> MaskClip {
134    MaskClip::GeometryBox(self.clone())
135  }
136}
137
138impl IsCompatible for GeometryBox {
139  fn is_compatible(&self, _browsers: Browsers) -> bool {
140    true
141  }
142}
143
144enum_property! {
145  /// A value for the [mask-composite](https://www.w3.org/TR/css-masking-1/#the-mask-composite) property.
146  pub enum MaskComposite {
147    /// The source is placed over the destination.
148    Add,
149    /// The source is placed, where it falls outside of the destination.
150    Subtract,
151    /// The parts of source that overlap the destination, replace the destination.
152    Intersect,
153    /// The non-overlapping regions of source and destination are combined.
154    Exclude,
155  }
156}
157
158impl Default for MaskComposite {
159  fn default() -> MaskComposite {
160    MaskComposite::Add
161  }
162}
163
164enum_property! {
165  /// A value for the [-webkit-mask-composite](https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-mask-composite)
166  /// property.
167  ///
168  /// See also [MaskComposite](MaskComposite).
169  #[allow(missing_docs)]
170  pub enum WebKitMaskComposite {
171    Clear,
172    Copy,
173    /// Equivalent to `add` in the standard `mask-composite` syntax.
174    SourceOver,
175    /// Equivalent to `intersect` in the standard `mask-composite` syntax.
176    SourceIn,
177    /// Equivalent to `subtract` in the standard `mask-composite` syntax.
178    SourceOut,
179    SourceAtop,
180    DestinationOver,
181    DestinationIn,
182    DestinationOut,
183    DestinationAtop,
184    /// Equivalent to `exclude` in the standard `mask-composite` syntax.
185    Xor,
186  }
187}
188
189impl From<MaskComposite> for WebKitMaskComposite {
190  fn from(composite: MaskComposite) -> WebKitMaskComposite {
191    match composite {
192      MaskComposite::Add => WebKitMaskComposite::SourceOver,
193      MaskComposite::Subtract => WebKitMaskComposite::SourceOut,
194      MaskComposite::Intersect => WebKitMaskComposite::SourceIn,
195      MaskComposite::Exclude => WebKitMaskComposite::Xor,
196    }
197  }
198}
199
200define_list_shorthand! {
201  /// A value for the [mask](https://www.w3.org/TR/css-masking-1/#the-mask) shorthand property.
202  pub struct Mask<'i>(VendorPrefix) {
203    /// The mask image.
204    #[cfg_attr(feature = "serde", serde(borrow))]
205    image: MaskImage(Image<'i>, VendorPrefix),
206    /// The position of the mask.
207    position: MaskPosition(Position, VendorPrefix),
208    /// The size of the mask image.
209    size: MaskSize(BackgroundSize, VendorPrefix),
210    /// How the mask repeats.
211    repeat: MaskRepeat(BackgroundRepeat, VendorPrefix),
212    /// The box in which the mask is clipped.
213    clip: MaskClip(MaskClip, VendorPrefix),
214    /// The origin of the mask.
215    origin: MaskOrigin(GeometryBox, VendorPrefix),
216    /// How the mask is composited with the element.
217    composite: MaskComposite(MaskComposite),
218    /// How the mask image is interpreted.
219    mode: MaskMode(MaskMode),
220  }
221}
222
223impl<'i> Parse<'i> for Mask<'i> {
224  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
225    let mut image: Option<Image> = None;
226    let mut position: Option<Position> = None;
227    let mut size: Option<BackgroundSize> = None;
228    let mut repeat: Option<BackgroundRepeat> = None;
229    let mut clip: Option<MaskClip> = None;
230    let mut origin: Option<GeometryBox> = None;
231    let mut composite: Option<MaskComposite> = None;
232    let mut mode: Option<MaskMode> = None;
233
234    loop {
235      if image.is_none() {
236        if let Ok(value) = input.try_parse(Image::parse) {
237          image = Some(value);
238          continue;
239        }
240      }
241
242      if position.is_none() {
243        if let Ok(value) = input.try_parse(Position::parse) {
244          position = Some(value);
245          size = input
246            .try_parse(|input| {
247              input.expect_delim('/')?;
248              BackgroundSize::parse(input)
249            })
250            .ok();
251          continue;
252        }
253      }
254
255      if repeat.is_none() {
256        if let Ok(value) = input.try_parse(BackgroundRepeat::parse) {
257          repeat = Some(value);
258          continue;
259        }
260      }
261
262      if origin.is_none() {
263        if let Ok(value) = input.try_parse(GeometryBox::parse) {
264          origin = Some(value);
265          continue;
266        }
267      }
268
269      if clip.is_none() {
270        if let Ok(value) = input.try_parse(MaskClip::parse) {
271          clip = Some(value);
272          continue;
273        }
274      }
275
276      if composite.is_none() {
277        if let Ok(value) = input.try_parse(MaskComposite::parse) {
278          composite = Some(value);
279          continue;
280        }
281      }
282
283      if mode.is_none() {
284        if let Ok(value) = input.try_parse(MaskMode::parse) {
285          mode = Some(value);
286          continue;
287        }
288      }
289
290      break;
291    }
292
293    if clip.is_none() {
294      if let Some(origin) = origin {
295        clip = Some(origin.into());
296      }
297    }
298
299    Ok(Mask {
300      image: image.unwrap_or_default(),
301      position: position.unwrap_or_default(),
302      repeat: repeat.unwrap_or_default(),
303      size: size.unwrap_or_default(),
304      origin: origin.unwrap_or(GeometryBox::BorderBox),
305      clip: clip.unwrap_or(GeometryBox::BorderBox.into()),
306      composite: composite.unwrap_or(MaskComposite::Add),
307      mode: mode.unwrap_or(MaskMode::MatchSource),
308    })
309  }
310}
311
312impl<'i> ToCss for Mask<'i> {
313  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
314    self.image.to_css(dest)?;
315
316    if self.position != Position::default() || self.size != BackgroundSize::default() {
317      dest.write_char(' ')?;
318      self.position.to_css(dest)?;
319
320      if self.size != BackgroundSize::default() {
321        dest.delim('/', true)?;
322        self.size.to_css(dest)?;
323      }
324    }
325
326    if self.repeat != BackgroundRepeat::default() {
327      dest.write_char(' ')?;
328      self.repeat.to_css(dest)?;
329    }
330
331    if self.origin != GeometryBox::BorderBox || self.clip != GeometryBox::BorderBox.into() {
332      dest.write_char(' ')?;
333      self.origin.to_css(dest)?;
334
335      if self.clip != self.origin.into() {
336        dest.write_char(' ')?;
337        self.clip.to_css(dest)?;
338      }
339    }
340
341    if self.composite != MaskComposite::default() {
342      dest.write_char(' ')?;
343      self.composite.to_css(dest)?;
344    }
345
346    if self.mode != MaskMode::default() {
347      dest.write_char(' ')?;
348      self.mode.to_css(dest)?;
349    }
350
351    Ok(())
352  }
353}
354
355// TODO: shorthand handler?
356impl<'i> ImageFallback<'i> for Mask<'i> {
357  #[inline]
358  fn get_image(&self) -> &Image<'i> {
359    &self.image
360  }
361
362  #[inline]
363  fn with_image(&self, image: Image<'i>) -> Self {
364    Mask { image, ..self.clone() }
365  }
366}
367
368/// A value for the [clip-path](https://www.w3.org/TR/css-masking-1/#the-clip-path) property.
369#[derive(Debug, Clone, PartialEq)]
370#[cfg_attr(feature = "visitor", derive(Visit))]
371#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
372#[cfg_attr(
373  feature = "serde",
374  derive(serde::Serialize, serde::Deserialize),
375  serde(tag = "type", rename_all = "kebab-case")
376)]
377#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
378pub enum ClipPath<'i> {
379  /// No clip path.
380  None,
381  /// A url reference to an SVG path element.
382  #[cfg_attr(feature = "serde", serde(borrow, with = "crate::serialization::ValueWrapper::<Url>"))]
383  Url(Url<'i>),
384  /// A basic shape, positioned according to the reference box.
385  #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
386  Shape {
387    /// A basic shape.
388    shape: Box<BasicShape>,
389    /// A reference box that the shape is positioned according to.
390    reference_box: GeometryBox,
391  },
392  /// A reference box.
393  #[cfg_attr(feature = "serde", serde(with = "crate::serialization::ValueWrapper::<GeometryBox>"))]
394  Box(GeometryBox),
395}
396
397impl<'i> Parse<'i> for ClipPath<'i> {
398  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
399    if let Ok(url) = input.try_parse(Url::parse) {
400      return Ok(ClipPath::Url(url));
401    }
402
403    if let Ok(shape) = input.try_parse(BasicShape::parse) {
404      let b = input.try_parse(GeometryBox::parse).unwrap_or_default();
405      return Ok(ClipPath::Shape {
406        shape: Box::new(shape),
407        reference_box: b,
408      });
409    }
410
411    if let Ok(b) = input.try_parse(GeometryBox::parse) {
412      if let Ok(shape) = input.try_parse(BasicShape::parse) {
413        return Ok(ClipPath::Shape {
414          shape: Box::new(shape),
415          reference_box: b,
416        });
417      }
418      return Ok(ClipPath::Box(b));
419    }
420
421    input.expect_ident_matching("none")?;
422    Ok(ClipPath::None)
423  }
424}
425
426impl<'i> ToCss for ClipPath<'i> {
427  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
428    match self {
429      ClipPath::None => {
430        dest.write_str("none")?;
431        Ok(())
432      }
433      ClipPath::Url(url) => url.to_css(dest),
434      ClipPath::Shape {
435        shape,
436        reference_box: b,
437      } => {
438        shape.to_css(dest)?;
439        if *b != GeometryBox::default() {
440          dest.write_char(' ')?;
441          b.to_css(dest)?;
442        }
443        Ok(())
444      }
445      ClipPath::Box(b) => b.to_css(dest),
446    }
447  }
448}
449
450enum_property! {
451  /// A value for the [mask-border-mode](https://www.w3.org/TR/css-masking-1/#the-mask-border-mode) property.
452  pub enum MaskBorderMode {
453    /// The luminance values of the mask image is used.
454    Luminance,
455    /// The alpha values of the mask image is used.
456    Alpha,
457  }
458}
459
460impl Default for MaskBorderMode {
461  fn default() -> MaskBorderMode {
462    MaskBorderMode::Alpha
463  }
464}
465
466define_shorthand! {
467  /// A value for the [mask-border](https://www.w3.org/TR/css-masking-1/#the-mask-border) shorthand property.
468  #[derive(Default)]
469  pub struct MaskBorder<'i> {
470    /// The mask image.
471    #[cfg_attr(feature = "serde", serde(borrow))]
472    source: MaskBorderSource(Image<'i>),
473    /// The offsets that define where the image is sliced.
474    slice: MaskBorderSlice(BorderImageSlice),
475    /// The width of the mask image.
476    width: MaskBorderWidth(Rect<BorderImageSideWidth>),
477    /// The amount that the image extends beyond the border box.
478    outset: MaskBorderOutset(Rect<NonNegative<LengthOrNumber>>),
479    /// How the mask image is scaled and tiled.
480    repeat: MaskBorderRepeat(BorderImageRepeat),
481    /// How the mask image is interpreted.
482    mode: MaskBorderMode(MaskBorderMode),
483  }
484}
485
486impl<'i> Parse<'i> for MaskBorder<'i> {
487  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
488    let mut mode: Option<MaskBorderMode> = None;
489    let border_image = BorderImage::parse_with_callback(input, |input| {
490      if mode.is_none() {
491        if let Ok(value) = input.try_parse(MaskBorderMode::parse) {
492          mode = Some(value);
493          return true;
494        }
495      }
496      false
497    });
498
499    if border_image.is_ok() || mode.is_some() {
500      let border_image = border_image.unwrap_or_default();
501      Ok(MaskBorder {
502        source: border_image.source,
503        slice: border_image.slice,
504        width: border_image.width,
505        outset: border_image.outset,
506        repeat: border_image.repeat,
507        mode: mode.unwrap_or_default(),
508      })
509    } else {
510      Err(input.new_custom_error(ParserError::InvalidDeclaration))
511    }
512  }
513}
514
515impl<'i> ToCss for MaskBorder<'i> {
516  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
517    BorderImage::to_css_internal(&self.source, &self.slice, &self.width, &self.outset, &self.repeat, dest)?;
518    if self.mode != MaskBorderMode::default() {
519      dest.write_char(' ')?;
520      self.mode.to_css(dest)?;
521    }
522    Ok(())
523  }
524}
525
526impl<'i> FallbackValues for MaskBorder<'i> {
527  fn get_fallbacks(&mut self, targets: Targets) -> Vec<Self> {
528    self
529      .source
530      .get_fallbacks(targets)
531      .into_iter()
532      .map(|source| MaskBorder { source, ..self.clone() })
533      .collect()
534  }
535}
536
537impl<'i> Into<BorderImage<'i>> for MaskBorder<'i> {
538  fn into(self) -> BorderImage<'i> {
539    BorderImage {
540      source: self.source,
541      slice: self.slice,
542      width: self.width,
543      outset: self.outset,
544      repeat: self.repeat,
545    }
546  }
547}
548
549property_bitflags! {
550  #[derive(Default, Debug)]
551  struct MaskProperty: u16 {
552    const MaskImage(_vp) = 1 << 0;
553    const MaskPosition(_vp) = 1 << 1;
554    const MaskSize(_vp) = 1 << 2;
555    const MaskRepeat(_vp) = 1 << 3;
556    const MaskClip(_vp) = 1 << 4;
557    const MaskOrigin(_vp) = 1 << 5;
558    const MaskComposite = 1 << 6;
559    const MaskMode = 1 << 7;
560    const Mask(_vp) = Self::MaskImage.bits() | Self::MaskPosition.bits() | Self::MaskSize.bits() | Self::MaskRepeat.bits() | Self::MaskClip.bits() | Self::MaskOrigin.bits() | Self::MaskComposite.bits() | Self::MaskMode.bits();
561
562    const MaskBorderSource = 1 << 7;
563    const MaskBorderMode = 1 << 8;
564    const MaskBorderSlice = 1 << 9;
565    const MaskBorderWidth = 1 << 10;
566    const MaskBorderOutset = 1 << 11;
567    const MaskBorderRepeat = 1 << 12;
568    const MaskBorder = Self::MaskBorderSource.bits() | Self::MaskBorderMode.bits() | Self::MaskBorderSlice.bits() | Self::MaskBorderWidth.bits() | Self::MaskBorderOutset.bits() | Self::MaskBorderRepeat.bits();
569  }
570}
571
572#[derive(Default)]
573pub(crate) struct MaskHandler<'i> {
574  images: Option<(SmallVec<[Image<'i>; 1]>, VendorPrefix)>,
575  positions: Option<(SmallVec<[Position; 1]>, VendorPrefix)>,
576  sizes: Option<(SmallVec<[BackgroundSize; 1]>, VendorPrefix)>,
577  repeats: Option<(SmallVec<[BackgroundRepeat; 1]>, VendorPrefix)>,
578  clips: Option<(SmallVec<[MaskClip; 1]>, VendorPrefix)>,
579  origins: Option<(SmallVec<[GeometryBox; 1]>, VendorPrefix)>,
580  composites: Option<SmallVec<[MaskComposite; 1]>>,
581  modes: Option<SmallVec<[MaskMode; 1]>>,
582  border_source: Option<(Image<'i>, VendorPrefix)>,
583  border_mode: Option<MaskBorderMode>,
584  border_slice: Option<(BorderImageSlice, VendorPrefix)>,
585  border_width: Option<(Rect<BorderImageSideWidth>, VendorPrefix)>,
586  border_outset: Option<(Rect<NonNegative<LengthOrNumber>>, VendorPrefix)>,
587  border_repeat: Option<(BorderImageRepeat, VendorPrefix)>,
588  flushed_properties: MaskProperty,
589  has_any: bool,
590}
591
592impl<'i> PropertyHandler<'i> for MaskHandler<'i> {
593  fn handle_property(
594    &mut self,
595    property: &Property<'i>,
596    dest: &mut DeclarationList<'i>,
597    context: &mut PropertyHandlerContext<'i, '_>,
598  ) -> bool {
599    macro_rules! maybe_flush {
600      ($prop: ident, $val: expr, $vp: expr) => {{
601        // If two vendor prefixes for the same property have different
602        // values, we need to flush what we have immediately to preserve order.
603        if let Some((val, prefixes)) = &self.$prop {
604          if val != $val && !prefixes.contains(*$vp) {
605            self.flush(dest, context);
606          }
607        }
608
609        if self.$prop.is_some() && matches!(context.targets.browsers, Some(targets) if !$val.is_compatible(targets)) {
610          self.flush(dest, context);
611        }
612      }};
613    }
614
615    macro_rules! property {
616      ($prop: ident, $val: expr, $vp: expr) => {{
617        maybe_flush!($prop, $val, $vp);
618
619        // Otherwise, update the value and add the prefix.
620        if let Some((val, prefixes)) = &mut self.$prop {
621          *val = $val.clone();
622          *prefixes |= *$vp;
623        } else {
624          self.$prop = Some(($val.clone(), *$vp));
625          self.has_any = true;
626        }
627      }};
628    }
629
630    macro_rules! border_shorthand {
631      ($val: expr, $vp: expr) => {
632        let source = $val.source.clone();
633        maybe_flush!(border_source, &source, &$vp);
634
635        let slice = $val.slice.clone();
636        maybe_flush!(border_slice, &slice, &$vp);
637
638        let width = $val.width.clone();
639        maybe_flush!(border_width, &width, &$vp);
640
641        let outset = $val.outset.clone();
642        maybe_flush!(border_outset, &outset, &$vp);
643
644        let repeat = $val.repeat.clone();
645        maybe_flush!(border_repeat, &repeat, &$vp);
646
647        property!(border_source, &source, &$vp);
648        property!(border_slice, &slice, &$vp);
649        property!(border_width, &width, &$vp);
650        property!(border_outset, &outset, &$vp);
651        property!(border_repeat, &repeat, &$vp);
652      };
653    }
654
655    match property {
656      Property::MaskImage(val, vp) => property!(images, val, vp),
657      Property::MaskPosition(val, vp) => property!(positions, val, vp),
658      Property::MaskSize(val, vp) => property!(sizes, val, vp),
659      Property::MaskRepeat(val, vp) => property!(repeats, val, vp),
660      Property::MaskClip(val, vp) => property!(clips, val, vp),
661      Property::MaskOrigin(val, vp) => property!(origins, val, vp),
662      Property::MaskComposite(val) => self.composites = Some(val.clone()),
663      Property::MaskMode(val) => self.modes = Some(val.clone()),
664      Property::Mask(val, prefix) => {
665        let images = val.iter().map(|b| b.image.clone()).collect();
666        maybe_flush!(images, &images, prefix);
667
668        let positions = val.iter().map(|b| b.position.clone()).collect();
669        maybe_flush!(positions, &positions, prefix);
670
671        let sizes = val.iter().map(|b| b.size.clone()).collect();
672        maybe_flush!(sizes, &sizes, prefix);
673
674        let repeats = val.iter().map(|b| b.repeat.clone()).collect();
675        maybe_flush!(repeats, &repeats, prefix);
676
677        let clips = val.iter().map(|b| b.clip.clone()).collect();
678        maybe_flush!(clips, &clips, prefix);
679
680        let origins = val.iter().map(|b| b.origin.clone()).collect();
681        maybe_flush!(origins, &origins, prefix);
682
683        self.composites = Some(val.iter().map(|b| b.composite.clone()).collect());
684        self.modes = Some(val.iter().map(|b| b.mode.clone()).collect());
685
686        property!(images, &images, prefix);
687        property!(positions, &positions, prefix);
688        property!(sizes, &sizes, prefix);
689        property!(repeats, &repeats, prefix);
690        property!(clips, &clips, prefix);
691        property!(origins, &origins, prefix);
692      }
693      Property::Unparsed(val) if is_mask_property(&val.property_id) => {
694        self.flush(dest, context);
695        let mut unparsed = val.get_prefixed(context.targets, Feature::Mask);
696        context.add_unparsed_fallbacks(&mut unparsed);
697        self
698          .flushed_properties
699          .insert(MaskProperty::try_from(&val.property_id).unwrap());
700        let mut merged = false;
701        if let (PropertyId::MaskImage(prefix), Some(Property::Unparsed(previous))) =
702          (&unparsed.property_id, dest.last_mut())
703        {
704          if let PropertyId::MaskImage(previous_prefix) = &mut previous.property_id {
705            if previous.value == unparsed.value {
706              *previous_prefix |= *prefix;
707              merged = true;
708            }
709          }
710        }
711        if !merged {
712          dest.push(Property::Unparsed(unparsed));
713        }
714      }
715      Property::MaskBorderSource(val) => property!(border_source, val, &VendorPrefix::None),
716      Property::WebKitMaskBoxImageSource(val, _) => property!(border_source, val, &VendorPrefix::WebKit),
717      Property::MaskBorderMode(val) => self.border_mode = Some(val.clone()),
718      Property::MaskBorderSlice(val) => property!(border_slice, val, &VendorPrefix::None),
719      Property::WebKitMaskBoxImageSlice(val, _) => property!(border_slice, val, &VendorPrefix::WebKit),
720      Property::MaskBorderWidth(val) => property!(border_width, val, &VendorPrefix::None),
721      Property::WebKitMaskBoxImageWidth(val, _) => property!(border_width, val, &VendorPrefix::WebKit),
722      Property::MaskBorderOutset(val) => property!(border_outset, val, &VendorPrefix::None),
723      Property::WebKitMaskBoxImageOutset(val, _) => property!(border_outset, val, &VendorPrefix::WebKit),
724      Property::MaskBorderRepeat(val) => property!(border_repeat, val, &VendorPrefix::None),
725      Property::WebKitMaskBoxImageRepeat(val, _) => property!(border_repeat, val, &VendorPrefix::WebKit),
726      Property::MaskBorder(val) => {
727        border_shorthand!(val, VendorPrefix::None);
728        self.border_mode = Some(val.mode.clone());
729      }
730      Property::WebKitMaskBoxImage(val, _) => {
731        border_shorthand!(val, VendorPrefix::WebKit);
732      }
733      Property::Unparsed(val) if is_mask_border_property(&val.property_id) => {
734        self.flush(dest, context);
735        // Add vendor prefixes and expand color fallbacks.
736        let mut val = val.clone();
737        let prefix = context
738          .targets
739          .prefixes(val.property_id.prefix().or_none(), Feature::MaskBorder);
740        if prefix.contains(VendorPrefix::WebKit) {
741          if let Some(property_id) = get_webkit_mask_property(&val.property_id) {
742            let mut clone = val.clone();
743            clone.property_id = property_id;
744            context.add_unparsed_fallbacks(&mut clone);
745            dest.push(Property::Unparsed(clone));
746          }
747        }
748
749        context.add_unparsed_fallbacks(&mut val);
750        self
751          .flushed_properties
752          .insert(MaskProperty::try_from(&val.property_id).unwrap());
753        dest.push(Property::Unparsed(val));
754      }
755      _ => return false,
756    }
757
758    self.has_any = true;
759    true
760  }
761
762  fn finalize(&mut self, dest: &mut DeclarationList<'i>, context: &mut PropertyHandlerContext<'i, '_>) {
763    self.flush(dest, context);
764    self.flushed_properties = MaskProperty::empty();
765  }
766}
767
768impl<'i> MaskHandler<'i> {
769  fn flush(&mut self, dest: &mut DeclarationList<'i>, context: &mut PropertyHandlerContext<'i, '_>) {
770    if !self.has_any {
771      return;
772    }
773
774    self.has_any = false;
775
776    self.flush_mask(dest, context);
777    self.flush_mask_border(dest, context);
778  }
779
780  fn flush_mask(&mut self, dest: &mut DeclarationList<'i>, context: &mut PropertyHandlerContext<'i, '_>) {
781    let mut images = std::mem::take(&mut self.images);
782    let mut positions = std::mem::take(&mut self.positions);
783    let mut sizes = std::mem::take(&mut self.sizes);
784    let mut repeats = std::mem::take(&mut self.repeats);
785    let mut clips = std::mem::take(&mut self.clips);
786    let mut origins = std::mem::take(&mut self.origins);
787    let mut composites = std::mem::take(&mut self.composites);
788    let mut modes = std::mem::take(&mut self.modes);
789
790    if let (
791      Some((images, images_vp)),
792      Some((positions, positions_vp)),
793      Some((sizes, sizes_vp)),
794      Some((repeats, repeats_vp)),
795      Some((clips, clips_vp)),
796      Some((origins, origins_vp)),
797      Some(composites_val),
798      Some(mode_vals),
799    ) = (
800      &mut images,
801      &mut positions,
802      &mut sizes,
803      &mut repeats,
804      &mut clips,
805      &mut origins,
806      &mut composites,
807      &mut modes,
808    ) {
809      // Only use shorthand syntax if the number of masks matches on all properties.
810      let len = images.len();
811      let intersection = *images_vp & *positions_vp & *sizes_vp & *repeats_vp & *clips_vp & *origins_vp;
812      if !intersection.is_empty()
813        && positions.len() == len
814        && sizes.len() == len
815        && repeats.len() == len
816        && clips.len() == len
817        && origins.len() == len
818        && composites_val.len() == len
819        && mode_vals.len() == len
820      {
821        let mut masks: SmallVec<[Mask<'i>; 1]> = izip!(
822          images.drain(..),
823          positions.drain(..),
824          sizes.drain(..),
825          repeats.drain(..),
826          clips.drain(..),
827          origins.drain(..),
828          composites_val.drain(..),
829          mode_vals.drain(..)
830        )
831        .map(|(image, position, size, repeat, clip, origin, composite, mode)| Mask {
832          image,
833          position,
834          size,
835          repeat,
836          clip,
837          origin,
838          composite,
839          mode,
840        })
841        .collect();
842
843        let mut prefix = context.targets.prefixes(intersection, Feature::Mask);
844        if !self.flushed_properties.intersects(MaskProperty::Mask) {
845          for fallback in masks.get_fallbacks(context.targets) {
846            // Match prefix of fallback. e.g. -webkit-linear-gradient
847            // can only be used in -webkit-mask-image.
848            // However, if mask-image is unprefixed, gradients can still be.
849            let mut p = fallback
850              .iter()
851              .fold(VendorPrefix::empty(), |p, mask| p | mask.image.get_vendor_prefix())
852              - VendorPrefix::None
853              & prefix;
854            if p.is_empty() {
855              p = prefix;
856            }
857            self.flush_mask_shorthand(fallback, p, dest);
858          }
859
860          let p = masks
861            .iter()
862            .fold(VendorPrefix::empty(), |p, mask| p | mask.image.get_vendor_prefix())
863            - VendorPrefix::None
864            & prefix;
865          if !p.is_empty() {
866            prefix = p;
867          }
868        }
869
870        self.flush_mask_shorthand(masks, prefix, dest);
871        self.flushed_properties.insert(MaskProperty::Mask);
872
873        images_vp.remove(intersection);
874        positions_vp.remove(intersection);
875        sizes_vp.remove(intersection);
876        repeats_vp.remove(intersection);
877        clips_vp.remove(intersection);
878        origins_vp.remove(intersection);
879        composites = None;
880        modes = None;
881      }
882    }
883
884    macro_rules! prop {
885      ($var: ident, $property: ident) => {
886        if let Some((val, vp)) = $var {
887          if !vp.is_empty() {
888            let prefix = context.targets.prefixes(vp, Feature::$property);
889            dest.push(Property::$property(val, prefix));
890            self.flushed_properties.insert(MaskProperty::$property);
891          }
892        }
893      };
894    }
895
896    if let Some((mut images, vp)) = images {
897      if !vp.is_empty() {
898        let mut prefix = vp;
899        if !self.flushed_properties.contains(MaskProperty::MaskImage) {
900          prefix = context.targets.prefixes(prefix, Feature::MaskImage);
901          for fallback in images.get_fallbacks(context.targets) {
902            // Match prefix of fallback. e.g. -webkit-linear-gradient
903            // can only be used in -webkit-mask-image.
904            // However, if mask-image is unprefixed, gradients can still be.
905            let mut p = fallback
906              .iter()
907              .fold(VendorPrefix::empty(), |p, image| p | image.get_vendor_prefix())
908              - VendorPrefix::None
909              & prefix;
910            if p.is_empty() {
911              p = prefix;
912            }
913            dest.push(Property::MaskImage(fallback, p))
914          }
915
916          let p = images
917            .iter()
918            .fold(VendorPrefix::empty(), |p, image| p | image.get_vendor_prefix())
919            - VendorPrefix::None
920            & prefix;
921          if !p.is_empty() {
922            prefix = p;
923          }
924        }
925
926        dest.push(Property::MaskImage(images, prefix));
927        self.flushed_properties.insert(MaskProperty::MaskImage);
928      }
929    }
930
931    prop!(positions, MaskPosition);
932    prop!(sizes, MaskSize);
933    prop!(repeats, MaskRepeat);
934    prop!(clips, MaskClip);
935    prop!(origins, MaskOrigin);
936
937    if let Some(composites) = composites {
938      let prefix = context.targets.prefixes(VendorPrefix::None, Feature::MaskComposite);
939      if prefix.contains(VendorPrefix::WebKit) {
940        dest.push(Property::WebKitMaskComposite(
941          composites.iter().map(|c| (*c).into()).collect(),
942        ));
943      }
944
945      dest.push(Property::MaskComposite(composites));
946      self.flushed_properties.insert(MaskProperty::MaskComposite);
947    }
948
949    if let Some(modes) = modes {
950      let prefix = context.targets.prefixes(VendorPrefix::None, Feature::Mask);
951      if prefix.contains(VendorPrefix::WebKit) {
952        dest.push(Property::WebKitMaskSourceType(
953          modes.iter().map(|c| (*c).into()).collect(),
954          VendorPrefix::WebKit,
955        ));
956      }
957
958      dest.push(Property::MaskMode(modes));
959      self.flushed_properties.insert(MaskProperty::MaskMode);
960    }
961  }
962
963  fn flush_mask_shorthand(
964    &self,
965    masks: SmallVec<[Mask<'i>; 1]>,
966    prefix: VendorPrefix,
967    dest: &mut DeclarationList<'i>,
968  ) {
969    if prefix.contains(VendorPrefix::WebKit)
970      && masks
971        .iter()
972        .any(|mask| mask.composite != MaskComposite::default() || mask.mode != MaskMode::default())
973    {
974      // Prefixed shorthand syntax did not support mask-composite or mask-mode. These map to different webkit-specific properties.
975      // -webkit-mask-composite uses a different syntax than mask-composite.
976      // -webkit-mask-source-type is equivalent to mask-mode, but only supported in Safari, not Chrome.
977      let mut webkit = masks.clone();
978      let mut composites: SmallVec<[WebKitMaskComposite; 1]> = SmallVec::new();
979      let mut modes: SmallVec<[WebKitMaskSourceType; 1]> = SmallVec::new();
980      let mut needs_composites = false;
981      let mut needs_modes = false;
982      for mask in &mut webkit {
983        let composite = std::mem::take(&mut mask.composite);
984        if composite != MaskComposite::default() {
985          needs_composites = true;
986        }
987        composites.push(composite.into());
988
989        let mode = std::mem::take(&mut mask.mode);
990        if mode != MaskMode::default() {
991          needs_modes = true;
992        }
993        modes.push(mode.into());
994      }
995
996      dest.push(Property::Mask(webkit, VendorPrefix::WebKit));
997      if needs_composites {
998        dest.push(Property::WebKitMaskComposite(composites));
999      }
1000      if needs_modes {
1001        dest.push(Property::WebKitMaskSourceType(modes, VendorPrefix::WebKit));
1002      }
1003
1004      let prefix = prefix - VendorPrefix::WebKit;
1005      if !prefix.is_empty() {
1006        dest.push(Property::Mask(masks, prefix));
1007      }
1008    } else {
1009      dest.push(Property::Mask(masks, prefix));
1010    }
1011  }
1012
1013  fn flush_mask_border(&mut self, dest: &mut DeclarationList<'i>, context: &mut PropertyHandlerContext<'i, '_>) {
1014    let mut source = std::mem::take(&mut self.border_source);
1015    let mut slice = std::mem::take(&mut self.border_slice);
1016    let mut width = std::mem::take(&mut self.border_width);
1017    let mut outset = std::mem::take(&mut self.border_outset);
1018    let mut repeat = std::mem::take(&mut self.border_repeat);
1019    let mut mode = std::mem::take(&mut self.border_mode);
1020
1021    if let (
1022      Some((source, source_vp)),
1023      Some((slice, slice_vp)),
1024      Some((width, width_vp)),
1025      Some((outset, outset_vp)),
1026      Some((repeat, repeat_vp)),
1027    ) = (&mut source, &mut slice, &mut width, &mut outset, &mut repeat)
1028    {
1029      let intersection = *source_vp & *slice_vp & *width_vp & *outset_vp & *repeat_vp;
1030      if !intersection.is_empty() && (!intersection.contains(VendorPrefix::None) || mode.is_some()) {
1031        let mut mask_border = MaskBorder {
1032          source: source.clone(),
1033          slice: slice.clone(),
1034          width: width.clone(),
1035          outset: outset.clone(),
1036          repeat: repeat.clone(),
1037          mode: mode.unwrap_or_default(),
1038        };
1039
1040        let mut prefix = context.targets.prefixes(intersection, Feature::MaskBorder);
1041        if !self.flushed_properties.intersects(MaskProperty::MaskBorder) {
1042          // Get vendor prefix and color fallbacks.
1043          let fallbacks = mask_border.get_fallbacks(context.targets);
1044          for fallback in fallbacks {
1045            let mut p = fallback.source.get_vendor_prefix() - VendorPrefix::None & prefix;
1046            if p.is_empty() {
1047              p = prefix;
1048            }
1049
1050            if p.contains(VendorPrefix::WebKit) {
1051              dest.push(Property::WebKitMaskBoxImage(
1052                fallback.clone().into(),
1053                VendorPrefix::WebKit,
1054              ));
1055            }
1056
1057            if p.contains(VendorPrefix::None) {
1058              dest.push(Property::MaskBorder(fallback));
1059            }
1060          }
1061        }
1062
1063        let p = mask_border.source.get_vendor_prefix() - VendorPrefix::None & prefix;
1064        if !p.is_empty() {
1065          prefix = p;
1066        }
1067
1068        if prefix.contains(VendorPrefix::WebKit) {
1069          dest.push(Property::WebKitMaskBoxImage(
1070            mask_border.clone().into(),
1071            VendorPrefix::WebKit,
1072          ));
1073        }
1074
1075        if prefix.contains(VendorPrefix::None) {
1076          dest.push(Property::MaskBorder(mask_border));
1077          self.flushed_properties.insert(MaskProperty::MaskBorder);
1078          mode = None;
1079        }
1080
1081        source_vp.remove(intersection);
1082        slice_vp.remove(intersection);
1083        width_vp.remove(intersection);
1084        outset_vp.remove(intersection);
1085        repeat_vp.remove(intersection);
1086      }
1087    }
1088
1089    if let Some((mut source, mut prefix)) = source {
1090      prefix = context.targets.prefixes(prefix, Feature::MaskBorderSource);
1091
1092      if !self.flushed_properties.contains(MaskProperty::MaskBorderSource) {
1093        // Get vendor prefix and color fallbacks.
1094        let fallbacks = source.get_fallbacks(context.targets);
1095        for fallback in fallbacks {
1096          if prefix.contains(VendorPrefix::WebKit) {
1097            dest.push(Property::WebKitMaskBoxImageSource(
1098              fallback.clone(),
1099              VendorPrefix::WebKit,
1100            ));
1101          }
1102
1103          if prefix.contains(VendorPrefix::None) {
1104            dest.push(Property::MaskBorderSource(fallback));
1105          }
1106        }
1107      }
1108
1109      if prefix.contains(VendorPrefix::WebKit) {
1110        dest.push(Property::WebKitMaskBoxImageSource(source.clone(), VendorPrefix::WebKit));
1111      }
1112
1113      if prefix.contains(VendorPrefix::None) {
1114        dest.push(Property::MaskBorderSource(source));
1115        self.flushed_properties.insert(MaskProperty::MaskBorderSource);
1116      }
1117    }
1118
1119    macro_rules! prop {
1120      ($val: expr, $prop: ident, $webkit: ident) => {
1121        if let Some((val, mut prefix)) = $val {
1122          prefix = context.targets.prefixes(prefix, Feature::$prop);
1123          if prefix.contains(VendorPrefix::WebKit) {
1124            dest.push(Property::$webkit(val.clone(), VendorPrefix::WebKit));
1125          }
1126
1127          if prefix.contains(VendorPrefix::None) {
1128            dest.push(Property::$prop(val));
1129          }
1130          self.flushed_properties.insert(MaskProperty::$prop);
1131        }
1132      };
1133    }
1134
1135    prop!(slice, MaskBorderSlice, WebKitMaskBoxImageSlice);
1136    prop!(width, MaskBorderWidth, WebKitMaskBoxImageWidth);
1137    prop!(outset, MaskBorderOutset, WebKitMaskBoxImageOutset);
1138    prop!(repeat, MaskBorderRepeat, WebKitMaskBoxImageRepeat);
1139
1140    if let Some(mode) = mode {
1141      dest.push(Property::MaskBorderMode(mode));
1142      self.flushed_properties.insert(MaskProperty::MaskBorderMode);
1143    }
1144  }
1145}
1146
1147#[inline]
1148fn is_mask_property(property_id: &PropertyId) -> bool {
1149  match property_id {
1150    PropertyId::MaskImage(_)
1151    | PropertyId::MaskPosition(_)
1152    | PropertyId::MaskSize(_)
1153    | PropertyId::MaskRepeat(_)
1154    | PropertyId::MaskClip(_)
1155    | PropertyId::MaskOrigin(_)
1156    | PropertyId::MaskComposite
1157    | PropertyId::MaskMode
1158    | PropertyId::Mask(_) => true,
1159    _ => false,
1160  }
1161}
1162
1163#[inline]
1164fn is_mask_border_property(property_id: &PropertyId) -> bool {
1165  match property_id {
1166    PropertyId::MaskBorderSource
1167    | PropertyId::MaskBorderSlice
1168    | PropertyId::MaskBorderWidth
1169    | PropertyId::MaskBorderOutset
1170    | PropertyId::MaskBorderRepeat
1171    | PropertyId::MaskBorderMode
1172    | PropertyId::MaskBorder => true,
1173    _ => false,
1174  }
1175}
1176
1177#[inline]
1178pub(crate) fn get_webkit_mask_property(property_id: &PropertyId) -> Option<PropertyId<'static>> {
1179  Some(match property_id {
1180    PropertyId::MaskBorderSource => PropertyId::WebKitMaskBoxImageSource(VendorPrefix::WebKit),
1181    PropertyId::MaskBorderSlice => PropertyId::WebKitMaskBoxImageSlice(VendorPrefix::WebKit),
1182    PropertyId::MaskBorderWidth => PropertyId::WebKitMaskBoxImageWidth(VendorPrefix::WebKit),
1183    PropertyId::MaskBorderOutset => PropertyId::WebKitMaskBoxImageOutset(VendorPrefix::WebKit),
1184    PropertyId::MaskBorderRepeat => PropertyId::WebKitMaskBoxImageRepeat(VendorPrefix::WebKit),
1185    PropertyId::MaskBorder => PropertyId::WebKitMaskBoxImage(VendorPrefix::WebKit),
1186    PropertyId::MaskComposite => PropertyId::WebKitMaskComposite,
1187    PropertyId::MaskMode => PropertyId::WebKitMaskSourceType(VendorPrefix::WebKit),
1188    _ => return None,
1189  })
1190}