Skip to main content

rspack_lightningcss/values/
image.rs

1//! CSS image values.
2
3use super::color::ColorFallbackKind;
4use super::gradient::*;
5use super::resolution::Resolution;
6use crate::compat;
7use crate::dependencies::{Dependency, UrlDependency};
8use crate::error::{ParserError, PrinterError};
9use crate::prefixes::{is_webkit_gradient, Feature};
10use crate::targets::{Browsers, Targets};
11use crate::traits::{FallbackValues, IsCompatible, Parse, ToCss};
12use crate::values::string::CowArcStr;
13use crate::values::url::Url;
14use crate::vendor_prefix::VendorPrefix;
15#[cfg(feature = "visitor")]
16use crate::visitor::Visit;
17use cssparser::*;
18use smallvec::SmallVec;
19
20/// A CSS [`<image>`](https://www.w3.org/TR/css-images-3/#image-values) value.
21#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
22#[cfg_attr(feature = "visitor", derive(Visit))]
23#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
24#[cfg_attr(feature = "visitor", visit(visit_image, IMAGES))]
25#[cfg_attr(
26  feature = "serde",
27  derive(serde::Serialize, serde::Deserialize),
28  serde(tag = "type", content = "value", rename_all = "kebab-case")
29)]
30#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
31pub enum Image<'i> {
32  /// The `none` keyword.
33  None,
34  /// A `url()`.
35  #[cfg_attr(feature = "serde", serde(borrow))]
36  Url(Url<'i>),
37  /// A gradient.
38  Gradient(Box<Gradient>),
39  /// An `image-set()`.
40  ImageSet(ImageSet<'i>),
41}
42
43impl<'i> Default for Image<'i> {
44  fn default() -> Image<'i> {
45    Image::None
46  }
47}
48
49impl<'i> Image<'i> {
50  /// Returns whether the image includes any vendor prefixed values.
51  pub fn has_vendor_prefix(&self) -> bool {
52    let prefix = self.get_vendor_prefix();
53    !prefix.is_empty() && prefix != VendorPrefix::None
54  }
55
56  /// Returns the vendor prefix used in the image value.
57  pub fn get_vendor_prefix(&self) -> VendorPrefix {
58    match self {
59      Image::Gradient(a) => a.get_vendor_prefix(),
60      Image::ImageSet(a) => a.get_vendor_prefix(),
61      _ => VendorPrefix::empty(),
62    }
63  }
64
65  /// Returns the vendor prefixes that are needed for the given browser targets.
66  pub fn get_necessary_prefixes(&self, targets: Targets) -> VendorPrefix {
67    match self {
68      Image::Gradient(grad) => grad.get_necessary_prefixes(targets),
69      Image::ImageSet(image_set) => image_set.get_necessary_prefixes(targets),
70      _ => VendorPrefix::None,
71    }
72  }
73
74  /// Returns a vendor prefixed version of the image for the given vendor prefixes.
75  pub fn get_prefixed(&self, prefix: VendorPrefix) -> Image<'i> {
76    match self {
77      Image::Gradient(grad) => Image::Gradient(Box::new(grad.get_prefixed(prefix))),
78      Image::ImageSet(image_set) => Image::ImageSet(image_set.get_prefixed(prefix)),
79      _ => self.clone(),
80    }
81  }
82
83  /// Returns a legacy `-webkit-gradient()` value for the image.
84  ///
85  /// May return an error in case the gradient cannot be converted.
86  pub fn get_legacy_webkit(&self) -> Result<Image<'i>, ()> {
87    match self {
88      Image::Gradient(grad) => Ok(Image::Gradient(Box::new(grad.get_legacy_webkit()?))),
89      _ => Ok(self.clone()),
90    }
91  }
92
93  /// Returns the color fallbacks that are needed for the given browser targets.
94  pub fn get_necessary_fallbacks(&self, targets: Targets) -> ColorFallbackKind {
95    match self {
96      Image::Gradient(grad) => grad.get_necessary_fallbacks(targets),
97      _ => ColorFallbackKind::empty(),
98    }
99  }
100
101  /// Returns a fallback version of the image for the given color fallback type.
102  pub fn get_fallback(&self, kind: ColorFallbackKind) -> Image<'i> {
103    match self {
104      Image::Gradient(grad) => Image::Gradient(Box::new(grad.get_fallback(kind))),
105      _ => self.clone(),
106    }
107  }
108}
109
110impl<'i> IsCompatible for Image<'i> {
111  fn is_compatible(&self, browsers: Browsers) -> bool {
112    match self {
113      Image::Gradient(g) => match &**g {
114        Gradient::Linear(g) => {
115          compat::Feature::LinearGradient.is_compatible(browsers) && g.is_compatible(browsers)
116        }
117        Gradient::RepeatingLinear(g) => {
118          compat::Feature::RepeatingLinearGradient.is_compatible(browsers) && g.is_compatible(browsers)
119        }
120        Gradient::Radial(g) => {
121          compat::Feature::RadialGradient.is_compatible(browsers) && g.is_compatible(browsers)
122        }
123        Gradient::RepeatingRadial(g) => {
124          compat::Feature::RepeatingRadialGradient.is_compatible(browsers) && g.is_compatible(browsers)
125        }
126        Gradient::Conic(g) => compat::Feature::ConicGradient.is_compatible(browsers) && g.is_compatible(browsers),
127        Gradient::RepeatingConic(g) => {
128          compat::Feature::RepeatingConicGradient.is_compatible(browsers) && g.is_compatible(browsers)
129        }
130        Gradient::WebKitGradient(..) => is_webkit_gradient(browsers),
131      },
132      Image::ImageSet(i) => i.is_compatible(browsers),
133      Image::Url(..) | Image::None => true,
134    }
135  }
136}
137
138pub(crate) trait ImageFallback<'i>: Sized {
139  fn get_image(&self) -> &Image<'i>;
140  fn with_image(&self, image: Image<'i>) -> Self;
141
142  #[inline]
143  fn get_necessary_fallbacks(&self, targets: Targets) -> ColorFallbackKind {
144    self.get_image().get_necessary_fallbacks(targets)
145  }
146
147  #[inline]
148  fn get_fallback(&self, kind: ColorFallbackKind) -> Self {
149    self.with_image(self.get_image().get_fallback(kind))
150  }
151}
152
153impl<'i> ImageFallback<'i> for Image<'i> {
154  #[inline]
155  fn get_image(&self) -> &Image<'i> {
156    self
157  }
158
159  #[inline]
160  fn with_image(&self, image: Image<'i>) -> Self {
161    image
162  }
163}
164
165impl<'i> FallbackValues for Image<'i> {
166  fn get_fallbacks(&mut self, targets: Targets) -> Vec<Self> {
167    // Determine which prefixes and color fallbacks are needed.
168    let prefixes = self.get_necessary_prefixes(targets);
169    let fallbacks = self.get_necessary_fallbacks(targets);
170    let mut res = Vec::new();
171
172    // Get RGB fallbacks if needed.
173    let rgb = if fallbacks.contains(ColorFallbackKind::RGB) {
174      Some(self.get_fallback(ColorFallbackKind::RGB))
175    } else {
176      None
177    };
178
179    // Prefixed properties only support RGB.
180    let prefix_image = rgb.as_ref().unwrap_or(self);
181
182    // Legacy -webkit-gradient()
183    if prefixes.contains(VendorPrefix::WebKit)
184      && targets.browsers.map(is_webkit_gradient).unwrap_or(false)
185      && matches!(prefix_image, Image::Gradient(_))
186    {
187      if let Ok(legacy) = prefix_image.get_legacy_webkit() {
188        res.push(legacy);
189      }
190    }
191
192    // Standard syntax, with prefixes.
193    if prefixes.contains(VendorPrefix::WebKit) {
194      res.push(prefix_image.get_prefixed(VendorPrefix::WebKit))
195    }
196
197    if prefixes.contains(VendorPrefix::Moz) {
198      res.push(prefix_image.get_prefixed(VendorPrefix::Moz))
199    }
200
201    if prefixes.contains(VendorPrefix::O) {
202      res.push(prefix_image.get_prefixed(VendorPrefix::O))
203    }
204
205    if prefixes.contains(VendorPrefix::None) {
206      // Unprefixed, rgb fallback.
207      if let Some(rgb) = rgb {
208        res.push(rgb);
209      }
210
211      // P3 fallback.
212      if fallbacks.contains(ColorFallbackKind::P3) {
213        res.push(self.get_fallback(ColorFallbackKind::P3));
214      }
215
216      // Convert original to lab if needed (e.g. if oklab is not supported but lab is).
217      if fallbacks.contains(ColorFallbackKind::LAB) {
218        *self = self.get_fallback(ColorFallbackKind::LAB);
219      }
220    } else if let Some(last) = res.pop() {
221      // Prefixed property with no unprefixed version.
222      // Replace self with the last prefixed version so that it doesn't
223      // get duplicated when the caller pushes the original value.
224      *self = last;
225    }
226
227    res
228  }
229}
230
231impl<'i, T: ImageFallback<'i>> FallbackValues for SmallVec<[T; 1]> {
232  fn get_fallbacks(&mut self, targets: Targets) -> Vec<Self> {
233    // Determine what vendor prefixes and color fallbacks are needed.
234    let mut prefixes = VendorPrefix::empty();
235    let mut fallbacks = ColorFallbackKind::empty();
236    let mut res = Vec::new();
237    for item in self.iter() {
238      prefixes |= item.get_image().get_necessary_prefixes(targets);
239      fallbacks |= item.get_necessary_fallbacks(targets);
240    }
241
242    // Get RGB fallbacks if needed.
243    let rgb: Option<SmallVec<[T; 1]>> = if fallbacks.contains(ColorFallbackKind::RGB) {
244      Some(self.iter().map(|item| item.get_fallback(ColorFallbackKind::RGB)).collect())
245    } else {
246      None
247    };
248
249    // Prefixed properties only support RGB.
250    let prefix_images = rgb.as_ref().unwrap_or(&self);
251
252    // Legacy -webkit-gradient()
253    if prefixes.contains(VendorPrefix::WebKit) && targets.browsers.map(is_webkit_gradient).unwrap_or(false) {
254      let images: SmallVec<[T; 1]> = prefix_images
255        .iter()
256        .map(|item| item.get_image().get_legacy_webkit().map(|image| item.with_image(image)))
257        .flatten()
258        .collect();
259      if !images.is_empty() {
260        res.push(images)
261      }
262    }
263
264    // Standard syntax, with prefixes.
265    macro_rules! prefix {
266      ($prefix: ident) => {
267        if prefixes.contains(VendorPrefix::$prefix) {
268          let images = prefix_images
269            .iter()
270            .map(|item| {
271              let image = item.get_image().get_prefixed(VendorPrefix::$prefix);
272              item.with_image(image)
273            })
274            .collect();
275          res.push(images)
276        }
277      };
278    }
279
280    prefix!(WebKit);
281    prefix!(Moz);
282    prefix!(O);
283    if prefixes.contains(VendorPrefix::None) {
284      if let Some(rgb) = rgb {
285        res.push(rgb);
286      }
287
288      if fallbacks.contains(ColorFallbackKind::P3) {
289        let p3_images = self.iter().map(|item| item.get_fallback(ColorFallbackKind::P3)).collect();
290
291        res.push(p3_images)
292      }
293
294      // Convert to lab if needed (e.g. if oklab is not supported but lab is).
295      if fallbacks.contains(ColorFallbackKind::LAB) {
296        for item in self.iter_mut() {
297          *item = item.get_fallback(ColorFallbackKind::LAB);
298        }
299      }
300    } else if let Some(last) = res.pop() {
301      // Prefixed property with no unprefixed version.
302      // Replace self with the last prefixed version so that it doesn't
303      // get duplicated when the caller pushes the original value.
304      *self = last;
305    }
306
307    res
308  }
309}
310
311/// A CSS [`image-set()`](https://drafts.csswg.org/css-images-4/#image-set-notation) value.
312///
313/// `image-set()` allows the user agent to choose between multiple versions of an image to
314/// display the most appropriate resolution or file type that it supports.
315#[derive(Debug, Clone, PartialEq)]
316#[cfg_attr(feature = "visitor", derive(Visit))]
317#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
318#[cfg_attr(
319  feature = "serde",
320  derive(serde::Serialize, serde::Deserialize),
321  serde(rename_all = "camelCase")
322)]
323#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
324pub struct ImageSet<'i> {
325  /// The image options to choose from.
326  #[cfg_attr(feature = "serde", serde(borrow))]
327  pub options: Vec<ImageSetOption<'i>>,
328  /// The vendor prefix for the `image-set()` function.
329  pub vendor_prefix: VendorPrefix,
330}
331
332impl<'i> ImageSet<'i> {
333  /// Returns the vendor prefix for the `image-set()`.
334  pub fn get_vendor_prefix(&self) -> VendorPrefix {
335    self.vendor_prefix
336  }
337
338  /// Returns the vendor prefixes needed for the given browser targets.
339  pub fn get_necessary_prefixes(&self, targets: Targets) -> VendorPrefix {
340    targets.prefixes(self.vendor_prefix, Feature::ImageSet)
341  }
342
343  /// Returns the `image-set()` value with the given vendor prefix.
344  pub fn get_prefixed(&self, prefix: VendorPrefix) -> ImageSet<'i> {
345    ImageSet {
346      options: self.options.clone(),
347      vendor_prefix: prefix,
348    }
349  }
350}
351
352impl<'i> Parse<'i> for ImageSet<'i> {
353  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
354    let location = input.current_source_location();
355    let f = input.expect_function()?;
356    let vendor_prefix = match_ignore_ascii_case! { &*f,
357      "image-set" => VendorPrefix::None,
358      "-webkit-image-set" => VendorPrefix::WebKit,
359      _ => return Err(location.new_unexpected_token_error(
360        cssparser::Token::Ident(f.clone())
361      ))
362    };
363
364    let options = input.parse_nested_block(|input| input.parse_comma_separated(ImageSetOption::parse))?;
365    Ok(ImageSet { options, vendor_prefix })
366  }
367}
368
369impl<'i> ToCss for ImageSet<'i> {
370  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
371    self.vendor_prefix.to_css(dest)?;
372    dest.write_str("image-set(")?;
373    let mut first = true;
374    for option in &self.options {
375      if first {
376        first = false;
377      } else {
378        dest.delim(',', false)?;
379      }
380      option.to_css(dest, self.vendor_prefix != VendorPrefix::None)?;
381    }
382    dest.write_char(')')?;
383    Ok(())
384  }
385}
386
387impl<'i> IsCompatible for ImageSet<'i> {
388  fn is_compatible(&self, browsers: Browsers) -> bool {
389    compat::Feature::ImageSet.is_compatible(browsers)
390      && self.options.iter().all(|opt| opt.image.is_compatible(browsers))
391  }
392}
393
394/// An image option within the `image-set()` function. See [ImageSet](ImageSet).
395#[derive(Debug, Clone, PartialEq)]
396#[cfg_attr(feature = "visitor", derive(Visit))]
397#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
398#[cfg_attr(
399  feature = "serde",
400  derive(serde::Serialize, serde::Deserialize),
401  serde(rename_all = "camelCase")
402)]
403#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
404pub struct ImageSetOption<'i> {
405  /// The image for this option.
406  #[cfg_attr(feature = "visitor", skip_type)]
407  pub image: Image<'i>,
408  /// The resolution of the image.
409  pub resolution: Resolution,
410  /// The mime type of the image.
411  #[cfg_attr(feature = "serde", serde(borrow))]
412  pub file_type: Option<CowArcStr<'i>>,
413}
414
415impl<'i> Parse<'i> for ImageSetOption<'i> {
416  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
417    let loc = input.current_source_location();
418    let image = if let Ok(url) = input.try_parse(|input| input.expect_url_or_string()) {
419      Image::Url(Url {
420        url: url.into(),
421        loc: loc.into(),
422      })
423    } else {
424      Image::parse(input)?
425    };
426
427    let (resolution, file_type) = if let Ok(res) = input.try_parse(Resolution::parse) {
428      let file_type = input.try_parse(parse_file_type).ok();
429      (res, file_type)
430    } else {
431      let file_type = input.try_parse(parse_file_type).ok();
432      let resolution = input.try_parse(Resolution::parse).unwrap_or(Resolution::Dppx(1.0));
433      (resolution, file_type)
434    };
435
436    Ok(ImageSetOption {
437      image,
438      resolution,
439      file_type: file_type.map(|x| x.into()),
440    })
441  }
442}
443
444impl<'i> ImageSetOption<'i> {
445  fn to_css<PrinterT: crate::printer::PrinterTrait>(
446    &self,
447    dest: &mut PrinterT,
448    is_prefixed: bool,
449  ) -> Result<(), PrinterError> {
450    match &self.image {
451      // Prefixed syntax didn't allow strings, only url()
452      Image::Url(url) if !is_prefixed => {
453        // Add dependency if needed. Normally this is handled by the Url type.
454        let dep = if dest.state().dependencies.is_some() {
455          Some(UrlDependency::new(url, dest.filename()))
456        } else {
457          None
458        };
459        if let Some(dep) = dep {
460          serialize_string(&dep.placeholder, dest)?;
461          if let Some(dependencies) = dest.state_mut().dependencies.as_mut() {
462            dependencies.push(Dependency::Url(dep))
463          }
464        } else {
465          serialize_string(&url.url, dest)?;
466        }
467      }
468      _ => self.image.to_css(dest)?,
469    }
470
471    // TODO: Throwing an error when `self.resolution = Resolution::Dppx(0.0)`
472    // TODO: -webkit-image-set() does not support `<image()> | <image-set()> |
473    // <cross-fade()> | <element()> | <gradient>` and `type(<string>)`.
474    dest.write_char(' ')?;
475
476    // Safari only supports the x resolution unit in image-set().
477    // In other places, x was added as an alias later.
478    // Temporarily ignore the targets while printing here.
479    let targets = dest.state().targets.current;
480    dest.state_mut().targets.current = Targets::default();
481    let res = self.resolution.to_css(dest);
482    dest.state_mut().targets.current = targets;
483    res?;
484
485    if let Some(file_type) = &self.file_type {
486      dest.write_str(" type(")?;
487      serialize_string(&file_type, dest)?;
488      dest.write_char(')')?;
489    }
490
491    Ok(())
492  }
493}
494
495fn parse_file_type<'i, 't>(input: &mut Parser<'i, 't>) -> Result<CowRcStr<'i>, ParseError<'i, ParserError<'i>>> {
496  input.expect_function_matching("type")?;
497  input.parse_nested_block(|input| Ok(input.expect_string_cloned()?))
498}