Skip to main content

rspack_lightningcss/properties/
font.rs

1//! CSS properties related to fonts.
2
3use std::collections::HashSet;
4
5use super::{Property, PropertyId};
6use crate::compat::Feature;
7use crate::context::PropertyHandlerContext;
8use crate::declaration::{DeclarationBlock, DeclarationList};
9use crate::error::{ParserError, PrinterError};
10use crate::macros::*;
11use crate::targets::should_compile;
12use crate::traits::{IsCompatible, Parse, PropertyHandler, Shorthand, ToCss};
13use crate::values::length::LengthValue;
14use crate::values::number::{CSSNumber, NonNegative};
15use crate::values::string::CowArcStr;
16use crate::values::{angle::Angle, length::LengthPercentage, percentage::Percentage};
17#[cfg(feature = "visitor")]
18use crate::visitor::Visit;
19use cssparser::*;
20
21/// A value for the [font-weight](https://www.w3.org/TR/css-fonts-4/#font-weight-prop) property.
22#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
23#[cfg_attr(feature = "visitor", derive(Visit))]
24#[cfg_attr(
25  feature = "serde",
26  derive(serde::Serialize, serde::Deserialize),
27  serde(tag = "type", content = "value", rename_all = "kebab-case")
28)]
29#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
30#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
31pub enum FontWeight {
32  /// An absolute font weight.
33  Absolute(AbsoluteFontWeight),
34  /// The `bolder` keyword.
35  Bolder,
36  /// The `lighter` keyword.
37  Lighter,
38}
39
40impl Default for FontWeight {
41  fn default() -> FontWeight {
42    FontWeight::Absolute(AbsoluteFontWeight::default())
43  }
44}
45
46impl IsCompatible for FontWeight {
47  fn is_compatible(&self, browsers: crate::targets::Browsers) -> bool {
48    match self {
49      FontWeight::Absolute(a) => a.is_compatible(browsers),
50      FontWeight::Bolder | FontWeight::Lighter => true,
51    }
52  }
53}
54
55/// An [absolute font weight](https://www.w3.org/TR/css-fonts-4/#font-weight-absolute-values),
56/// as used in the `font-weight` property.
57///
58/// See [FontWeight](FontWeight).
59#[derive(Debug, Clone, PartialEq, Parse)]
60#[cfg_attr(feature = "visitor", derive(Visit))]
61#[cfg_attr(
62  feature = "serde",
63  derive(serde::Serialize, serde::Deserialize),
64  serde(tag = "type", content = "value", rename_all = "kebab-case")
65)]
66#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
67pub enum AbsoluteFontWeight {
68  /// An explicit weight.
69  Weight(CSSNumber),
70  /// Same as `400`.
71  Normal,
72  /// Same as `700`.
73  Bold,
74}
75
76impl Default for AbsoluteFontWeight {
77  fn default() -> AbsoluteFontWeight {
78    AbsoluteFontWeight::Normal
79  }
80}
81
82impl ToCss for AbsoluteFontWeight {
83  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
84    use AbsoluteFontWeight::*;
85    match self {
86      Weight(val) => val.to_css(dest)?,
87      Normal => dest.write_str(if dest.options().minify { "400" } else { "normal" })?,
88      Bold => dest.write_str(if dest.options().minify { "700" } else { "bold" })?,
89    };
90    Ok(())
91  }
92}
93
94impl IsCompatible for AbsoluteFontWeight {
95  fn is_compatible(&self, browsers: crate::targets::Browsers) -> bool {
96    match self {
97      // Older browsers only supported 100, 200, 300, ...900 rather than arbitrary values.
98      AbsoluteFontWeight::Weight(val) if !(*val >= 100.0 && *val <= 900.0 && *val % 100.0 == 0.0) => {
99        Feature::FontWeightNumber.is_compatible(browsers)
100      }
101      _ => true,
102    }
103  }
104}
105
106enum_property! {
107  /// An [absolute font size](https://www.w3.org/TR/css-fonts-3/#absolute-size-value),
108  /// as used in the `font-size` property.
109  ///
110  /// See [FontSize](FontSize).
111  #[allow(missing_docs)]
112  pub enum AbsoluteFontSize {
113    "xx-small": XXSmall,
114    "x-small": XSmall,
115    "small": Small,
116    "medium": Medium,
117    "large": Large,
118    "x-large": XLarge,
119    "xx-large": XXLarge,
120    "xxx-large": XXXLarge,
121  }
122}
123
124impl IsCompatible for AbsoluteFontSize {
125  fn is_compatible(&self, browsers: crate::targets::Browsers) -> bool {
126    use AbsoluteFontSize::*;
127    match self {
128      XXXLarge => Feature::FontSizeXXXLarge.is_compatible(browsers),
129      _ => true,
130    }
131  }
132}
133
134enum_property! {
135  /// A [relative font size](https://www.w3.org/TR/css-fonts-3/#relative-size-value),
136  /// as used in the `font-size` property.
137  ///
138  /// See [FontSize](FontSize).
139  #[allow(missing_docs)]
140  pub enum RelativeFontSize {
141    Smaller,
142    Larger,
143  }
144}
145
146/// A value for the [font-size](https://www.w3.org/TR/css-fonts-4/#font-size-prop) property.
147#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
148#[cfg_attr(feature = "visitor", derive(Visit))]
149#[cfg_attr(
150  feature = "serde",
151  derive(serde::Serialize, serde::Deserialize),
152  serde(tag = "type", content = "value", rename_all = "kebab-case")
153)]
154#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
155#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
156pub enum FontSize {
157  /// An explicit size.
158  Length(NonNegative<LengthPercentage>),
159  /// An absolute font size keyword.
160  Absolute(AbsoluteFontSize),
161  /// A relative font size keyword.
162  Relative(RelativeFontSize),
163}
164
165impl IsCompatible for FontSize {
166  fn is_compatible(&self, browsers: crate::targets::Browsers) -> bool {
167    match self {
168      FontSize::Length(NonNegative(LengthPercentage::Dimension(LengthValue::Rem(..)))) => {
169        Feature::FontSizeRem.is_compatible(browsers)
170      }
171      FontSize::Length(l) => l.is_compatible(browsers),
172      FontSize::Absolute(a) => a.is_compatible(browsers),
173      FontSize::Relative(..) => true,
174    }
175  }
176}
177
178enum_property! {
179  /// A [font stretch keyword](https://www.w3.org/TR/css-fonts-4/#font-stretch-prop),
180  /// as used in the `font-stretch` property.
181  ///
182  /// See [FontStretch](FontStretch).
183  pub enum FontStretchKeyword {
184    /// 100%
185    "normal": Normal,
186    /// 50%
187    "ultra-condensed": UltraCondensed,
188    /// 62.5%
189    "extra-condensed": ExtraCondensed,
190    /// 75%
191    "condensed": Condensed,
192    /// 87.5%
193    "semi-condensed": SemiCondensed,
194    /// 112.5%
195    "semi-expanded": SemiExpanded,
196    /// 125%
197    "expanded": Expanded,
198    /// 150%
199    "extra-expanded": ExtraExpanded,
200    /// 200%
201    "ultra-expanded": UltraExpanded,
202  }
203}
204
205impl Default for FontStretchKeyword {
206  fn default() -> FontStretchKeyword {
207    FontStretchKeyword::Normal
208  }
209}
210
211impl Into<Percentage> for &FontStretchKeyword {
212  fn into(self) -> Percentage {
213    use FontStretchKeyword::*;
214    let val = match self {
215      UltraCondensed => 0.5,
216      ExtraCondensed => 0.625,
217      Condensed => 0.75,
218      SemiCondensed => 0.875,
219      Normal => 1.0,
220      SemiExpanded => 1.125,
221      Expanded => 1.25,
222      ExtraExpanded => 1.5,
223      UltraExpanded => 2.0,
224    };
225    Percentage(val)
226  }
227}
228
229/// A value for the [font-stretch](https://www.w3.org/TR/css-fonts-4/#font-stretch-prop) property.
230#[derive(Debug, Clone, PartialEq, Parse)]
231#[cfg_attr(feature = "visitor", derive(Visit))]
232#[cfg_attr(
233  feature = "serde",
234  derive(serde::Serialize, serde::Deserialize),
235  serde(tag = "type", content = "value", rename_all = "kebab-case")
236)]
237#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
238#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
239pub enum FontStretch {
240  /// A font stretch keyword.
241  Keyword(FontStretchKeyword),
242  /// A percentage.
243  Percentage(NonNegative<Percentage>),
244}
245
246impl Default for FontStretch {
247  fn default() -> FontStretch {
248    FontStretch::Keyword(FontStretchKeyword::default())
249  }
250}
251
252impl Into<Percentage> for &FontStretch {
253  fn into(self) -> Percentage {
254    match self {
255      FontStretch::Percentage(val) => val.0.clone(),
256      FontStretch::Keyword(keyword) => keyword.into(),
257    }
258  }
259}
260
261impl ToCss for FontStretch {
262  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
263    if dest.options().minify {
264      let percentage: Percentage = self.into();
265      return percentage.to_css(dest);
266    }
267
268    match self {
269      FontStretch::Percentage(val) => val.to_css(dest),
270      FontStretch::Keyword(val) => val.to_css(dest),
271    }
272  }
273}
274
275impl IsCompatible for FontStretch {
276  fn is_compatible(&self, browsers: crate::targets::Browsers) -> bool {
277    match self {
278      FontStretch::Percentage(..) => Feature::FontStretchPercentage.is_compatible(browsers),
279      FontStretch::Keyword(..) => true,
280    }
281  }
282}
283
284enum_property! {
285  /// A [generic font family](https://www.w3.org/TR/css-fonts-4/#generic-font-families) name,
286  /// as used in the `font-family` property.
287  ///
288  /// See [FontFamily](FontFamily).
289  #[allow(missing_docs)]
290  #[derive(Eq, Hash)]
291  pub enum GenericFontFamily {
292    "serif": Serif,
293    "sans-serif": SansSerif,
294    "cursive": Cursive,
295    "fantasy": Fantasy,
296    "monospace": Monospace,
297    "system-ui": SystemUI,
298    "emoji": Emoji,
299    "math": Math,
300    "fangsong": FangSong,
301    "ui-serif": UISerif,
302    "ui-sans-serif": UISansSerif,
303    "ui-monospace": UIMonospace,
304    "ui-rounded": UIRounded,
305
306    // CSS wide keywords. These must be parsed as identifiers so they
307    // don't get serialized as strings.
308    // https://www.w3.org/TR/css-values-4/#common-keywords
309    "initial": Initial,
310    "inherit": Inherit,
311    "unset": Unset,
312    // Default is also reserved by the <custom-ident> type.
313    // https://www.w3.org/TR/css-values-4/#custom-idents
314    "default": Default,
315
316    // CSS defaulting keywords
317    // https://drafts.csswg.org/css-cascade-5/#defaulting-keywords
318    "revert": Revert,
319    "revert-layer": RevertLayer,
320  }
321}
322
323impl IsCompatible for GenericFontFamily {
324  fn is_compatible(&self, browsers: crate::targets::Browsers) -> bool {
325    use GenericFontFamily::*;
326    match self {
327      SystemUI => Feature::FontFamilySystemUi.is_compatible(browsers),
328      UISerif | UISansSerif | UIMonospace | UIRounded => Feature::ExtendedSystemFonts.is_compatible(browsers),
329      _ => true,
330    }
331  }
332}
333
334/// A value for the [font-family](https://www.w3.org/TR/css-fonts-4/#font-family-prop) property.
335#[derive(Debug, Clone, PartialEq, Eq, Hash)]
336#[cfg_attr(feature = "visitor", derive(Visit))]
337#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
338#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(untagged))]
339#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
340pub enum FontFamily<'i> {
341  /// A generic family name.
342  Generic(GenericFontFamily),
343  /// A custom family name.
344  #[cfg_attr(feature = "serde", serde(borrow))]
345  FamilyName(FamilyName<'i>),
346}
347
348impl<'i> Parse<'i> for FontFamily<'i> {
349  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
350    if let Ok(value) = input.try_parse(GenericFontFamily::parse) {
351      return Ok(FontFamily::Generic(value));
352    }
353
354    let family = FamilyName::parse(input)?;
355    Ok(FontFamily::FamilyName(family))
356  }
357}
358
359impl<'i> ToCss for FontFamily<'i> {
360  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
361    match self {
362      FontFamily::Generic(val) => val.to_css(dest),
363      FontFamily::FamilyName(val) => val.to_css(dest),
364    }
365  }
366}
367
368/// A font [family name](https://drafts.csswg.org/css-fonts/#family-name-syntax).
369#[derive(Debug, Clone, PartialEq, Eq, Hash)]
370#[cfg_attr(feature = "visitor", derive(Visit))]
371#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
372#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(transparent))]
373#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
374pub struct FamilyName<'i>(#[cfg_attr(feature = "serde", serde(borrow))] CowArcStr<'i>);
375
376impl<'i> Parse<'i> for FamilyName<'i> {
377  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
378    if let Ok(value) = input.try_parse(|i| i.expect_string_cloned()) {
379      return Ok(FamilyName(value.into()));
380    }
381
382    let value: CowArcStr<'i> = input.expect_ident()?.into();
383    let mut string = None;
384    while let Ok(ident) = input.try_parse(|i| i.expect_ident_cloned()) {
385      if string.is_none() {
386        string = Some(value.to_string());
387      }
388
389      if let Some(string) = &mut string {
390        string.push(' ');
391        string.push_str(&ident);
392      }
393    }
394
395    let value = if let Some(string) = string {
396      string.into()
397    } else {
398      value
399    };
400
401    Ok(FamilyName(value))
402  }
403}
404
405impl<'i> ToCss for FamilyName<'i> {
406  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
407    // Generic family names such as sans-serif must be quoted if parsed as a string.
408    // CSS wide keywords, as well as "default", must also be quoted.
409    // https://www.w3.org/TR/css-fonts-4/#family-name-syntax
410    let val = &self.0;
411    if !val.is_empty() && !GenericFontFamily::parse_string(val).is_ok() {
412      // Family names with two or more consecutive spaces must be quoted to preserve the spaces.
413      let needs_quotes = val.contains("  ");
414      if needs_quotes {
415        serialize_string(&val, dest)?;
416        return Ok(());
417      }
418
419      let mut id = String::new();
420      let mut first = true;
421      for slice in val.split(' ') {
422        if first {
423          first = false;
424        } else {
425          id.push(' ');
426        }
427        serialize_identifier(slice, &mut id)?;
428      }
429      if id.len() < val.len() + 2 {
430        dest.write_str(&id)?;
431        return Ok(());
432      }
433    }
434    serialize_string(&val, dest)?;
435    Ok(())
436  }
437}
438
439impl IsCompatible for FontFamily<'_> {
440  fn is_compatible(&self, browsers: crate::targets::Browsers) -> bool {
441    match self {
442      FontFamily::Generic(g) => g.is_compatible(browsers),
443      FontFamily::FamilyName(..) => true,
444    }
445  }
446}
447
448/// A value for the [font-style](https://www.w3.org/TR/css-fonts-4/#font-style-prop) property.
449#[derive(Debug, Clone, PartialEq)]
450#[cfg_attr(feature = "visitor", derive(Visit))]
451#[cfg_attr(
452  feature = "serde",
453  derive(serde::Serialize, serde::Deserialize),
454  serde(tag = "type", content = "value", rename_all = "kebab-case")
455)]
456#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
457#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
458pub enum FontStyle {
459  /// Normal font style.
460  Normal,
461  /// Italic font style.
462  Italic,
463  /// Oblique font style, with a custom angle.
464  Oblique(#[cfg_attr(feature = "serde", serde(default = "FontStyle::default_oblique_angle"))] Angle),
465}
466
467impl Default for FontStyle {
468  fn default() -> FontStyle {
469    FontStyle::Normal
470  }
471}
472
473impl FontStyle {
474  #[inline]
475  pub(crate) fn default_oblique_angle() -> Angle {
476    Angle::Deg(14.0)
477  }
478}
479
480impl<'i> Parse<'i> for FontStyle {
481  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
482    let location = input.current_source_location();
483    let ident = input.expect_ident()?;
484    match_ignore_ascii_case! { &*ident,
485      "normal" => Ok(FontStyle::Normal),
486      "italic" => Ok(FontStyle::Italic),
487      "oblique" => {
488        let angle = input.try_parse(Angle::parse).unwrap_or(FontStyle::default_oblique_angle());
489        Ok(FontStyle::Oblique(angle))
490      },
491      _ => Err(location.new_unexpected_token_error(
492        cssparser::Token::Ident(ident.clone())
493      ))
494    }
495  }
496}
497
498impl ToCss for FontStyle {
499  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
500    match self {
501      FontStyle::Normal => dest.write_str("normal")?,
502      FontStyle::Italic => dest.write_str("italic")?,
503      FontStyle::Oblique(angle) => {
504        dest.write_str("oblique")?;
505        if *angle != FontStyle::default_oblique_angle() {
506          dest.write_char(' ')?;
507          angle.to_css(dest)?;
508        }
509      }
510    };
511    Ok(())
512  }
513}
514
515impl IsCompatible for FontStyle {
516  fn is_compatible(&self, browsers: crate::targets::Browsers) -> bool {
517    match self {
518      FontStyle::Oblique(angle) if *angle != FontStyle::default_oblique_angle() => {
519        Feature::FontStyleObliqueAngle.is_compatible(browsers)
520      }
521      FontStyle::Normal | FontStyle::Italic | FontStyle::Oblique(..) => true,
522    }
523  }
524}
525
526enum_property! {
527  /// A value for the [font-variant-caps](https://www.w3.org/TR/css-fonts-4/#font-variant-caps-prop) property.
528  pub enum FontVariantCaps {
529    /// No special capitalization features are applied.
530    Normal,
531    /// The small capitals feature is used for lower case letters.
532    SmallCaps,
533    /// Small capitals are used for both upper and lower case letters.
534    AllSmallCaps,
535    /// Petite capitals are used.
536    PetiteCaps,
537    /// Petite capitals are used for both upper and lower case letters.
538    AllPetiteCaps,
539    /// Enables display of mixture of small capitals for uppercase letters with normal lowercase letters.
540    Unicase,
541    /// Uses titling capitals.
542    TitlingCaps,
543  }
544}
545
546impl Default for FontVariantCaps {
547  fn default() -> FontVariantCaps {
548    FontVariantCaps::Normal
549  }
550}
551
552impl FontVariantCaps {
553  fn is_css2(&self) -> bool {
554    matches!(self, FontVariantCaps::Normal | FontVariantCaps::SmallCaps)
555  }
556
557  fn parse_css2<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
558    let value = Self::parse(input)?;
559    if !value.is_css2() {
560      return Err(input.new_custom_error(ParserError::InvalidValue));
561    }
562    Ok(value)
563  }
564}
565
566impl IsCompatible for FontVariantCaps {
567  fn is_compatible(&self, _browsers: crate::targets::Browsers) -> bool {
568    true
569  }
570}
571
572/// A value for the [line-height](https://www.w3.org/TR/2020/WD-css-inline-3-20200827/#propdef-line-height) property.
573#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
574#[cfg_attr(feature = "visitor", derive(Visit))]
575#[cfg_attr(
576  feature = "serde",
577  derive(serde::Serialize, serde::Deserialize),
578  serde(tag = "type", content = "value", rename_all = "kebab-case")
579)]
580#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
581#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
582pub enum LineHeight {
583  /// The UA sets the line height based on the font.
584  Normal,
585  /// A multiple of the element's font size.
586  Number(NonNegative<CSSNumber>),
587  /// An explicit height.
588  Length(NonNegative<LengthPercentage>),
589}
590
591impl Default for LineHeight {
592  fn default() -> LineHeight {
593    LineHeight::Normal
594  }
595}
596
597impl IsCompatible for LineHeight {
598  fn is_compatible(&self, browsers: crate::targets::Browsers) -> bool {
599    match self {
600      LineHeight::Length(l) => l.is_compatible(browsers),
601      LineHeight::Normal | LineHeight::Number(..) => true,
602    }
603  }
604}
605
606enum_property! {
607  /// A keyword for the [vertical align](https://drafts.csswg.org/css2/#propdef-vertical-align) property.
608  pub enum VerticalAlignKeyword {
609    /// Align the baseline of the box with the baseline of the parent box.
610    Baseline,
611    /// Lower the baseline of the box to the proper position for subscripts of the parent’s box.
612    Sub,
613    /// Raise the baseline of the box to the proper position for superscripts of the parent’s box.
614    Super,
615    /// Align the top of the aligned subtree with the top of the line box.
616    Top,
617    /// Align the top of the box with the top of the parent’s content area.
618    TextTop,
619    /// Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.
620    Middle,
621    /// Align the bottom of the aligned subtree with the bottom of the line box.
622    Bottom,
623    /// Align the bottom of the box with the bottom of the parent’s content area.
624    TextBottom,
625  }
626}
627
628/// A value for the [vertical align](https://drafts.csswg.org/css2/#propdef-vertical-align) property.
629// TODO: there is a more extensive spec in CSS3 but it doesn't seem any browser implements it? https://www.w3.org/TR/css-inline-3/#transverse-alignment
630#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
631#[cfg_attr(feature = "visitor", derive(Visit))]
632#[cfg_attr(
633  feature = "serde",
634  derive(serde::Serialize, serde::Deserialize),
635  serde(tag = "type", content = "value", rename_all = "kebab-case")
636)]
637#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
638#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
639pub enum VerticalAlign {
640  /// A vertical align keyword.
641  Keyword(VerticalAlignKeyword),
642  /// An explicit length.
643  Length(LengthPercentage),
644}
645
646define_shorthand! {
647  /// A value for the [font](https://www.w3.org/TR/css-fonts-4/#font-prop) shorthand property.
648  pub struct Font<'i> {
649    /// The font family.
650    #[cfg_attr(feature = "serde", serde(borrow))]
651    family: FontFamily(Vec<FontFamily<'i>>),
652    /// The font size.
653    size: FontSize(FontSize),
654    /// The font style.
655    style: FontStyle(FontStyle),
656    /// The font weight.
657    weight: FontWeight(FontWeight),
658    /// The font stretch.
659    stretch: FontStretch(FontStretch),
660    /// The line height.
661    line_height: LineHeight(LineHeight),
662    /// How the text should be capitalized. Only CSS 2.1 values are supported.
663    variant_caps: FontVariantCaps(FontVariantCaps),
664  }
665}
666
667impl<'i> Parse<'i> for Font<'i> {
668  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
669    let mut style = None;
670    let mut weight = None;
671    let mut stretch = None;
672    let size;
673    let mut variant_caps = None;
674    let mut count = 0;
675
676    loop {
677      // Skip "normal" since it is valid for several properties, but we don't know which ones it will be used for yet.
678      if input.try_parse(|input| input.expect_ident_matching("normal")).is_ok() {
679        count += 1;
680        continue;
681      }
682      if style.is_none() {
683        if let Ok(value) = input.try_parse(FontStyle::parse) {
684          style = Some(value);
685          count += 1;
686          continue;
687        }
688      }
689      if weight.is_none() {
690        if let Ok(value) = input.try_parse(FontWeight::parse) {
691          weight = Some(value);
692          count += 1;
693          continue;
694        }
695      }
696      if variant_caps.is_none() {
697        if let Ok(value) = input.try_parse(FontVariantCaps::parse_css2) {
698          variant_caps = Some(value);
699          count += 1;
700          continue;
701        }
702      }
703
704      if stretch.is_none() {
705        if let Ok(value) = input.try_parse(FontStretchKeyword::parse) {
706          stretch = Some(FontStretch::Keyword(value));
707          count += 1;
708          continue;
709        }
710      }
711      size = Some(FontSize::parse(input)?);
712      break;
713    }
714
715    if count > 4 {
716      return Err(input.new_custom_error(ParserError::InvalidDeclaration));
717    }
718
719    let size = match size {
720      Some(s) => s,
721      None => return Err(input.new_custom_error(ParserError::InvalidDeclaration)),
722    };
723
724    let line_height = if input.try_parse(|input| input.expect_delim('/')).is_ok() {
725      Some(LineHeight::parse(input)?)
726    } else {
727      None
728    };
729
730    let family = input.parse_comma_separated(FontFamily::parse)?;
731    Ok(Font {
732      family,
733      size,
734      style: style.unwrap_or_default(),
735      weight: weight.unwrap_or_default(),
736      stretch: stretch.unwrap_or_default(),
737      line_height: line_height.unwrap_or_default(),
738      variant_caps: variant_caps.unwrap_or_default(),
739    })
740  }
741}
742
743impl<'i> ToCss for Font<'i> {
744  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
745    if self.style != FontStyle::default() {
746      self.style.to_css(dest)?;
747      dest.write_char(' ')?;
748    }
749
750    if self.variant_caps != FontVariantCaps::default() {
751      self.variant_caps.to_css(dest)?;
752      dest.write_char(' ')?;
753    }
754
755    if self.weight != FontWeight::default() {
756      self.weight.to_css(dest)?;
757      dest.write_char(' ')?;
758    }
759
760    if self.stretch != FontStretch::default() {
761      self.stretch.to_css(dest)?;
762      dest.write_char(' ')?;
763    }
764
765    self.size.to_css(dest)?;
766
767    if self.line_height != LineHeight::default() {
768      dest.delim('/', true)?;
769      self.line_height.to_css(dest)?;
770    }
771
772    dest.write_char(' ')?;
773
774    let len = self.family.len();
775    for (idx, val) in self.family.iter().enumerate() {
776      val.to_css(dest)?;
777      if idx < len - 1 {
778        dest.delim(',', false)?;
779      }
780    }
781
782    Ok(())
783  }
784}
785
786property_bitflags! {
787  #[derive(Default, Debug)]
788  struct FontProperty: u8 {
789    const FontFamily = 1 << 0;
790    const FontSize = 1 << 1;
791    const FontStyle = 1 << 2;
792    const FontWeight = 1 << 3;
793    const FontStretch = 1 << 4;
794    const LineHeight = 1 << 5;
795    const FontVariantCaps = 1 << 6;
796    const Font = Self::FontFamily.bits() | Self::FontSize.bits() | Self::FontStyle.bits() | Self::FontWeight.bits() | Self::FontStretch.bits() | Self::LineHeight.bits() | Self::FontVariantCaps.bits();
797  }
798}
799
800#[derive(Default, Debug)]
801pub(crate) struct FontHandler<'i> {
802  family: Option<Vec<FontFamily<'i>>>,
803  size: Option<FontSize>,
804  style: Option<FontStyle>,
805  weight: Option<FontWeight>,
806  stretch: Option<FontStretch>,
807  line_height: Option<LineHeight>,
808  variant_caps: Option<FontVariantCaps>,
809  flushed_properties: FontProperty,
810  has_any: bool,
811}
812
813impl<'i> PropertyHandler<'i> for FontHandler<'i> {
814  fn handle_property(
815    &mut self,
816    property: &Property<'i>,
817    dest: &mut DeclarationList<'i>,
818    context: &mut PropertyHandlerContext<'i, '_>,
819  ) -> bool {
820    use Property::*;
821
822    macro_rules! flush {
823      ($prop: ident, $val: expr) => {{
824        if self.$prop.is_some() && self.$prop.as_ref().unwrap() != $val && matches!(context.targets.browsers, Some(targets) if !$val.is_compatible(targets)) {
825          self.flush(dest, context);
826        }
827      }};
828    }
829
830    macro_rules! property {
831      ($prop: ident, $val: ident) => {{
832        flush!($prop, $val);
833        self.$prop = Some($val.clone());
834        self.has_any = true;
835      }};
836    }
837
838    match property {
839      FontFamily(val) => property!(family, val),
840      FontSize(val) => property!(size, val),
841      FontStyle(val) => property!(style, val),
842      FontWeight(val) => property!(weight, val),
843      FontStretch(val) => property!(stretch, val),
844      FontVariantCaps(val) => property!(variant_caps, val),
845      LineHeight(val) => property!(line_height, val),
846      Font(val) => {
847        flush!(family, &val.family);
848        flush!(size, &val.size);
849        flush!(style, &val.style);
850        flush!(weight, &val.weight);
851        flush!(stretch, &val.stretch);
852        flush!(line_height, &val.line_height);
853        flush!(variant_caps, &val.variant_caps);
854        self.family = Some(val.family.clone());
855        self.size = Some(val.size.clone());
856        self.style = Some(val.style.clone());
857        self.weight = Some(val.weight.clone());
858        self.stretch = Some(val.stretch.clone());
859        self.line_height = Some(val.line_height.clone());
860        self.variant_caps = Some(val.variant_caps.clone());
861        self.has_any = true;
862        // TODO: reset other properties
863      }
864      Unparsed(val) if is_font_property(&val.property_id) => {
865        self.flush(dest, context);
866        self
867          .flushed_properties
868          .insert(FontProperty::try_from(&val.property_id).unwrap());
869        dest.push(property.clone());
870      }
871      _ => return false,
872    }
873
874    true
875  }
876
877  fn finalize(&mut self, decls: &mut DeclarationList<'i>, context: &mut PropertyHandlerContext<'i, '_>) {
878    self.flush(decls, context);
879    self.flushed_properties = FontProperty::empty();
880  }
881}
882
883impl<'i> FontHandler<'i> {
884  fn flush(&mut self, decls: &mut DeclarationList<'i>, context: &mut PropertyHandlerContext<'i, '_>) {
885    if !self.has_any {
886      return;
887    }
888
889    self.has_any = false;
890
891    macro_rules! push {
892      ($prop: ident, $val: expr) => {
893        decls.push(Property::$prop($val));
894        self.flushed_properties.insert(FontProperty::$prop);
895      };
896    }
897
898    let mut family = std::mem::take(&mut self.family);
899    if !self.flushed_properties.contains(FontProperty::FontFamily) {
900      family = compatible_font_family(family, !should_compile!(context.targets, FontFamilySystemUi));
901    }
902    let size = std::mem::take(&mut self.size);
903    let style = std::mem::take(&mut self.style);
904    let weight = std::mem::take(&mut self.weight);
905    let stretch = std::mem::take(&mut self.stretch);
906    let line_height = std::mem::take(&mut self.line_height);
907    let variant_caps = std::mem::take(&mut self.variant_caps);
908
909    if let Some(family) = &mut family {
910      if family.len() > 1 {
911        // Dedupe.
912        let mut seen = HashSet::new();
913        family.retain(|f| seen.insert(f.clone()));
914      }
915    }
916
917    if family.is_some()
918      && size.is_some()
919      && style.is_some()
920      && weight.is_some()
921      && stretch.is_some()
922      && line_height.is_some()
923      && variant_caps.is_some()
924    {
925      let caps = variant_caps.unwrap();
926      push!(
927        Font,
928        Font {
929          family: family.unwrap(),
930          size: size.unwrap(),
931          style: style.unwrap(),
932          weight: weight.unwrap(),
933          stretch: stretch.unwrap(),
934          line_height: line_height.unwrap(),
935          variant_caps: if caps.is_css2() {
936            caps
937          } else {
938            FontVariantCaps::default()
939          },
940        }
941      );
942
943      // The `font` property only accepts CSS 2.1 values for font-variant caps.
944      // If we have a CSS 3+ value, we need to add a separate property.
945      if !caps.is_css2() {
946        push!(FontVariantCaps, variant_caps.unwrap());
947      }
948    } else {
949      if let Some(val) = family {
950        push!(FontFamily, val);
951      }
952
953      if let Some(val) = size {
954        push!(FontSize, val);
955      }
956
957      if let Some(val) = style {
958        push!(FontStyle, val);
959      }
960
961      if let Some(val) = variant_caps {
962        push!(FontVariantCaps, val);
963      }
964
965      if let Some(val) = weight {
966        push!(FontWeight, val);
967      }
968
969      if let Some(val) = stretch {
970        push!(FontStretch, val);
971      }
972
973      if let Some(val) = line_height {
974        push!(LineHeight, val);
975      }
976    }
977  }
978}
979
980const SYSTEM_UI: FontFamily = FontFamily::Generic(GenericFontFamily::SystemUI);
981
982const DEFAULT_SYSTEM_FONTS: &[&str] = &[
983  // #1: Supported as the '-apple-system' value (macOS, Safari >= 9.2 < 11, Firefox >= 43)
984  "-apple-system",
985  // #2: Supported as the 'BlinkMacSystemFont' value (macOS, Chrome < 56)
986  "BlinkMacSystemFont",
987  "Segoe UI",  // Windows >= Vista
988  "Roboto",    // Android >= 4
989  "Noto Sans", // Plasma >= 5.5
990  "Ubuntu",    // Ubuntu >= 10.10
991  "Cantarell", // GNOME >= 3
992  "Helvetica Neue",
993];
994
995/// [`system-ui`](https://www.w3.org/TR/css-fonts-4/#system-ui-def) is a special generic font family
996/// It is platform dependent but if not supported by the target will simply be ignored
997/// This list is an attempt at providing that support
998#[inline]
999fn compatible_font_family(mut family: Option<Vec<FontFamily>>, is_supported: bool) -> Option<Vec<FontFamily>> {
1000  if is_supported {
1001    return family;
1002  }
1003
1004  if let Some(families) = &mut family {
1005    if let Some(position) = families.iter().position(|v| *v == SYSTEM_UI) {
1006      families.splice(
1007        (position + 1)..(position + 1),
1008        DEFAULT_SYSTEM_FONTS
1009          .iter()
1010          .map(|name| FontFamily::FamilyName(FamilyName(CowArcStr::from(*name)))),
1011      );
1012    }
1013  }
1014
1015  return family;
1016}
1017
1018#[inline]
1019fn is_font_property(property_id: &PropertyId) -> bool {
1020  match property_id {
1021    PropertyId::FontFamily
1022    | PropertyId::FontSize
1023    | PropertyId::FontStyle
1024    | PropertyId::FontWeight
1025    | PropertyId::FontStretch
1026    | PropertyId::FontVariantCaps
1027    | PropertyId::LineHeight
1028    | PropertyId::Font => true,
1029    _ => false,
1030  }
1031}