1use 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#[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 #[cfg_attr(feature = "serde", serde(borrow))]
27 pub properties: Vec<FontFaceProperty<'i>>,
28 #[cfg_attr(feature = "visitor", skip_visit)]
30 pub loc: Location,
31}
32
33#[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 #[cfg_attr(feature = "serde", serde(borrow))]
48 Source(Vec<Source<'i>>),
49 FontFamily(FontFamily<'i>),
51 FontStyle(FontStyle),
53 FontWeight(Size2D<FontWeight>),
55 FontStretch(Size2D<FontStretch>),
57 UnicodeRange(Vec<UnicodeRange>),
59 Custom(CustomProperty<'i>),
61}
62
63#[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 Url(UrlSource<'i>),
77 #[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#[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 pub url: Url<'i>,
125 #[cfg_attr(feature = "serde", serde(borrow))]
127 pub format: Option<FontFormat<'i>>,
128 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#[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 WOFF,
188 WOFF2,
190 TrueType,
192 OpenType,
194 #[cfg_attr(feature = "serde", serde(rename = "embedded-opentype"))]
196 EmbeddedOpenType,
197 Collection,
199 SVG,
201 #[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 serialize_string(&s, dest)?;
238 Ok(())
239 }
240}
241
242enum_property! {
243 pub enum FontTechnology {
247 "features-opentype": FeaturesOpentype,
253 "features-aat": FeaturesAat,
256 "features-graphite": FeaturesGraphite,
259
260 "color-colrv0": ColorCOLRv0,
265 "color-colrv1": ColorCOLRv1,
267 "color-svg": ColorSVG,
269 "color-sbix": ColorSbix,
271 "color-cbdt": ColorCBDT,
273
274 "variations": Variations,
277 "palettes": Palettes,
280 "incremental": Incremental,
283 }
284}
285
286#[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 pub start: u32,
297 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 if self.start != self.end {
315 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 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#[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,
374 Italic,
376 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
434impl<'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
479impl<'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}