Skip to main content

rspack_lightningcss/properties/
box_shadow.rs

1//! The CSS box-shadow property.
2
3use super::PropertyId;
4use crate::context::PropertyHandlerContext;
5use crate::declaration::DeclarationList;
6use crate::error::{ParserError, PrinterError};
7use crate::prefixes::Feature;
8use crate::properties::Property;
9use crate::targets::Browsers;
10use crate::traits::{IsCompatible, Parse, PropertyHandler, ToCss, Zero};
11use crate::values::color::{ColorFallbackKind, CssColor};
12use crate::values::length::Length;
13use crate::values::number::NonNegative;
14use crate::vendor_prefix::VendorPrefix;
15#[cfg(feature = "visitor")]
16use crate::visitor::Visit;
17use cssparser::*;
18use smallvec::SmallVec;
19
20/// A value for the [box-shadow](https://drafts.csswg.org/css-backgrounds/#box-shadow) property.
21#[derive(Debug, Clone, PartialEq)]
22#[cfg_attr(feature = "visitor", derive(Visit))]
23#[cfg_attr(
24  feature = "serde",
25  derive(serde::Serialize, serde::Deserialize),
26  serde(rename_all = "camelCase")
27)]
28#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
29#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
30pub struct BoxShadow {
31  /// The color of the box shadow.
32  pub color: CssColor,
33  /// The x offset of the shadow.
34  pub x_offset: Length,
35  /// The y offset of the shadow.
36  pub y_offset: Length,
37  /// The blur radius of the shadow.
38  pub blur: NonNegative<Length>,
39  /// The spread distance of the shadow.
40  pub spread: Length,
41  /// Whether the shadow is inset within the box.
42  pub inset: bool,
43}
44
45impl<'i> Parse<'i> for BoxShadow {
46  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
47    let mut color = None;
48    let mut lengths = None;
49    let mut inset = false;
50
51    loop {
52      if !inset {
53        if input.try_parse(|input| input.expect_ident_matching("inset")).is_ok() {
54          inset = true;
55          continue;
56        }
57      }
58
59      if lengths.is_none() {
60        let value = input.try_parse::<_, _, ParseError<ParserError<'i>>>(|input| {
61          let horizontal = Length::parse(input)?;
62          let vertical = Length::parse(input)?;
63          let blur = input.try_parse(NonNegative::<Length>::parse).ok();
64          // A rejected blur radius must not be reinterpreted as a spread.
65          let spread = if blur.is_some() {
66            input.try_parse(Length::parse).unwrap_or(Length::zero())
67          } else {
68            Length::zero()
69          };
70          Ok((horizontal, vertical, blur.unwrap_or(NonNegative::zero()), spread))
71        });
72
73        if let Ok(value) = value {
74          lengths = Some(value);
75          continue;
76        }
77      }
78
79      if color.is_none() {
80        if let Ok(value) = input.try_parse(CssColor::parse) {
81          color = Some(value);
82          continue;
83        }
84      }
85
86      break;
87    }
88
89    let lengths = lengths.ok_or(input.new_error(BasicParseErrorKind::QualifiedRuleInvalid))?;
90    Ok(BoxShadow {
91      color: color.unwrap_or(CssColor::current_color()),
92      x_offset: lengths.0,
93      y_offset: lengths.1,
94      blur: lengths.2,
95      spread: lengths.3,
96      inset,
97    })
98  }
99}
100
101impl ToCss for BoxShadow {
102  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
103    if self.inset {
104      dest.write_str("inset ")?;
105    }
106
107    self.x_offset.to_css(dest)?;
108    dest.write_char(' ')?;
109    self.y_offset.to_css(dest)?;
110
111    if self.blur != NonNegative::zero() || self.spread != Length::zero() {
112      dest.write_char(' ')?;
113      self.blur.to_css(dest)?;
114
115      if self.spread != Length::zero() {
116        dest.write_char(' ')?;
117        self.spread.to_css(dest)?;
118      }
119    }
120
121    if self.color != CssColor::current_color() {
122      dest.write_char(' ')?;
123      self.color.to_css(dest)?;
124    }
125
126    Ok(())
127  }
128}
129
130impl IsCompatible for BoxShadow {
131  fn is_compatible(&self, browsers: Browsers) -> bool {
132    self.color.is_compatible(browsers)
133      && self.x_offset.is_compatible(browsers)
134      && self.y_offset.is_compatible(browsers)
135      && self.blur.is_compatible(browsers)
136      && self.spread.is_compatible(browsers)
137  }
138}
139
140#[derive(Default)]
141pub(crate) struct BoxShadowHandler {
142  box_shadows: Option<(SmallVec<[BoxShadow; 1]>, VendorPrefix)>,
143  flushed: bool,
144}
145
146impl<'i> PropertyHandler<'i> for BoxShadowHandler {
147  fn handle_property(
148    &mut self,
149    property: &Property<'i>,
150    dest: &mut DeclarationList<'i>,
151    context: &mut PropertyHandlerContext<'i, '_>,
152  ) -> bool {
153    match property {
154      Property::BoxShadow(box_shadows, prefix) => {
155        if self.box_shadows.is_some()
156          && matches!(context.targets.browsers, Some(browsers) if !box_shadows.is_compatible(browsers))
157        {
158          self.flush(dest, context);
159        }
160
161        if let Some((val, prefixes)) = &mut self.box_shadows {
162          if val != box_shadows && !prefixes.contains(*prefix) {
163            self.flush(dest, context);
164            self.box_shadows = Some((box_shadows.clone(), *prefix));
165          } else {
166            *val = box_shadows.clone();
167            *prefixes |= *prefix;
168          }
169        } else {
170          self.box_shadows = Some((box_shadows.clone(), *prefix));
171        }
172      }
173      Property::Unparsed(unparsed) if matches!(unparsed.property_id, PropertyId::BoxShadow(_)) => {
174        self.flush(dest, context);
175
176        let mut unparsed = unparsed.clone();
177        context.add_unparsed_fallbacks(&mut unparsed);
178        dest.push(Property::Unparsed(unparsed));
179        self.flushed = true;
180      }
181      _ => return false,
182    }
183
184    true
185  }
186
187  fn finalize(&mut self, dest: &mut DeclarationList<'i>, context: &mut PropertyHandlerContext<'i, '_>) {
188    self.flush(dest, context);
189    self.flushed = false;
190  }
191}
192
193impl BoxShadowHandler {
194  fn flush<'i>(&mut self, dest: &mut DeclarationList<'i>, context: &mut PropertyHandlerContext<'i, '_>) {
195    if self.box_shadows.is_none() {
196      return;
197    }
198
199    let box_shadows = std::mem::take(&mut self.box_shadows);
200
201    if let Some((box_shadows, prefixes)) = box_shadows {
202      if !self.flushed {
203        let mut prefixes = context.targets.prefixes(prefixes, Feature::BoxShadow);
204        let mut fallbacks = ColorFallbackKind::empty();
205        for shadow in &box_shadows {
206          fallbacks |= shadow.color.get_necessary_fallbacks(context.targets);
207        }
208
209        if fallbacks.contains(ColorFallbackKind::RGB) {
210          let rgb = box_shadows
211            .iter()
212            .map(|shadow| BoxShadow {
213              color: shadow.color.to_rgb().unwrap_or_else(|_| shadow.color.clone()),
214              ..shadow.clone()
215            })
216            .collect();
217          dest.push(Property::BoxShadow(rgb, prefixes));
218          if prefixes.contains(VendorPrefix::None) {
219            prefixes = VendorPrefix::None;
220          } else {
221            // Only output RGB for prefixed property (e.g. -webkit-box-shadow)
222            return;
223          }
224        }
225
226        if fallbacks.contains(ColorFallbackKind::P3) {
227          let p3 = box_shadows
228            .iter()
229            .map(|shadow| BoxShadow {
230              color: shadow.color.to_p3().unwrap_or_else(|_| shadow.color.clone()),
231              ..shadow.clone()
232            })
233            .collect();
234          dest.push(Property::BoxShadow(p3, VendorPrefix::None));
235        }
236
237        if fallbacks.contains(ColorFallbackKind::LAB) {
238          let lab = box_shadows
239            .iter()
240            .map(|shadow| BoxShadow {
241              color: shadow.color.to_lab().unwrap_or_else(|_| shadow.color.clone()),
242              ..shadow.clone()
243            })
244            .collect();
245          dest.push(Property::BoxShadow(lab, VendorPrefix::None));
246        } else {
247          dest.push(Property::BoxShadow(box_shadows, prefixes))
248        }
249      } else {
250        dest.push(Property::BoxShadow(box_shadows, prefixes))
251      }
252    }
253
254    self.flushed = true;
255  }
256}