1use std::borrow::Cow;
4
5use crate::context::PropertyHandlerContext;
6use crate::declaration::{DeclarationBlock, DeclarationList};
7use crate::error::{ParserError, PrinterError};
8use crate::macros::*;
9use crate::prefixes::Feature;
10use crate::properties::{Property, PropertyId, TokenOrValue, VendorPrefix};
11use crate::traits::{Parse, PropertyHandler, Shorthand, ToCss, Zero};
12use crate::values::ident::DashedIdent;
13use crate::values::number::{CSSNumber, NonNegative};
14use crate::values::percentage::Percentage;
15use crate::values::size::Size2D;
16use crate::values::string::CSSString;
17use crate::values::{easing::EasingFunction, ident::CustomIdent, time::Time};
18#[cfg(feature = "visitor")]
19use crate::visitor::Visit;
20use cssparser::*;
21use itertools::izip;
22use smallvec::SmallVec;
23
24use super::{LengthPercentage, LengthPercentageOrAuto};
25
26#[derive(Debug, Clone, PartialEq, Parse)]
28#[cfg_attr(feature = "visitor", derive(Visit))]
29#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
30#[cfg_attr(
31 feature = "serde",
32 derive(serde::Serialize, serde::Deserialize),
33 serde(tag = "type", content = "value", rename_all = "kebab-case")
34)]
35#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
36pub enum AnimationName<'i> {
37 None,
39 #[cfg_attr(feature = "serde", serde(borrow))]
41 Ident(CustomIdent<'i>),
42 #[cfg_attr(feature = "serde", serde(borrow))]
44 String(CSSString<'i>),
45}
46
47impl<'i> ToCss for AnimationName<'i> {
48 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
49 let css_module_animation_enabled = dest.css_module_config().is_some_and(|config| config.animation);
50 let source_index = dest.loc().source_index;
51
52 match self {
53 AnimationName::None => {
54 dest.write_str("none")?;
55 Ok(())
56 }
57 AnimationName::Ident(s) => {
58 if css_module_animation_enabled {
59 dest.with_css_module_mut(|css_module| css_module.reference(&s.0, source_index));
60 }
61 s.to_css_with_options(dest, css_module_animation_enabled)
62 }
63 AnimationName::String(s) => {
64 if css_module_animation_enabled {
65 dest.with_css_module_mut(|css_module| css_module.reference(&s, source_index));
66 }
67
68 match_ignore_ascii_case! { &*s,
70 "none" | "initial" | "inherit" | "unset" | "default" | "revert" | "revert-layer" => {
71 serialize_string(&s, dest)?;
72 Ok(())
73 },
74 _ => {
75 dest.write_ident(s.as_ref(), css_module_animation_enabled)
76 }
77 }
78 }
79 }
80 }
81}
82
83pub type AnimationNameList<'i> = SmallVec<[AnimationName<'i>; 1]>;
85
86#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
88#[cfg_attr(feature = "visitor", derive(Visit))]
89#[cfg_attr(
90 feature = "serde",
91 derive(serde::Serialize, serde::Deserialize),
92 serde(tag = "type", content = "value", rename_all = "kebab-case")
93)]
94#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
95#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
96pub enum AnimationIterationCount {
97 Number(NonNegative<CSSNumber>),
99 Infinite,
101}
102
103impl Default for AnimationIterationCount {
104 fn default() -> Self {
105 AnimationIterationCount::Number(NonNegative(1.0))
106 }
107}
108
109enum_property! {
110 pub enum AnimationDirection {
112 Normal,
114 Reverse,
116 Alternate,
118 AlternateReverse,
120 }
121}
122
123impl Default for AnimationDirection {
124 fn default() -> Self {
125 AnimationDirection::Normal
126 }
127}
128
129enum_property! {
130 pub enum AnimationPlayState {
132 Running,
134 Paused,
136 }
137}
138
139impl Default for AnimationPlayState {
140 fn default() -> Self {
141 AnimationPlayState::Running
142 }
143}
144
145enum_property! {
146 pub enum AnimationFillMode {
148 None,
150 Forwards,
152 Backwards,
154 Both,
156 }
157}
158
159impl Default for AnimationFillMode {
160 fn default() -> Self {
161 AnimationFillMode::None
162 }
163}
164
165enum_property! {
166 pub enum AnimationComposition {
168 Replace,
170 Add,
172 Accumulate,
174 }
175}
176
177#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
179#[cfg_attr(feature = "visitor", derive(Visit))]
180#[cfg_attr(
181 feature = "serde",
182 derive(serde::Serialize, serde::Deserialize),
183 serde(tag = "type", content = "value", rename_all = "kebab-case")
184)]
185#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
186#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
187pub enum AnimationTimeline<'i> {
188 Auto,
190 None,
192 #[cfg_attr(feature = "serde", serde(borrow))]
194 DashedIdent(DashedIdent<'i>),
195 Scroll(ScrollTimeline),
197 View(ViewTimeline),
199}
200
201impl<'i> Default for AnimationTimeline<'i> {
202 fn default() -> Self {
203 AnimationTimeline::Auto
204 }
205}
206
207#[derive(Debug, Clone, PartialEq)]
209#[cfg_attr(feature = "visitor", derive(Visit))]
210#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
211#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
212#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
213pub struct ScrollTimeline {
214 pub scroller: Scroller,
216 pub axis: ScrollAxis,
218}
219
220impl<'i> Parse<'i> for ScrollTimeline {
221 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
222 input.expect_function_matching("scroll")?;
223 input.parse_nested_block(|input| {
224 let mut scroller = None;
225 let mut axis = None;
226 loop {
227 if scroller.is_none() {
228 scroller = input.try_parse(Scroller::parse).ok();
229 }
230
231 if axis.is_none() {
232 axis = input.try_parse(ScrollAxis::parse).ok();
233 if axis.is_some() {
234 continue;
235 }
236 }
237 break;
238 }
239
240 Ok(ScrollTimeline {
241 scroller: scroller.unwrap_or_default(),
242 axis: axis.unwrap_or_default(),
243 })
244 })
245 }
246}
247
248impl ToCss for ScrollTimeline {
249 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
250 dest.write_str("scroll(")?;
251
252 let mut needs_space = false;
253 if self.scroller != Scroller::default() {
254 self.scroller.to_css(dest)?;
255 needs_space = true;
256 }
257
258 if self.axis != ScrollAxis::default() {
259 if needs_space {
260 dest.write_char(' ')?;
261 }
262 self.axis.to_css(dest)?;
263 }
264
265 dest.write_char(')')?;
266
267 Ok(())
268 }
269}
270
271enum_property! {
272 pub enum Scroller {
274 "root": Root,
276 "nearest": Nearest,
278 "self": SelfElement,
280 }
281}
282
283impl Default for Scroller {
284 fn default() -> Self {
285 Scroller::Nearest
286 }
287}
288
289enum_property! {
290 pub enum ScrollAxis {
292 Block,
294 Inline,
296 X,
298 Y,
300 }
301}
302
303impl Default for ScrollAxis {
304 fn default() -> Self {
305 ScrollAxis::Block
306 }
307}
308
309#[derive(Debug, Clone, PartialEq)]
311#[cfg_attr(feature = "visitor", derive(Visit))]
312#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
313#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
314#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
315pub struct ViewTimeline {
316 pub axis: ScrollAxis,
318 pub inset: Size2D<LengthPercentageOrAuto>,
320}
321
322impl<'i> Parse<'i> for ViewTimeline {
323 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
324 input.expect_function_matching("view")?;
325 input.parse_nested_block(|input| {
326 let mut axis = None;
327 let mut inset = None;
328 loop {
329 if axis.is_none() {
330 axis = input.try_parse(ScrollAxis::parse).ok();
331 }
332
333 if inset.is_none() {
334 inset = input.try_parse(Size2D::parse).ok();
335 if inset.is_some() {
336 continue;
337 }
338 }
339 break;
340 }
341
342 Ok(ViewTimeline {
343 axis: axis.unwrap_or_default(),
344 inset: inset.unwrap_or(Size2D(LengthPercentageOrAuto::Auto, LengthPercentageOrAuto::Auto)),
345 })
346 })
347 }
348}
349
350impl ToCss for ViewTimeline {
351 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
352 dest.write_str("view(")?;
353 let mut needs_space = false;
354 if self.axis != ScrollAxis::default() {
355 self.axis.to_css(dest)?;
356 needs_space = true;
357 }
358
359 if self.inset.0 != LengthPercentageOrAuto::Auto || self.inset.1 != LengthPercentageOrAuto::Auto {
360 if needs_space {
361 dest.write_char(' ')?;
362 }
363 self.inset.to_css(dest)?;
364 }
365
366 dest.write_char(')')?;
367
368 Ok(())
369 }
370}
371
372#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
374#[cfg_attr(feature = "visitor", derive(Visit))]
375#[cfg_attr(
376 feature = "serde",
377 derive(serde::Serialize, serde::Deserialize),
378 serde(rename_all = "kebab-case")
379)]
380#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
381#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
382pub enum TimelineRangeName {
383 Cover,
385 Contain,
388 Entry,
390 Exit,
392 EntryCrossing,
394 ExitCrossing,
396}
397
398#[derive(Debug, Clone, PartialEq)]
401#[cfg_attr(feature = "visitor", derive(Visit))]
402#[cfg_attr(
403 feature = "serde",
404 derive(serde::Serialize, serde::Deserialize),
405 serde(rename_all = "lowercase")
406)]
407#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
408#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
409pub enum AnimationAttachmentRange {
410 Normal,
412 #[cfg_attr(feature = "serde", serde(untagged))]
414 LengthPercentage(LengthPercentage),
415 #[cfg_attr(feature = "serde", serde(untagged))]
417 TimelineRange {
418 name: TimelineRangeName,
420 offset: LengthPercentage,
422 },
423}
424
425impl<'i> AnimationAttachmentRange {
426 fn parse<'t>(input: &mut Parser<'i, 't>, default: f32) -> Result<Self, ParseError<'i, ParserError<'i>>> {
427 if input.try_parse(|input| input.expect_ident_matching("normal")).is_ok() {
428 return Ok(AnimationAttachmentRange::Normal);
429 }
430
431 if let Ok(val) = input.try_parse(LengthPercentage::parse) {
432 return Ok(AnimationAttachmentRange::LengthPercentage(val));
433 }
434
435 let name = TimelineRangeName::parse(input)?;
436 let offset = input
437 .try_parse(LengthPercentage::parse)
438 .unwrap_or(LengthPercentage::Percentage(Percentage(default)));
439 Ok(AnimationAttachmentRange::TimelineRange { name, offset })
440 }
441
442 fn to_css<PrinterT: crate::printer::PrinterTrait>(
443 &self,
444 dest: &mut PrinterT,
445 default: f32,
446 ) -> Result<(), PrinterError> {
447 match self {
448 Self::Normal => {
449 dest.write_str("normal")?;
450 Ok(())
451 }
452 Self::LengthPercentage(val) => val.to_css(dest),
453 Self::TimelineRange { name, offset } => {
454 name.to_css(dest)?;
455 if *offset != LengthPercentage::Percentage(Percentage(default)) {
456 dest.write_char(' ')?;
457 offset.to_css(dest)?;
458 }
459 Ok(())
460 }
461 }
462 }
463}
464
465impl Default for AnimationAttachmentRange {
466 fn default() -> Self {
467 AnimationAttachmentRange::Normal
468 }
469}
470
471#[derive(Debug, Clone, PartialEq)]
473#[cfg_attr(feature = "visitor", derive(Visit))]
474#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
475#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
476#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
477pub struct AnimationRangeStart(pub AnimationAttachmentRange);
478
479impl<'i> Parse<'i> for AnimationRangeStart {
480 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
481 let range = AnimationAttachmentRange::parse(input, 0.0)?;
482 Ok(Self(range))
483 }
484}
485
486impl ToCss for AnimationRangeStart {
487 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
488 self.0.to_css(dest, 0.0)
489 }
490}
491
492#[derive(Debug, Clone, PartialEq)]
494#[cfg_attr(feature = "visitor", derive(Visit))]
495#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
496#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
497#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
498pub struct AnimationRangeEnd(pub AnimationAttachmentRange);
499
500impl<'i> Parse<'i> for AnimationRangeEnd {
501 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
502 let range = AnimationAttachmentRange::parse(input, 1.0)?;
503 Ok(Self(range))
504 }
505}
506
507impl ToCss for AnimationRangeEnd {
508 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
509 self.0.to_css(dest, 1.0)
510 }
511}
512
513#[derive(Debug, Clone, PartialEq)]
515#[cfg_attr(feature = "visitor", derive(Visit))]
516#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
517#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
518#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
519pub struct AnimationRange {
520 pub start: AnimationRangeStart,
522 pub end: AnimationRangeEnd,
524}
525
526impl<'i> Parse<'i> for AnimationRange {
527 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
528 let start = AnimationRangeStart::parse(input)?;
529 let end = input
530 .try_parse(AnimationRangeStart::parse)
531 .map(|r| AnimationRangeEnd(r.0))
532 .unwrap_or_else(|_| {
533 match &start.0 {
536 AnimationAttachmentRange::TimelineRange { name, .. } => {
537 AnimationRangeEnd(AnimationAttachmentRange::TimelineRange {
538 name: name.clone(),
539 offset: LengthPercentage::Percentage(Percentage(1.0)),
540 })
541 }
542 _ => AnimationRangeEnd(AnimationAttachmentRange::default()),
543 }
544 });
545 Ok(AnimationRange { start, end })
546 }
547}
548
549impl ToCss for AnimationRange {
550 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
551 self.start.to_css(dest)?;
552
553 let omit_end = match (&self.start.0, &self.end.0) {
554 (
555 AnimationAttachmentRange::TimelineRange { name: start_name, .. },
556 AnimationAttachmentRange::TimelineRange {
557 name: end_name,
558 offset: end_offset,
559 },
560 ) => start_name == end_name && *end_offset == LengthPercentage::Percentage(Percentage(1.0)),
561 (_, end) => *end == AnimationAttachmentRange::default(),
562 };
563
564 if !omit_end {
565 dest.write_char(' ')?;
566 self.end.to_css(dest)?;
567 }
568 Ok(())
569 }
570}
571
572define_list_shorthand! {
573 pub struct Animation<'i>(VendorPrefix) {
575 #[cfg_attr(feature = "serde", serde(borrow))]
577 name: AnimationName(AnimationName<'i>, VendorPrefix),
578 duration: AnimationDuration(NonNegative<Time>, VendorPrefix),
580 timing_function: AnimationTimingFunction(EasingFunction, VendorPrefix),
582 iteration_count: AnimationIterationCount(AnimationIterationCount, VendorPrefix),
584 direction: AnimationDirection(AnimationDirection, VendorPrefix),
586 play_state: AnimationPlayState(AnimationPlayState, VendorPrefix),
588 delay: AnimationDelay(Time, VendorPrefix),
590 fill_mode: AnimationFillMode(AnimationFillMode, VendorPrefix),
592 timeline: AnimationTimeline(AnimationTimeline<'i>),
594 }
595}
596
597impl<'i> Parse<'i> for Animation<'i> {
598 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
599 let mut name = None;
600 let mut duration = None;
601 let mut timing_function = None;
602 let mut iteration_count = None;
603 let mut direction = None;
604 let mut play_state = None;
605 let mut delay = None;
606 let mut fill_mode = None;
607 let mut timeline = None;
608
609 macro_rules! parse_prop {
610 ($var: ident, $type: ty) => {
611 if $var.is_none() {
612 if let Ok(value) = input.try_parse(<$type>::parse) {
613 $var = Some(value);
614 continue;
615 }
616 }
617 };
618 }
619
620 loop {
621 parse_prop!(duration, NonNegative<Time>);
622 parse_prop!(timing_function, EasingFunction);
623 if duration.is_some() {
625 parse_prop!(delay, Time);
626 }
627 parse_prop!(iteration_count, AnimationIterationCount);
628 parse_prop!(direction, AnimationDirection);
629 parse_prop!(fill_mode, AnimationFillMode);
630 parse_prop!(play_state, AnimationPlayState);
631 parse_prop!(name, AnimationName);
632 parse_prop!(timeline, AnimationTimeline);
633 break;
634 }
635
636 Ok(Animation {
637 name: name.unwrap_or(AnimationName::None),
638 duration: duration.unwrap_or(NonNegative(Time::Seconds(0.0))),
639 timing_function: timing_function.unwrap_or(EasingFunction::Ease),
640 iteration_count: iteration_count.unwrap_or(AnimationIterationCount::Number(NonNegative(1.0))),
641 direction: direction.unwrap_or(AnimationDirection::Normal),
642 play_state: play_state.unwrap_or(AnimationPlayState::Running),
643 delay: delay.unwrap_or(Time::Seconds(0.0)),
644 fill_mode: fill_mode.unwrap_or(AnimationFillMode::None),
645 timeline: timeline.unwrap_or(AnimationTimeline::Auto),
646 })
647 }
648}
649
650impl<'i> ToCss for Animation<'i> {
651 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
652 match &self.name {
653 AnimationName::None => {}
654 AnimationName::Ident(CustomIdent(name)) | AnimationName::String(CSSString(name)) => {
655 if !self.duration.is_zero() || !self.delay.is_zero() {
656 self.duration.to_css(dest)?;
657 dest.write_char(' ')?;
658 }
659
660 if !self.timing_function.is_ease() || EasingFunction::is_ident(&name) {
661 self.timing_function.to_css(dest)?;
662 dest.write_char(' ')?;
663 }
664
665 if !self.delay.is_zero() {
666 self.delay.to_css(dest)?;
667 dest.write_char(' ')?;
668 }
669
670 if self.iteration_count != AnimationIterationCount::default() || name.as_ref() == "infinite" {
671 self.iteration_count.to_css(dest)?;
672 dest.write_char(' ')?;
673 }
674
675 if self.direction != AnimationDirection::default() || AnimationDirection::parse_string(&name).is_ok() {
676 self.direction.to_css(dest)?;
677 dest.write_char(' ')?;
678 }
679
680 if self.fill_mode != AnimationFillMode::default()
681 || (!name.eq_ignore_ascii_case("none") && AnimationFillMode::parse_string(&name).is_ok())
682 {
683 self.fill_mode.to_css(dest)?;
684 dest.write_char(' ')?;
685 }
686
687 if self.play_state != AnimationPlayState::default() || AnimationPlayState::parse_string(&name).is_ok() {
688 self.play_state.to_css(dest)?;
689 dest.write_char(' ')?;
690 }
691 }
692 }
693
694 self.name.to_css(dest)?;
697
698 if self.name != AnimationName::None && self.timeline != AnimationTimeline::default() {
699 dest.write_char(' ')?;
700 self.timeline.to_css(dest)?;
701 }
702
703 Ok(())
704 }
705}
706
707pub type AnimationList<'i> = SmallVec<[Animation<'i>; 1]>;
709
710#[derive(Default)]
711pub(crate) struct AnimationHandler<'i> {
712 names: Option<(SmallVec<[AnimationName<'i>; 1]>, VendorPrefix)>,
713 durations: Option<(SmallVec<[NonNegative<Time>; 1]>, VendorPrefix)>,
714 timing_functions: Option<(SmallVec<[EasingFunction; 1]>, VendorPrefix)>,
715 iteration_counts: Option<(SmallVec<[AnimationIterationCount; 1]>, VendorPrefix)>,
716 directions: Option<(SmallVec<[AnimationDirection; 1]>, VendorPrefix)>,
717 play_states: Option<(SmallVec<[AnimationPlayState; 1]>, VendorPrefix)>,
718 delays: Option<(SmallVec<[Time; 1]>, VendorPrefix)>,
719 fill_modes: Option<(SmallVec<[AnimationFillMode; 1]>, VendorPrefix)>,
720 timelines: Option<SmallVec<[AnimationTimeline<'i>; 1]>>,
721 range_starts: Option<SmallVec<[AnimationRangeStart; 1]>>,
722 range_ends: Option<SmallVec<[AnimationRangeEnd; 1]>>,
723 has_any: bool,
724}
725
726impl<'i> PropertyHandler<'i> for AnimationHandler<'i> {
727 fn handle_property(
728 &mut self,
729 property: &Property<'i>,
730 dest: &mut DeclarationList<'i>,
731 context: &mut PropertyHandlerContext<'i, '_>,
732 ) -> bool {
733 macro_rules! maybe_flush {
734 ($prop: ident, $val: expr, $vp: ident) => {{
735 if let Some((val, prefixes)) = &self.$prop {
738 if val != $val && !prefixes.contains(*$vp) {
739 self.flush(dest, context);
740 }
741 }
742 }};
743 }
744
745 macro_rules! property {
746 ($prop: ident, $val: expr, $vp: ident) => {{
747 maybe_flush!($prop, $val, $vp);
748
749 if let Some((val, prefixes)) = &mut self.$prop {
751 *val = $val.clone();
752 *prefixes |= *$vp;
753 } else {
754 self.$prop = Some(($val.clone(), *$vp));
755 self.has_any = true;
756 }
757 }};
758 }
759
760 match property {
761 Property::AnimationName(val, vp) => property!(names, val, vp),
762 Property::AnimationDuration(val, vp) => property!(durations, val, vp),
763 Property::AnimationTimingFunction(val, vp) => property!(timing_functions, val, vp),
764 Property::AnimationIterationCount(val, vp) => property!(iteration_counts, val, vp),
765 Property::AnimationDirection(val, vp) => property!(directions, val, vp),
766 Property::AnimationPlayState(val, vp) => property!(play_states, val, vp),
767 Property::AnimationDelay(val, vp) => property!(delays, val, vp),
768 Property::AnimationFillMode(val, vp) => property!(fill_modes, val, vp),
769 Property::AnimationTimeline(val) => {
770 self.timelines = Some(val.clone());
771 self.has_any = true;
772 }
773 Property::AnimationRangeStart(val) => {
774 self.range_starts = Some(val.clone());
775 self.has_any = true;
776 }
777 Property::AnimationRangeEnd(val) => {
778 self.range_ends = Some(val.clone());
779 self.has_any = true;
780 }
781 Property::AnimationRange(val) => {
782 self.range_starts = Some(val.iter().map(|v| v.start.clone()).collect());
783 self.range_ends = Some(val.iter().map(|v| v.end.clone()).collect());
784 self.has_any = true;
785 }
786 Property::Animation(val, vp) => {
787 let names = val.iter().map(|b| b.name.clone()).collect();
788 maybe_flush!(names, &names, vp);
789
790 let durations = val.iter().map(|b| b.duration.clone()).collect();
791 maybe_flush!(durations, &durations, vp);
792
793 let timing_functions = val.iter().map(|b| b.timing_function.clone()).collect();
794 maybe_flush!(timing_functions, &timing_functions, vp);
795
796 let iteration_counts = val.iter().map(|b| b.iteration_count.clone()).collect();
797 maybe_flush!(iteration_counts, &iteration_counts, vp);
798
799 let directions = val.iter().map(|b| b.direction.clone()).collect();
800 maybe_flush!(directions, &directions, vp);
801
802 let play_states = val.iter().map(|b| b.play_state.clone()).collect();
803 maybe_flush!(play_states, &play_states, vp);
804
805 let delays = val.iter().map(|b| b.delay.clone()).collect();
806 maybe_flush!(delays, &delays, vp);
807
808 let fill_modes = val.iter().map(|b| b.fill_mode.clone()).collect();
809 maybe_flush!(fill_modes, &fill_modes, vp);
810
811 self.timelines = Some(val.iter().map(|b| b.timeline.clone()).collect());
812
813 property!(names, &names, vp);
814 property!(durations, &durations, vp);
815 property!(timing_functions, &timing_functions, vp);
816 property!(iteration_counts, &iteration_counts, vp);
817 property!(directions, &directions, vp);
818 property!(play_states, &play_states, vp);
819 property!(delays, &delays, vp);
820 property!(fill_modes, &fill_modes, vp);
821
822 self.range_starts = None;
825 self.range_ends = None;
826 }
827 Property::Unparsed(val) if is_animation_property(&val.property_id) => {
828 let mut val = Cow::Borrowed(val);
829 if matches!(val.property_id, PropertyId::Animation(_)) {
830 use crate::properties::custom::Token;
831
832 for token in &mut val.to_mut().value.0 {
835 match token {
836 TokenOrValue::Token(Token::Ident(id)) => {
837 if AnimationDirection::parse_string(&id).is_err()
838 && AnimationPlayState::parse_string(&id).is_err()
839 && AnimationFillMode::parse_string(&id).is_err()
840 && !EasingFunction::is_ident(&id)
841 && id.as_ref() != "infinite"
842 && id.as_ref() != "auto"
843 {
844 *token = TokenOrValue::AnimationName(AnimationName::Ident(CustomIdent(id.clone())));
845 }
846 }
847 TokenOrValue::Token(Token::String(s)) => {
848 *token = TokenOrValue::AnimationName(AnimationName::String(CSSString(s.clone())));
849 }
850 _ => {}
851 }
852 }
853
854 self.range_starts = None;
855 self.range_ends = None;
856 }
857
858 self.flush(dest, context);
859 dest.push(Property::Unparsed(
860 val.get_prefixed(context.targets, Feature::Animation),
861 ));
862 }
863 _ => return false,
864 }
865
866 true
867 }
868
869 fn finalize(&mut self, dest: &mut DeclarationList<'i>, context: &mut PropertyHandlerContext<'i, '_>) {
870 self.flush(dest, context);
871 }
872}
873
874impl<'i> AnimationHandler<'i> {
875 fn flush(&mut self, dest: &mut DeclarationList<'i>, context: &mut PropertyHandlerContext<'i, '_>) {
876 if !self.has_any {
877 return;
878 }
879
880 self.has_any = false;
881
882 let mut names = std::mem::take(&mut self.names);
883 let mut durations = std::mem::take(&mut self.durations);
884 let mut timing_functions = std::mem::take(&mut self.timing_functions);
885 let mut iteration_counts = std::mem::take(&mut self.iteration_counts);
886 let mut directions = std::mem::take(&mut self.directions);
887 let mut play_states = std::mem::take(&mut self.play_states);
888 let mut delays = std::mem::take(&mut self.delays);
889 let mut fill_modes = std::mem::take(&mut self.fill_modes);
890 let mut timelines_value = std::mem::take(&mut self.timelines);
891 let range_starts = std::mem::take(&mut self.range_starts);
892 let range_ends = std::mem::take(&mut self.range_ends);
893
894 if let (
895 Some((names, names_vp)),
896 Some((durations, durations_vp)),
897 Some((timing_functions, timing_functions_vp)),
898 Some((iteration_counts, iteration_counts_vp)),
899 Some((directions, directions_vp)),
900 Some((play_states, play_states_vp)),
901 Some((delays, delays_vp)),
902 Some((fill_modes, fill_modes_vp)),
903 ) = (
904 &mut names,
905 &mut durations,
906 &mut timing_functions,
907 &mut iteration_counts,
908 &mut directions,
909 &mut play_states,
910 &mut delays,
911 &mut fill_modes,
912 ) {
913 let len = names.len();
915 let intersection = *names_vp
916 & *durations_vp
917 & *timing_functions_vp
918 & *iteration_counts_vp
919 & *directions_vp
920 & *play_states_vp
921 & *delays_vp
922 & *fill_modes_vp;
923 let mut timelines = if let Some(timelines) = &mut timelines_value {
924 Cow::Borrowed(timelines)
925 } else if !intersection.contains(VendorPrefix::None) {
926 Cow::Owned(std::iter::repeat(AnimationTimeline::Auto).take(len).collect())
928 } else {
929 Cow::Owned(SmallVec::new())
930 };
931
932 if !intersection.is_empty()
933 && durations.len() == len
934 && timing_functions.len() == len
935 && iteration_counts.len() == len
936 && directions.len() == len
937 && play_states.len() == len
938 && delays.len() == len
939 && fill_modes.len() == len
940 && timelines.len() == len
941 {
942 let timeline_property = if timelines.iter().any(|t| *t != AnimationTimeline::Auto)
943 && (intersection != VendorPrefix::None
944 || !context
945 .targets
946 .is_compatible(crate::compat::Feature::AnimationTimelineShorthand))
947 {
948 Some(Property::AnimationTimeline(timelines.clone().into_owned()))
949 } else {
950 None
951 };
952
953 let animations = izip!(
954 names.drain(..),
955 durations.drain(..),
956 timing_functions.drain(..),
957 iteration_counts.drain(..),
958 directions.drain(..),
959 play_states.drain(..),
960 delays.drain(..),
961 fill_modes.drain(..),
962 timelines.to_mut().drain(..)
963 )
964 .map(
965 |(
966 name,
967 duration,
968 timing_function,
969 iteration_count,
970 direction,
971 play_state,
972 delay,
973 fill_mode,
974 timeline,
975 )| {
976 Animation {
977 name,
978 duration,
979 timing_function,
980 iteration_count,
981 direction,
982 play_state,
983 delay,
984 fill_mode,
985 timeline: if timeline_property.is_some() {
986 AnimationTimeline::Auto
987 } else {
988 timeline
989 },
990 }
991 },
992 )
993 .collect();
994 let prefix = context.targets.prefixes(intersection, Feature::Animation);
995 dest.push(Property::Animation(animations, prefix));
996 names_vp.remove(intersection);
997 durations_vp.remove(intersection);
998 timing_functions_vp.remove(intersection);
999 iteration_counts_vp.remove(intersection);
1000 directions_vp.remove(intersection);
1001 play_states_vp.remove(intersection);
1002 delays_vp.remove(intersection);
1003 fill_modes_vp.remove(intersection);
1004
1005 if let Some(p) = timeline_property {
1006 dest.push(p);
1007 }
1008 timelines_value = None;
1009 }
1010 }
1011
1012 macro_rules! prop {
1013 ($var: ident, $property: ident) => {
1014 if let Some((val, vp)) = $var {
1015 if !vp.is_empty() {
1016 let prefix = context.targets.prefixes(vp, Feature::$property);
1017 dest.push(Property::$property(val, prefix))
1018 }
1019 }
1020 };
1021 }
1022
1023 prop!(names, AnimationName);
1024 prop!(durations, AnimationDuration);
1025 prop!(timing_functions, AnimationTimingFunction);
1026 prop!(iteration_counts, AnimationIterationCount);
1027 prop!(directions, AnimationDirection);
1028 prop!(play_states, AnimationPlayState);
1029 prop!(delays, AnimationDelay);
1030 prop!(fill_modes, AnimationFillMode);
1031
1032 if let Some(val) = timelines_value {
1033 dest.push(Property::AnimationTimeline(val));
1034 }
1035
1036 match (range_starts, range_ends) {
1037 (Some(range_starts), Some(range_ends)) => {
1038 if range_starts.len() == range_ends.len() {
1039 dest.push(Property::AnimationRange(
1040 range_starts
1041 .into_iter()
1042 .zip(range_ends.into_iter())
1043 .map(|(start, end)| AnimationRange { start, end })
1044 .collect(),
1045 ));
1046 } else {
1047 dest.push(Property::AnimationRangeStart(range_starts));
1048 dest.push(Property::AnimationRangeEnd(range_ends));
1049 }
1050 }
1051 (range_starts, range_ends) => {
1052 if let Some(range_starts) = range_starts {
1053 dest.push(Property::AnimationRangeStart(range_starts));
1054 }
1055
1056 if let Some(range_ends) = range_ends {
1057 dest.push(Property::AnimationRangeEnd(range_ends));
1058 }
1059 }
1060 }
1061 }
1062}
1063
1064#[inline]
1065fn is_animation_property(property_id: &PropertyId) -> bool {
1066 match property_id {
1067 PropertyId::AnimationName(_)
1068 | PropertyId::AnimationDuration(_)
1069 | PropertyId::AnimationTimingFunction(_)
1070 | PropertyId::AnimationIterationCount(_)
1071 | PropertyId::AnimationDirection(_)
1072 | PropertyId::AnimationPlayState(_)
1073 | PropertyId::AnimationDelay(_)
1074 | PropertyId::AnimationFillMode(_)
1075 | PropertyId::AnimationComposition
1076 | PropertyId::AnimationTimeline
1077 | PropertyId::AnimationRange
1078 | PropertyId::AnimationRangeStart
1079 | PropertyId::AnimationRangeEnd
1080 | PropertyId::Animation(_) => true,
1081 _ => false,
1082 }
1083}