Skip to main content

rspack_lightningcss/rules/
font_face.rs

1//! The `@font-face` rule.
2
3use super::Location;
4use crate::error::{ParserError, PrinterError};
5use crate::macros::enum_property;
6use crate::properties::custom::CustomProperty;
7use crate::properties::font::{FontFamily, FontStretch, FontStyle as FontStyleProperty, FontWeight};
8use crate::stylesheet::ParserOptions;
9use crate::traits::{Parse, ToCss};
10use crate::values::angle::Angle;
11use crate::values::size::Size2D;
12use crate::values::string::CowArcStr;
13use crate::values::url::Url;
14#[cfg(feature = "visitor")]
15use crate::visitor::Visit;
16use cssparser::*;
17
18/// A [@font-face](https://drafts.csswg.org/css-fonts/#font-face-rule) rule.
19#[derive(Debug, PartialEq, Clone)]
20#[cfg_attr(feature = "visitor", derive(Visit))]
21#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
22#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
23#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
24pub struct FontFaceRule<'i> {
25  /// Declarations in the `@font-face` rule.
26  #[cfg_attr(feature = "serde", serde(borrow))]
27  pub properties: Vec<FontFaceProperty<'i>>,
28  /// The location of the rule in the source file.
29  #[cfg_attr(feature = "visitor", skip_visit)]
30  pub loc: Location,
31}
32
33/// A property within an `@font-face` rule.
34///
35/// See [FontFaceRule](FontFaceRule).
36#[derive(Debug, Clone, PartialEq)]
37#[cfg_attr(feature = "visitor", derive(Visit))]
38#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
39#[cfg_attr(
40  feature = "serde",
41  derive(serde::Serialize, serde::Deserialize),
42  serde(tag = "type", content = "value", rename_all = "kebab-case")
43)]
44#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
45pub enum FontFaceProperty<'i> {
46  /// The `src` property.
47  #[cfg_attr(feature = "serde", serde(borrow))]
48  Source(Vec<Source<'i>>),
49  /// The `font-family` property.
50  FontFamily(FontFamily<'i>),
51  /// The `font-style` property.
52  FontStyle(FontStyle),
53  /// The `font-weight` property.
54  FontWeight(Size2D<FontWeight>),
55  /// The `font-stretch` property.
56  FontStretch(Size2D<FontStretch>),
57  /// The `unicode-range` property.
58  UnicodeRange(Vec<UnicodeRange>),
59  /// An unknown or unsupported property.
60  Custom(CustomProperty<'i>),
61}
62
63/// A value for the [src](https://drafts.csswg.org/css-fonts/#src-desc)
64/// property in an `@font-face` rule.
65#[derive(Debug, Clone, PartialEq)]
66#[cfg_attr(feature = "visitor", derive(Visit))]
67#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
68#[cfg_attr(
69  feature = "serde",
70  derive(serde::Serialize, serde::Deserialize),
71  serde(tag = "type", content = "value", rename_all = "kebab-case")
72)]
73#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
74pub enum Source<'i> {
75  /// A `url()` with optional format metadata.
76  Url(UrlSource<'i>),
77  /// The `local()` function.
78  #[cfg_attr(feature = "serde", serde(borrow))]
79  Local(FontFamily<'i>),
80}
81
82impl<'i> Parse<'i> for Source<'i> {
83  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
84    match input.try_parse(UrlSource::parse) {
85      Ok(url) => return Ok(Source::Url(url)),
86      e @ Err(ParseError {
87        kind: ParseErrorKind::Basic(BasicParseErrorKind::AtRuleBodyInvalid),
88        ..
89      }) => {
90        return Err(e.err().unwrap());
91      }
92      _ => {}
93    }
94
95    input.expect_function_matching("local")?;
96    let local = input.parse_nested_block(FontFamily::parse)?;
97    Ok(Source::Local(local))
98  }
99}
100
101impl<'i> ToCss for Source<'i> {
102  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
103    match self {
104      Source::Url(url) => url.to_css(dest),
105      Source::Local(local) => {
106        dest.write_str("local(")?;
107        local.to_css(dest)?;
108        dest.write_char(')')?;
109        Ok(())
110      }
111    }
112  }
113}
114
115/// A `url()` value for the [src](https://drafts.csswg.org/css-fonts/#src-desc)
116/// property in an `@font-face` rule.
117#[derive(Debug, Clone, PartialEq)]
118#[cfg_attr(feature = "visitor", derive(Visit))]
119#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
120#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
121#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
122pub struct UrlSource<'i> {
123  /// The URL.
124  pub url: Url<'i>,
125  /// Optional `format()` function.
126  #[cfg_attr(feature = "serde", serde(borrow))]
127  pub format: Option<FontFormat<'i>>,
128  /// Optional `tech()` function.
129  pub tech: Vec<FontTechnology>,
130}
131
132impl<'i> Parse<'i> for UrlSource<'i> {
133  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
134    let url = Url::parse(input)?;
135
136    let format = if input.try_parse(|input| input.expect_function_matching("format")).is_ok() {
137      Some(input.parse_nested_block(FontFormat::parse)?)
138    } else {
139      None
140    };
141
142    let tech = if input.try_parse(|input| input.expect_function_matching("tech")).is_ok() {
143      input.parse_nested_block(Vec::<FontTechnology>::parse)?
144    } else {
145      vec![]
146    };
147
148    Ok(UrlSource { url, format, tech })
149  }
150}
151
152impl<'i> ToCss for UrlSource<'i> {
153  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
154    self.url.to_css(dest)?;
155    if let Some(format) = &self.format {
156      dest.whitespace()?;
157      dest.write_str("format(")?;
158      format.to_css(dest)?;
159      dest.write_char(')')?;
160    }
161
162    if !self.tech.is_empty() {
163      dest.whitespace()?;
164      dest.write_str("tech(")?;
165      self.tech.to_css(dest)?;
166      dest.write_char(')')?;
167    }
168    Ok(())
169  }
170}
171
172/// A font format keyword in the `format()` function of the the
173/// [src](https://drafts.csswg.org/css-fonts/#src-desc)
174/// property of an `@font-face` rule.
175#[derive(Debug, Clone, PartialEq)]
176#[cfg_attr(feature = "visitor", derive(Visit))]
177#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
178#[cfg_attr(
179  feature = "serde",
180  derive(serde::Serialize, serde::Deserialize),
181  serde(tag = "type", content = "value", rename_all = "lowercase")
182)]
183#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
184pub enum FontFormat<'i> {
185  /// [src](https://drafts.csswg.org/css-fonts/#font-format-definitions)
186  /// A WOFF 1.0 font.
187  WOFF,
188  /// A WOFF 2.0 font.
189  WOFF2,
190  /// A TrueType font.
191  TrueType,
192  /// An OpenType font.
193  OpenType,
194  /// An Embedded OpenType (.eot) font.
195  #[cfg_attr(feature = "serde", serde(rename = "embedded-opentype"))]
196  EmbeddedOpenType,
197  /// OpenType Collection.
198  Collection,
199  /// An SVG font.
200  SVG,
201  /// An unknown format.
202  #[cfg_attr(feature = "serde", serde(borrow))]
203  String(CowArcStr<'i>),
204}
205
206impl<'i> Parse<'i> for FontFormat<'i> {
207  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
208    let s = input.expect_ident_or_string()?;
209    match_ignore_ascii_case! { &s,
210      "woff" => Ok(FontFormat::WOFF),
211      "woff2" => Ok(FontFormat::WOFF2),
212      "truetype" => Ok(FontFormat::TrueType),
213      "opentype" => Ok(FontFormat::OpenType),
214      "embedded-opentype" => Ok(FontFormat::EmbeddedOpenType),
215      "collection" => Ok(FontFormat::Collection),
216      "svg" => Ok(FontFormat::SVG),
217      _ => Ok(FontFormat::String(s.into()))
218    }
219  }
220}
221
222impl<'i> ToCss for FontFormat<'i> {
223  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
224    use FontFormat::*;
225    let s = match self {
226      WOFF => "woff",
227      WOFF2 => "woff2",
228      TrueType => "truetype",
229      OpenType => "opentype",
230      EmbeddedOpenType => "embedded-opentype",
231      Collection => "collection",
232      SVG => "svg",
233      String(s) => &s,
234    };
235    // Browser support for keywords rather than strings is very limited.
236    // https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/src
237    serialize_string(&s, dest)?;
238    Ok(())
239  }
240}
241
242enum_property! {
243  /// A font format keyword in the `format()` function of the the
244  /// [src](https://drafts.csswg.org/css-fonts/#src-desc)
245  /// property of an `@font-face` rule.
246  pub enum FontTechnology {
247    /// A font features tech descriptor in the `tech()`function of the
248    /// [src](https://drafts.csswg.org/css-fonts/#font-features-tech-values)
249    /// property of an `@font-face` rule.
250    /// Supports OpenType Features.
251    /// https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist
252    "features-opentype": FeaturesOpentype,
253    /// Supports Apple Advanced Typography Font Features.
254    /// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html
255    "features-aat": FeaturesAat,
256    /// Supports Graphite Table Format.
257    /// https://scripts.sil.org/cms/scripts/render_download.php?site_id=nrsi&format=file&media_id=GraphiteBinaryFormat_3_0&filename=GraphiteBinaryFormat_3_0.pdf
258    "features-graphite": FeaturesGraphite,
259
260    /// A color font tech descriptor in the `tech()`function of the
261    /// [src](https://drafts.csswg.org/css-fonts/#src-desc)
262    /// property of an `@font-face` rule.
263    /// Supports the `COLR` v0 table.
264    "color-colrv0": ColorCOLRv0,
265    /// Supports the `COLR` v1 table.
266    "color-colrv1": ColorCOLRv1,
267    /// Supports the `SVG` table.
268    "color-svg": ColorSVG,
269    /// Supports the `sbix` table.
270    "color-sbix": ColorSbix,
271    /// Supports the `CBDT` table.
272    "color-cbdt": ColorCBDT,
273
274    /// Supports Variations
275    /// The variations tech refers to the support of font variations
276    "variations": Variations,
277    /// Supports Palettes
278    /// The palettes tech refers to support for font palettes
279    "palettes": Palettes,
280    /// Supports Incremental
281    /// The incremental tech refers to client support for incremental font loading, using either the range-request or the patch-subset method
282    "incremental": Incremental,
283  }
284}
285
286/// A contiguous range of Unicode code points.
287///
288/// Cannot be empty. Can represent a single code point when start == end.
289#[derive(Debug, Clone, PartialEq)]
290#[cfg_attr(feature = "visitor", derive(Visit))]
291#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
292#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
293#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
294pub struct UnicodeRange {
295  /// Inclusive start of the range. In [0, end].
296  pub start: u32,
297  /// Inclusive end of the range. In [0, 0x10FFFF].
298  pub end: u32,
299}
300
301impl<'i> Parse<'i> for UnicodeRange {
302  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
303    let range = cssparser::UnicodeRange::parse(input)?;
304    Ok(UnicodeRange {
305      start: range.start,
306      end: range.end,
307    })
308  }
309}
310
311impl ToCss for UnicodeRange {
312  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
313    // Attempt to optimize the range to use question mark syntax.
314    if self.start != self.end {
315      // Find the first hex digit that differs between the start and end values.
316      let mut shift = 24;
317      let mut mask = 0xf << shift;
318      while shift > 0 {
319        let c1 = self.start & mask;
320        let c2 = self.end & mask;
321        if c1 != c2 {
322          break;
323        }
324
325        mask = mask >> 4;
326        shift -= 4;
327      }
328
329      // Get the remainder of the value. This must be 0x0 to 0xf for the rest
330      // of the value to use the question mark syntax.
331      shift += 4;
332      let remainder_mask = (1 << shift) - 1;
333      let start_remainder = self.start & remainder_mask;
334      let end_remainder = self.end & remainder_mask;
335
336      if start_remainder == 0 && end_remainder == remainder_mask {
337        let start = (self.start & !remainder_mask) >> shift;
338        if start != 0 {
339          write!(dest, "U+{:X}", start)?;
340        } else {
341          dest.write_str("U+")?;
342        }
343
344        while shift > 0 {
345          dest.write_char('?')?;
346          shift -= 4;
347        }
348
349        return Ok(());
350      }
351    }
352
353    write!(dest, "U+{:X}", self.start)?;
354    if self.end != self.start {
355      write!(dest, "-{:X}", self.end)?;
356    }
357    Ok(())
358  }
359}
360
361/// A value for the [font-style](https://w3c.github.io/csswg-drafts/css-fonts/#descdef-font-face-font-style) descriptor in an `@font-face` rule.
362#[derive(Debug, Clone, PartialEq)]
363#[cfg_attr(feature = "visitor", derive(Visit))]
364#[cfg_attr(
365  feature = "serde",
366  derive(serde::Serialize, serde::Deserialize),
367  serde(tag = "type", content = "value", rename_all = "kebab-case")
368)]
369#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
370#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
371pub enum FontStyle {
372  /// Normal font style.
373  Normal,
374  /// Italic font style.
375  Italic,
376  /// Oblique font style, with a custom angle.
377  Oblique(#[cfg_attr(feature = "serde", serde(default = "FontStyle::default_oblique_angle"))] Size2D<Angle>),
378}
379
380impl Default for FontStyle {
381  fn default() -> FontStyle {
382    FontStyle::Normal
383  }
384}
385
386impl FontStyle {
387  #[inline]
388  fn default_oblique_angle() -> Size2D<Angle> {
389    Size2D(
390      FontStyleProperty::default_oblique_angle(),
391      FontStyleProperty::default_oblique_angle(),
392    )
393  }
394}
395
396impl<'i> Parse<'i> for FontStyle {
397  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
398    Ok(match FontStyleProperty::parse(input)? {
399      FontStyleProperty::Normal => FontStyle::Normal,
400      FontStyleProperty::Italic => FontStyle::Italic,
401      FontStyleProperty::Oblique(angle) => {
402        let second_angle = input.try_parse(Angle::parse).unwrap_or_else(|_| angle.clone());
403        FontStyle::Oblique(Size2D(angle, second_angle))
404      }
405    })
406  }
407}
408
409impl ToCss for FontStyle {
410  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
411    match self {
412      FontStyle::Normal => {
413        dest.write_str("normal")?;
414        Ok(())
415      }
416      FontStyle::Italic => {
417        dest.write_str("italic")?;
418        Ok(())
419      }
420      FontStyle::Oblique(angle) => {
421        dest.write_str("oblique")?;
422        if *angle != FontStyle::default_oblique_angle() {
423          dest.write_char(' ')?;
424          angle.to_css(dest)?;
425        }
426        Ok(())
427      }
428    }
429  }
430}
431
432pub(crate) struct FontFaceDeclarationParser;
433
434/// Parse a declaration within {} block: `color: blue`
435impl<'i> cssparser::DeclarationParser<'i> for FontFaceDeclarationParser {
436  type Declaration = FontFaceProperty<'i>;
437  type Error = ParserError<'i>;
438
439  fn parse_value<'t>(
440    &mut self,
441    name: CowRcStr<'i>,
442    input: &mut cssparser::Parser<'i, 't>,
443    _declaration_start: &ParserState,
444  ) -> Result<Self::Declaration, cssparser::ParseError<'i, Self::Error>> {
445    macro_rules! property {
446      ($property: ident, $type: ty) => {
447        if let Ok(c) = <$type>::parse(input) {
448          if input.expect_exhausted().is_ok() {
449            return Ok(FontFaceProperty::$property(c));
450          }
451        }
452      };
453    }
454
455    let state = input.state();
456    match_ignore_ascii_case! { &name,
457      "src" => {
458        if let Ok(sources) = input.parse_comma_separated(Source::parse) {
459          return Ok(FontFaceProperty::Source(sources))
460        }
461      },
462      "font-family" => property!(FontFamily, FontFamily),
463      "font-weight" => property!(FontWeight, Size2D<FontWeight>),
464      "font-style" => property!(FontStyle, FontStyle),
465      "font-stretch" => property!(FontStretch, Size2D<FontStretch>),
466      "unicode-range" => property!(UnicodeRange, Vec<UnicodeRange>),
467      _ => {}
468    }
469
470    input.reset(&state);
471    return Ok(FontFaceProperty::Custom(CustomProperty::parse(
472      name.into(),
473      input,
474      &ParserOptions::default(),
475    )?));
476  }
477}
478
479/// Default methods reject all at rules.
480impl<'i> AtRuleParser<'i> for FontFaceDeclarationParser {
481  type Prelude = ();
482  type AtRule = FontFaceProperty<'i>;
483  type Error = ParserError<'i>;
484}
485
486impl<'i> QualifiedRuleParser<'i> for FontFaceDeclarationParser {
487  type Prelude = ();
488  type QualifiedRule = FontFaceProperty<'i>;
489  type Error = ParserError<'i>;
490}
491
492impl<'i> RuleBodyItemParser<'i, FontFaceProperty<'i>, ParserError<'i>> for FontFaceDeclarationParser {
493  fn parse_qualified(&self) -> bool {
494    false
495  }
496
497  fn parse_declarations(&self) -> bool {
498    true
499  }
500}
501
502impl<'i> ToCss for FontFaceRule<'i> {
503  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
504    dest.add_mapping(self.loc);
505    dest.write_str("@font-face")?;
506    dest.whitespace()?;
507    dest.write_char('{')?;
508    dest.indent();
509    let len = self.properties.len();
510    for (i, prop) in self.properties.iter().enumerate() {
511      dest.newline()?;
512      prop.to_css(dest)?;
513      if i != len - 1 || !dest.options().minify {
514        dest.write_char(';')?;
515      }
516    }
517    dest.dedent();
518    dest.newline()?;
519    dest.write_char('}')?;
520    Ok(())
521  }
522}
523
524impl<'i> ToCss for FontFaceProperty<'i> {
525  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
526    use FontFaceProperty::*;
527    macro_rules! property {
528      ($prop: literal, $value: expr) => {{
529        dest.write_str($prop)?;
530        dest.delim(':', false)?;
531        $value.to_css(dest)
532      }};
533      ($prop: literal, $value: expr, $multi: expr) => {{
534        dest.write_str($prop)?;
535        dest.delim(':', false)?;
536        let len = $value.len();
537        for (idx, val) in $value.iter().enumerate() {
538          val.to_css(dest)?;
539          if idx < len - 1 {
540            dest.delim(',', false)?;
541          }
542        }
543        Ok(())
544      }};
545    }
546
547    match self {
548      Source(value) => property!("src", value, true),
549      FontFamily(value) => property!("font-family", value),
550      FontStyle(value) => property!("font-style", value),
551      FontWeight(value) => property!("font-weight", value),
552      FontStretch(value) => property!("font-stretch", value),
553      UnicodeRange(value) => property!("unicode-range", value),
554      Custom(custom) => {
555        dest.write_str(custom.name.as_ref())?;
556        dest.delim(':', false)?;
557        custom.value.to_css(dest, true)
558      }
559    }
560  }
561}