rspack_lightningcss/rules/
keyframes.rs1use 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#[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 #[cfg_attr(feature = "serde", serde(borrow))]
38 pub name: KeyframesName<'i>,
39 pub keyframes: Vec<Keyframe<'i>>,
41 #[cfg_attr(feature = "visitor", skip_visit)]
43 pub vendor_prefix: VendorPrefix,
44 #[cfg_attr(feature = "visitor", skip_visit)]
46 pub loc: Location,
47}
48
49#[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 #[cfg_attr(feature = "serde", serde(borrow))]
62 Ident(CustomIdent<'i>),
63
64 #[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 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.css_module_config().is_some_and(|config| config.animation);
93
94 match self {
95 KeyframesName::Ident(ident) => {
96 dest.write_ident(ident.0.as_ref(), css_module_animation_enabled)?;
97 }
98 KeyframesName::Custom(s) => {
99 match_ignore_ascii_case! { &*s,
101 "none" | "initial" | "inherit" | "unset" | "default" | "revert" | "revert-layer" => {
102 serialize_string(&s, dest)?;
103 },
104 _ => {
105 dest.write_ident(s.as_ref(), css_module_animation_enabled)?;
106 }
107 }
108 }
109 }
110 Ok(())
111 }
112}
113
114impl<'i> KeyframesRule<'i> {
115 pub(crate) fn minify(&mut self, context: &mut MinifyContext<'_, 'i>) {
116 context.handler_context.context = DeclarationContext::Keyframes;
117
118 for keyframe in &mut self.keyframes {
119 keyframe
120 .declarations
121 .minify(context.handler, context.important_handler, &mut context.handler_context)
122 }
123
124 context.handler_context.context = DeclarationContext::None;
125 }
126
127 pub(crate) fn get_fallbacks<T>(&mut self, targets: &Targets) -> Vec<CssRule<'i, T>> {
128 let mut fallbacks = ColorFallbackKind::empty();
129 for keyframe in &self.keyframes {
130 for property in &keyframe.declarations.declarations {
131 match property {
132 Property::Custom(CustomProperty { value, .. }) | Property::Unparsed(UnparsedProperty { value, .. }) => {
133 fallbacks |= value.get_necessary_fallbacks(*targets);
134 }
135 _ => {}
136 }
137 }
138 }
139
140 let mut res = Vec::new();
141 let lowest_fallback = fallbacks.lowest();
142 fallbacks.remove(lowest_fallback);
143
144 if fallbacks.contains(ColorFallbackKind::P3) {
145 res.push(self.get_fallback(ColorFallbackKind::P3));
146 }
147
148 if fallbacks.contains(ColorFallbackKind::LAB)
149 || (!lowest_fallback.is_empty() && lowest_fallback != ColorFallbackKind::LAB)
150 {
151 res.push(self.get_fallback(ColorFallbackKind::LAB));
152 }
153
154 if !lowest_fallback.is_empty() {
155 for keyframe in &mut self.keyframes {
156 for property in &mut keyframe.declarations.declarations {
157 match property {
158 Property::Custom(CustomProperty { value, .. })
159 | Property::Unparsed(UnparsedProperty { value, .. }) => {
160 *value = value.get_fallback(lowest_fallback);
161 }
162 _ => {}
163 }
164 }
165 }
166 }
167
168 res
169 }
170
171 fn get_fallback<T>(&self, kind: ColorFallbackKind) -> CssRule<'i, T> {
172 let keyframes = self
173 .keyframes
174 .iter()
175 .map(|keyframe| Keyframe {
176 selectors: keyframe.selectors.clone(),
177 declarations: DeclarationBlock {
178 important_declarations: vec![],
179 declarations: keyframe
180 .declarations
181 .declarations
182 .iter()
183 .map(|property| match property {
184 Property::Custom(custom) => Property::Custom(CustomProperty {
185 name: custom.name.clone(),
186 value: custom.value.get_fallback(kind),
187 }),
188 Property::Unparsed(unparsed) => Property::Unparsed(UnparsedProperty {
189 property_id: unparsed.property_id.clone(),
190 value: unparsed.value.get_fallback(kind),
191 }),
192 _ => property.clone(),
193 })
194 .collect(),
195 },
196 })
197 .collect();
198
199 CssRule::Supports(SupportsRule {
200 condition: kind.supports_condition(),
201 rules: CssRuleList(vec![CssRule::Keyframes(KeyframesRule {
202 name: self.name.clone(),
203 keyframes,
204 vendor_prefix: self.vendor_prefix,
205 loc: self.loc.clone(),
206 })]),
207 loc: self.loc.clone(),
208 })
209 }
210}
211
212impl<'i> ToCss for KeyframesRule<'i> {
213 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
214 #[cfg(feature = "custom_sourcemap")]
215 dest.add_mapping(self.loc);
216 let mut first_rule = true;
217 macro_rules! write_prefix {
218 ($prefix: ident) => {
219 if self.vendor_prefix.contains(VendorPrefix::$prefix) {
220 #[allow(unused_assignments)]
221 if first_rule {
222 first_rule = false;
223 } else {
224 if !dest.options().minify {
225 dest.write_char('\n')?; }
227 dest.newline()?;
228 }
229 dest.write_char('@')?;
230 VendorPrefix::$prefix.to_css(dest)?;
231 dest.write_str("keyframes ")?;
232 self.name.to_css(dest)?;
233 dest.whitespace()?;
234 dest.write_char('{')?;
235 dest.indent();
236 let mut first = true;
237 for keyframe in &self.keyframes {
238 if first {
239 first = false;
240 } else if !dest.options().minify {
241 dest.write_char('\n')?; }
243 dest.newline()?;
244 keyframe.to_css(dest)?;
245 }
246 dest.dedent();
247 dest.newline()?;
248 dest.write_char('}')?;
249 }
250 };
251 }
252
253 write_prefix!(WebKit);
254 write_prefix!(Moz);
255 write_prefix!(O);
256 write_prefix!(None);
257 Ok(())
258 }
259}
260
261#[derive(Debug, PartialEq, Clone)]
263#[cfg_attr(feature = "visitor", derive(Visit))]
264#[cfg_attr(
265 feature = "serde",
266 derive(serde::Serialize, serde::Deserialize),
267 serde(tag = "type", rename_all = "camelCase")
268)]
269#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
270#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
271pub struct TimelineRangePercentage {
272 name: TimelineRangeName,
274 percentage: Percentage,
276}
277
278impl<'i> Parse<'i> for TimelineRangePercentage {
279 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
280 let name = TimelineRangeName::parse(input)?;
281 let percentage = Percentage::parse(input)?;
282 Ok(TimelineRangePercentage { name, percentage })
283 }
284}
285
286#[derive(Debug, PartialEq, Clone, Parse)]
289#[cfg_attr(feature = "visitor", derive(Visit))]
290#[cfg_attr(
291 feature = "serde",
292 derive(serde::Serialize, serde::Deserialize),
293 serde(tag = "type", content = "value", rename_all = "kebab-case")
294)]
295#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
296#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
297pub enum KeyframeSelector {
298 Percentage(Percentage),
300 From,
302 To,
304 TimelineRangePercentage(TimelineRangePercentage),
306}
307
308impl ToCss for KeyframeSelector {
309 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
310 match self {
311 KeyframeSelector::Percentage(p) => {
312 if dest.options().minify && *p == Percentage(1.0) {
313 dest.write_str("to")?;
314 Ok(())
315 } else {
316 p.to_css(dest)
317 }
318 }
319 KeyframeSelector::From => {
320 if dest.options().minify {
321 dest.write_str("0%")?;
322 Ok(())
323 } else {
324 dest.write_str("from")?;
325 Ok(())
326 }
327 }
328 KeyframeSelector::To => {
329 dest.write_str("to")?;
330 Ok(())
331 }
332 KeyframeSelector::TimelineRangePercentage(TimelineRangePercentage {
333 name: timeline_range_name,
334 percentage,
335 }) => {
336 timeline_range_name.to_css(dest)?;
337 dest.write_char(' ')?;
338 percentage.to_css(dest)
339 }
340 }
341 }
342}
343
344#[derive(Debug, PartialEq, Clone)]
348#[cfg_attr(feature = "visitor", derive(Visit))]
349#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
350#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
351#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
352pub struct Keyframe<'i> {
353 pub selectors: Vec<KeyframeSelector>,
355 #[cfg_attr(feature = "serde", serde(borrow))]
357 pub declarations: DeclarationBlock<'i>,
358}
359
360impl<'i> ToCss for Keyframe<'i> {
361 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
362 let mut first = true;
363 for selector in &self.selectors {
364 if !first {
365 dest.delim(',', false)?;
366 }
367 first = false;
368 selector.to_css(dest)?;
369 }
370
371 self.declarations.to_css_block(dest)
372 }
373}
374
375pub(crate) struct KeyframeListParser;
376
377impl<'a, 'i> AtRuleParser<'i> for KeyframeListParser {
378 type Prelude = ();
379 type AtRule = Keyframe<'i>;
380 type Error = ParserError<'i>;
381}
382
383impl<'a, 'i> QualifiedRuleParser<'i> for KeyframeListParser {
384 type Prelude = Vec<KeyframeSelector>;
385 type QualifiedRule = Keyframe<'i>;
386 type Error = ParserError<'i>;
387
388 fn parse_prelude<'t>(
389 &mut self,
390 input: &mut Parser<'i, 't>,
391 ) -> Result<Self::Prelude, ParseError<'i, ParserError<'i>>> {
392 input.parse_comma_separated(KeyframeSelector::parse)
393 }
394
395 fn parse_block<'t>(
396 &mut self,
397 selectors: Self::Prelude,
398 _: &ParserState,
399 input: &mut Parser<'i, 't>,
400 ) -> Result<Self::QualifiedRule, ParseError<'i, ParserError<'i>>> {
401 let options = ParserOptions::default();
403 Ok(Keyframe {
404 selectors,
405 declarations: DeclarationBlock::parse(input, &options)?,
406 })
407 }
408}
409
410impl<'i> DeclarationParser<'i> for KeyframeListParser {
411 type Declaration = Keyframe<'i>;
412 type Error = ParserError<'i>;
413}
414
415impl<'i> RuleBodyItemParser<'i, Keyframe<'i>, ParserError<'i>> for KeyframeListParser {
416 fn parse_qualified(&self) -> bool {
417 true
418 }
419
420 fn parse_declarations(&self) -> bool {
421 false
422 }
423}