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.state().dependencies.is_some() {
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      if let Some(dependencies) = dest.state_mut().dependencies.as_mut() {
57        dependencies.push(Dependency::Url(dep))
58      }
59
60      return Ok(());
61    }
62
63    use cssparser::ToCss;
64    if dest.options().minify {
65      let mut buf = String::new();
66      Token::UnquotedUrl(CowRcStr::from(self.url.as_ref())).to_css(&mut buf)?;
67
68      // If quoting could be shorter, choose the quote that needs fewer escapes,
69      // then compare with the unquoted url. Keep the existing choice on ties.
70      if buf.len() > self.url.len() + 7 {
71        let mut single_quotes = 0;
72        let mut double_quotes = 0;
73        for b in self.url.bytes() {
74          match b {
75            b'\'' => single_quotes += 1,
76            b'"' => double_quotes += 1,
77            _ => {}
78          }
79        }
80
81        let mut buf2 = String::new();
82        if double_quotes > single_quotes {
83          serialize_single_quoted_string(&self.url, &mut buf2)?;
84        } else {
85          serialize_string(&self.url, &mut buf2)?;
86        }
87        if buf2.len() + 5 < buf.len() {
88          dest.write_str("url(")?;
89          dest.write_str(&buf2)?;
90          dest.write_char(')')?;
91          return Ok(());
92        }
93      }
94
95      dest.write_str(&buf)?;
96    } else {
97      dest.write_str("url(")?;
98      serialize_string(&self.url, dest)?;
99      dest.write_char(')')?;
100    }
101
102    Ok(())
103  }
104}
105
106fn serialize_single_quoted_string<W: Write>(value: &str, dest: &mut W) -> fmt::Result {
107  dest.write_char('\'')?;
108  let mut start = 0;
109  for (i, b) in value.bytes().enumerate() {
110    if matches!(b, b'\'' | b'"') {
111      // Delegate all other escapes, including hex escape terminators, to cssparser.
112      CssStringWriter::new(dest).write_str(&value[start..i])?;
113      if b == b'\'' {
114        dest.write_char('\\')?;
115      }
116      dest.write_char(b as char)?;
117      start = i + 1;
118    }
119  }
120  CssStringWriter::new(dest).write_str(&value[start..])?;
121  dest.write_char('\'')
122}
123
124impl<'i> Url<'i> {
125  /// Returns whether the URL is absolute, and not relative.
126  pub fn is_absolute(&self) -> bool {
127    let url = self.url.as_ref();
128
129    // Quick checks. If the url starts with '.', it is relative.
130    if url.starts_with('.') {
131      return false;
132    }
133
134    // If the url starts with '/' it is absolute.
135    if url.starts_with('/') {
136      return true;
137    }
138
139    // If the url starts with '#' we have a fragment URL.
140    // These are resolved relative to the document rather than the CSS file.
141    // https://drafts.csswg.org/css-values-4/#local-urls
142    if url.starts_with('#') {
143      return true;
144    }
145
146    // Otherwise, we might have a scheme. These must start with an ascii alpha character.
147    // https://url.spec.whatwg.org/#scheme-start-state
148    if !url.starts_with(|c| matches!(c, 'a'..='z' | 'A'..='Z')) {
149      return false;
150    }
151
152    // https://url.spec.whatwg.org/#scheme-state
153    for b in url.as_bytes() {
154      let c = *b as char;
155      match c {
156        'a'..='z' | 'A'..='Z' | '0'..='9' | '+' | '-' | '.' => {}
157        ':' => return true,
158        _ => break,
159      }
160    }
161
162    false
163  }
164}