Skip to main content

rspack_lightningcss/values/
url.rs

1//! CSS url() values.
2
3use crate::dependencies::{Dependency, Location, UrlDependency};
4use crate::error::{ParserError, PrinterError};
5use crate::traits::{Parse, ToCss};
6use crate::values::string::CowArcStr;
7#[cfg(feature = "visitor")]
8use crate::visitor::Visit;
9use cssparser::*;
10use std::fmt::{self, Write};
11
12/// A CSS [url()](https://www.w3.org/TR/css-values-4/#urls) value and its source location.
13#[derive(Debug, Clone)]
14#[cfg_attr(feature = "visitor", derive(Visit))]
15#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
16#[cfg_attr(feature = "visitor", visit(visit_url, URLS))]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
19pub struct Url<'i> {
20  /// The url string.
21  #[cfg_attr(feature = "serde", serde(borrow))]
22  pub url: CowArcStr<'i>,
23  /// The location where the `url()` was seen in the CSS source file.
24  pub loc: Location,
25}
26
27impl<'i> PartialEq for Url<'i> {
28  fn eq(&self, other: &Self) -> bool {
29    self.url == other.url
30  }
31}
32
33impl<'i> Parse<'i> for Url<'i> {
34  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
35    let loc = input.current_source_location();
36    let url = input.expect_url()?.into();
37    Ok(Url { url, loc: loc.into() })
38  }
39}
40
41impl<'i> ToCss for Url<'i> {
42  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
43    let dep = if dest.has_dependencies() {
44      Some(UrlDependency::new(self, dest.filename()))
45    } else {
46      None
47    };
48
49    // If adding dependencies, always write url() with quotes so that the placeholder can
50    // be replaced without escaping more easily. Quotes may be removed later during minification.
51    if let Some(dep) = dep {
52      dest.write_str("url(")?;
53      serialize_string(&dep.placeholder, dest)?;
54      dest.write_char(')')?;
55
56      dest.add_dependency(Dependency::Url(dep));
57
58      return Ok(());
59    }
60
61    use cssparser::ToCss;
62    if dest.options().minify {
63      let mut buf = String::new();
64      Token::UnquotedUrl(CowRcStr::from(self.url.as_ref())).to_css(&mut buf)?;
65
66      // If quoting could be shorter, choose the quote that needs fewer escapes,
67      // then compare with the unquoted url. Keep the existing choice on ties.
68      if buf.len() > self.url.len() + 7 {
69        let mut single_quotes = 0;
70        let mut double_quotes = 0;
71        for b in self.url.bytes() {
72          match b {
73            b'\'' => single_quotes += 1,
74            b'"' => double_quotes += 1,
75            _ => {}
76          }
77        }
78
79        let mut buf2 = String::new();
80        if double_quotes > single_quotes {
81          serialize_single_quoted_string(&self.url, &mut buf2)?;
82        } else {
83          serialize_string(&self.url, &mut buf2)?;
84        }
85        if buf2.len() + 5 < buf.len() {
86          dest.write_str("url(")?;
87          dest.write_str(&buf2)?;
88          dest.write_char(')')?;
89          return Ok(());
90        }
91      }
92
93      dest.write_str(&buf)?;
94    } else {
95      dest.write_str("url(")?;
96      serialize_string(&self.url, dest)?;
97      dest.write_char(')')?;
98    }
99
100    Ok(())
101  }
102}
103
104fn serialize_single_quoted_string<W: Write>(value: &str, dest: &mut W) -> fmt::Result {
105  dest.write_char('\'')?;
106  let mut start = 0;
107  for (i, b) in value.bytes().enumerate() {
108    if matches!(b, b'\'' | b'"') {
109      // Delegate all other escapes, including hex escape terminators, to cssparser.
110      CssStringWriter::new(dest).write_str(&value[start..i])?;
111      if b == b'\'' {
112        dest.write_char('\\')?;
113      }
114      dest.write_char(b as char)?;
115      start = i + 1;
116    }
117  }
118  CssStringWriter::new(dest).write_str(&value[start..])?;
119  dest.write_char('\'')
120}
121
122impl<'i> Url<'i> {
123  /// Returns whether the URL is absolute, and not relative.
124  pub fn is_absolute(&self) -> bool {
125    let url = self.url.as_ref();
126
127    // Quick checks. If the url starts with '.', it is relative.
128    if url.starts_with('.') {
129      return false;
130    }
131
132    // If the url starts with '/' it is absolute.
133    if url.starts_with('/') {
134      return true;
135    }
136
137    // If the url starts with '#' we have a fragment URL.
138    // These are resolved relative to the document rather than the CSS file.
139    // https://drafts.csswg.org/css-values-4/#local-urls
140    if url.starts_with('#') {
141      return true;
142    }
143
144    // Otherwise, we might have a scheme. These must start with an ascii alpha character.
145    // https://url.spec.whatwg.org/#scheme-start-state
146    if !url.starts_with(|c| matches!(c, 'a'..='z' | 'A'..='Z')) {
147      return false;
148    }
149
150    // https://url.spec.whatwg.org/#scheme-state
151    for b in url.as_bytes() {
152      let c = *b as char;
153      match c {
154        'a'..='z' | 'A'..='Z' | '0'..='9' | '+' | '-' | '.' => {}
155        ':' => return true,
156        _ => break,
157      }
158    }
159
160    false
161  }
162}