Skip to main content

rspack_lightningcss/rules/
keyframes.rs

1//! The `@keyframes` rule.
2
3use super::supports::SupportsRule;
4use super::MinifyContext;
5use super::{CssRule, CssRuleList, Location};
6use crate::context::DeclarationContext;
7use crate::declaration::DeclarationBlock;
8use crate::error::{ParserError, PrinterError};
9use crate::parser::ParserOptions;
10use crate::properties::animation::TimelineRangeName;
11use crate::properties::custom::{CustomProperty, UnparsedProperty};
12use crate::properties::Property;
13use crate::targets::Targets;
14use crate::traits::{Parse, ToCss};
15use crate::values::color::ColorFallbackKind;
16use crate::values::ident::CustomIdent;
17use crate::values::percentage::Percentage;
18use crate::values::string::CowArcStr;
19use crate::vendor_prefix::VendorPrefix;
20#[cfg(feature = "visitor")]
21use crate::visitor::Visit;
22use cssparser::*;
23
24/// A [@keyframes](https://drafts.csswg.org/css-animations/#keyframes) rule.
25#[derive(Debug, PartialEq, Clone)]
26#[cfg_attr(feature = "visitor", derive(Visit))]
27#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
28#[cfg_attr(
29  feature = "serde",
30  derive(serde::Serialize, serde::Deserialize),
31  serde(rename_all = "camelCase")
32)]
33#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
34pub struct KeyframesRule<'i> {
35  /// The animation name.
36  /// <keyframes-name> = <custom-ident> | <string>
37  #[cfg_attr(feature = "serde", serde(borrow))]
38  pub name: KeyframesName<'i>,
39  /// A list of keyframes in the animation.
40  pub keyframes: Vec<Keyframe<'i>>,
41  /// A vendor prefix for the rule, e.g. `@-webkit-keyframes`.
42  #[cfg_attr(feature = "visitor", skip_visit)]
43  pub vendor_prefix: VendorPrefix,
44  /// The location of the rule in the source file.
45  #[cfg_attr(feature = "visitor", skip_visit)]
46  pub loc: Location,
47}
48
49/// KeyframesName
50#[derive(Debug, Clone, PartialEq, Eq, Hash)]
51#[cfg_attr(feature = "visitor", derive(Visit))]
52#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
53#[cfg_attr(
54  feature = "serde",
55  derive(serde::Serialize, serde::Deserialize),
56  serde(tag = "type", content = "value", rename_all = "kebab-case")
57)]
58#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
59pub enum KeyframesName<'i> {
60  /// `<custom-ident>` of a `@keyframes` name.
61  #[cfg_attr(feature = "serde", serde(borrow))]
62  Ident(CustomIdent<'i>),
63
64  /// `<string>` of a `@keyframes` name.
65  #[cfg_attr(feature = "serde", serde(borrow))]
66  Custom(CowArcStr<'i>),
67}
68
69impl<'i> Parse<'i> for KeyframesName<'i> {
70  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
71    match input.next()?.clone() {
72      Token::Ident(ref s) => {
73        // CSS-wide keywords without quotes throws an error.
74        match_ignore_ascii_case! { &*s,
75          "none" | "initial" | "inherit" | "unset" | "default" | "revert" | "revert-layer" => {
76            Err(input.new_unexpected_token_error(Token::Ident(s.clone())))
77          },
78          _ => {
79            Ok(KeyframesName::Ident(CustomIdent(s.into())))
80          }
81        }
82      }
83
84      Token::QuotedString(ref s) => Ok(KeyframesName::Custom(s.into())),
85      t => return Err(input.new_unexpected_token_error(t.clone())),
86    }
87  }
88}
89
90impl<'i> ToCss for KeyframesName<'i> {
91  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
92    let css_module_animation_enabled = dest
93      .state()
94      .css_module
95      .as_ref()
96      .map_or(false, |css_module| css_module.config.animation);
97
98    match self {
99      KeyframesName::Ident(ident) => {
100        dest.write_ident(ident.0.as_ref(), css_module_animation_enabled)?;
101      }
102      KeyframesName::Custom(s) => {
103        // CSS-wide keywords and `none` cannot remove quotes.
104        match_ignore_ascii_case! { &*s,
105          "none" | "initial" | "inherit" | "unset" | "default" | "revert" | "revert-layer" => {
106            serialize_string(&s, dest)?;
107          },
108          _ => {
109            dest.write_ident(s.as_ref(), css_module_animation_enabled)?;
110          }
111        }
112      }
113    }
114    Ok(())
115  }
116}
117
118impl<'i> KeyframesRule<'i> {
119  pub(crate) fn minify(&mut self, context: &mut MinifyContext<'_, 'i>) {
120    context.handler_context.context = DeclarationContext::Keyframes;
121
122    for keyframe in &mut self.keyframes {
123      keyframe
124        .declarations
125        .minify(context.handler, context.important_handler, &mut context.handler_context)
126    }
127
128    context.handler_context.context = DeclarationContext::None;
129  }
130
131  pub(crate) fn get_fallbacks<T>(&mut self, targets: &Targets) -> Vec<CssRule<'i, T>> {
132    let mut fallbacks = ColorFallbackKind::empty();
133    for keyframe in &self.keyframes {
134      for property in &keyframe.declarations.declarations {
135        match property {
136          Property::Custom(CustomProperty { value, .. }) | Property::Unparsed(UnparsedProperty { value, .. }) => {
137            fallbacks |= value.get_necessary_fallbacks(*targets);
138          }
139          _ => {}
140        }
141      }
142    }
143
144    let mut res = Vec::new();
145    let lowest_fallback = fallbacks.lowest();
146    fallbacks.remove(lowest_fallback);
147
148    if fallbacks.contains(ColorFallbackKind::P3) {
149      res.push(self.get_fallback(ColorFallbackKind::P3));
150    }
151
152    if fallbacks.contains(ColorFallbackKind::LAB)
153      || (!lowest_fallback.is_empty() && lowest_fallback != ColorFallbackKind::LAB)
154    {
155      res.push(self.get_fallback(ColorFallbackKind::LAB));
156    }
157
158    if !lowest_fallback.is_empty() {
159      for keyframe in &mut self.keyframes {
160        for property in &mut keyframe.declarations.declarations {
161          match property {
162            Property::Custom(CustomProperty { value, .. })
163            | Property::Unparsed(UnparsedProperty { value, .. }) => {
164              *value = value.get_fallback(lowest_fallback);
165            }
166            _ => {}
167          }
168        }
169      }
170    }
171
172    res
173  }
174
175  fn get_fallback<T>(&self, kind: ColorFallbackKind) -> CssRule<'i, T> {
176    let keyframes = self
177      .keyframes
178      .iter()
179      .map(|keyframe| Keyframe {
180        selectors: keyframe.selectors.clone(),
181        declarations: DeclarationBlock {
182          important_declarations: vec![],
183          declarations: keyframe
184            .declarations
185            .declarations
186            .iter()
187            .map(|property| match property {
188              Property::Custom(custom) => Property::Custom(CustomProperty {
189                name: custom.name.clone(),
190                value: custom.value.get_fallback(kind),
191              }),
192              Property::Unparsed(unparsed) => Property::Unparsed(UnparsedProperty {
193                property_id: unparsed.property_id.clone(),
194                value: unparsed.value.get_fallback(kind),
195              }),
196              _ => property.clone(),
197            })
198            .collect(),
199        },
200      })
201      .collect();
202
203    CssRule::Supports(SupportsRule {
204      condition: kind.supports_condition(),
205      rules: CssRuleList(vec![CssRule::Keyframes(KeyframesRule {
206        name: self.name.clone(),
207        keyframes,
208        vendor_prefix: self.vendor_prefix,
209        loc: self.loc.clone(),
210      })]),
211      loc: self.loc.clone(),
212    })
213  }
214}
215
216impl<'i> ToCss for KeyframesRule<'i> {
217  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
218    dest.add_mapping(self.loc);
219    let mut first_rule = true;
220    macro_rules! write_prefix {
221      ($prefix: ident) => {
222        if self.vendor_prefix.contains(VendorPrefix::$prefix) {
223          #[allow(unused_assignments)]
224          if first_rule {
225            first_rule = false;
226          } else {
227            if !dest.options().minify {
228              dest.write_char('\n')?; // no indent
229            }
230            dest.newline()?;
231          }
232          dest.write_char('@')?;
233          VendorPrefix::$prefix.to_css(dest)?;
234          dest.write_str("keyframes ")?;
235          self.name.to_css(dest)?;
236          dest.whitespace()?;
237          dest.write_char('{')?;
238          dest.indent();
239          let mut first = true;
240          for keyframe in &self.keyframes {
241            if first {
242              first = false;
243            } else if !dest.options().minify {
244              dest.write_char('\n')?; // no indent
245            }
246            dest.newline()?;
247            keyframe.to_css(dest)?;
248          }
249          dest.dedent();
250          dest.newline()?;
251          dest.write_char('}')?;
252        }
253      };
254    }
255
256    write_prefix!(WebKit);
257    write_prefix!(Moz);
258    write_prefix!(O);
259    write_prefix!(None);
260    Ok(())
261  }
262}
263
264/// A percentage of a given timeline range
265#[derive(Debug, PartialEq, Clone)]
266#[cfg_attr(feature = "visitor", derive(Visit))]
267#[cfg_attr(
268  feature = "serde",
269  derive(serde::Serialize, serde::Deserialize),
270  serde(tag = "type", rename_all = "camelCase")
271)]
272#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
273#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
274pub struct TimelineRangePercentage {
275  /// The name of the timeline range.
276  name: TimelineRangeName,
277  /// The percentage progress between the start and end of the range.
278  percentage: Percentage,
279}
280
281impl<'i> Parse<'i> for TimelineRangePercentage {
282  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
283    let name = TimelineRangeName::parse(input)?;
284    let percentage = Percentage::parse(input)?;
285    Ok(TimelineRangePercentage { name, percentage })
286  }
287}
288
289/// A [keyframe selector](https://drafts.csswg.org/css-animations/#typedef-keyframe-selector)
290/// within an `@keyframes` rule.
291#[derive(Debug, PartialEq, Clone, Parse)]
292#[cfg_attr(feature = "visitor", derive(Visit))]
293#[cfg_attr(
294  feature = "serde",
295  derive(serde::Serialize, serde::Deserialize),
296  serde(tag = "type", content = "value", rename_all = "kebab-case")
297)]
298#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
299#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
300pub enum KeyframeSelector {
301  /// An explicit percentage.
302  Percentage(Percentage),
303  /// The `from` keyword. Equivalent to 0%.
304  From,
305  /// The `to` keyword. Equivalent to 100%.
306  To,
307  /// A [named timeline range selector](https://drafts.csswg.org/scroll-animations-1/#named-range-keyframes)
308  TimelineRangePercentage(TimelineRangePercentage),
309}
310
311impl ToCss for KeyframeSelector {
312  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
313    match self {
314      KeyframeSelector::Percentage(p) => {
315        if dest.options().minify && *p == Percentage(1.0) {
316          dest.write_str("to")?;
317          Ok(())
318        } else {
319          p.to_css(dest)
320        }
321      }
322      KeyframeSelector::From => {
323        if dest.options().minify {
324          dest.write_str("0%")?;
325          Ok(())
326        } else {
327          dest.write_str("from")?;
328          Ok(())
329        }
330      }
331      KeyframeSelector::To => {
332        dest.write_str("to")?;
333        Ok(())
334      }
335      KeyframeSelector::TimelineRangePercentage(TimelineRangePercentage {
336        name: timeline_range_name,
337        percentage,
338      }) => {
339        timeline_range_name.to_css(dest)?;
340        dest.write_char(' ')?;
341        percentage.to_css(dest)
342      }
343    }
344  }
345}
346
347/// An individual keyframe within an `@keyframes` rule.
348///
349/// See [KeyframesRule](KeyframesRule).
350#[derive(Debug, PartialEq, Clone)]
351#[cfg_attr(feature = "visitor", derive(Visit))]
352#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
353#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
354#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
355pub struct Keyframe<'i> {
356  /// A list of keyframe selectors to associate with the declarations in this keyframe.
357  pub selectors: Vec<KeyframeSelector>,
358  /// The declarations for this keyframe.
359  #[cfg_attr(feature = "serde", serde(borrow))]
360  pub declarations: DeclarationBlock<'i>,
361}
362
363impl<'i> ToCss for Keyframe<'i> {
364  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
365    let mut first = true;
366    for selector in &self.selectors {
367      if !first {
368        dest.delim(',', false)?;
369      }
370      first = false;
371      selector.to_css(dest)?;
372    }
373
374    self.declarations.to_css_block(dest)
375  }
376}
377
378pub(crate) struct KeyframeListParser;
379
380impl<'a, 'i> AtRuleParser<'i> for KeyframeListParser {
381  type Prelude = ();
382  type AtRule = Keyframe<'i>;
383  type Error = ParserError<'i>;
384}
385
386impl<'a, 'i> QualifiedRuleParser<'i> for KeyframeListParser {
387  type Prelude = Vec<KeyframeSelector>;
388  type QualifiedRule = Keyframe<'i>;
389  type Error = ParserError<'i>;
390
391  fn parse_prelude<'t>(
392    &mut self,
393    input: &mut Parser<'i, 't>,
394  ) -> Result<Self::Prelude, ParseError<'i, ParserError<'i>>> {
395    input.parse_comma_separated(KeyframeSelector::parse)
396  }
397
398  fn parse_block<'t>(
399    &mut self,
400    selectors: Self::Prelude,
401    _: &ParserState,
402    input: &mut Parser<'i, 't>,
403  ) -> Result<Self::QualifiedRule, ParseError<'i, ParserError<'i>>> {
404    // For now there are no options that apply within @keyframes
405    let options = ParserOptions::default();
406    Ok(Keyframe {
407      selectors,
408      declarations: DeclarationBlock::parse(input, &options)?,
409    })
410  }
411}
412
413impl<'i> DeclarationParser<'i> for KeyframeListParser {
414  type Declaration = Keyframe<'i>;
415  type Error = ParserError<'i>;
416}
417
418impl<'i> RuleBodyItemParser<'i, Keyframe<'i>, ParserError<'i>> for KeyframeListParser {
419  fn parse_qualified(&self) -> bool {
420    true
421  }
422
423  fn parse_declarations(&self) -> bool {
424    false
425  }
426}