1use std::rc::Rc;
6use std::time::Duration;
7
8use lightningcss::properties::{Property, PropertyId};
9use lightningcss::values::easing::{EasingFunction, StepPosition as CssStepPosition};
10use lightningcss::values::time::Time;
11
12#[derive(Clone, Debug, PartialEq, Eq, Hash)]
13pub enum TransitionProperty {
14 Opacity,
15 Color,
16 BackgroundColor,
17 BorderColor,
18 TextDecorationColor,
19 TextShadow,
20 Fill,
23 Stroke,
24 Width,
25 Height,
26 MinWidth,
27 MinHeight,
28 MaxWidth,
29 MaxHeight,
30 PaddingTop,
31 PaddingRight,
32 PaddingBottom,
33 PaddingLeft,
34 MarginTop,
35 MarginRight,
36 MarginBottom,
37 MarginLeft,
38 BorderTopLeftRadius,
39 BorderTopRightRadius,
40 BorderBottomRightRadius,
41 BorderBottomLeftRadius,
42 CornerTopLeftShape,
44 CornerTopRightShape,
45 CornerBottomRightShape,
46 CornerBottomLeftShape,
47 BorderTopWidth,
48 BorderRightWidth,
49 BorderBottomWidth,
50 BorderLeftWidth,
51 RowGap,
52 ColumnGap,
53 FontSize,
54 ObjectPosition,
55 AspectRatio,
57 OverflowX,
60 OverflowY,
61 Transform,
64 Shading,
67 All,
68 Other(Rc<str>),
69}
70
71pub const ANIMATABLE_COUNT: usize = 40;
72
73impl TransitionProperty {
74 pub fn animatable() -> [TransitionProperty; ANIMATABLE_COUNT] {
76 use TransitionProperty::*;
77 [
78 Opacity,
79 Color,
80 BackgroundColor,
81 BorderColor,
82 TextDecorationColor,
83 TextShadow,
84 Fill,
85 Stroke,
86 Width,
87 Height,
88 MinWidth,
89 MinHeight,
90 MaxWidth,
91 MaxHeight,
92 PaddingTop,
93 PaddingRight,
94 PaddingBottom,
95 PaddingLeft,
96 MarginTop,
97 MarginRight,
98 MarginBottom,
99 MarginLeft,
100 BorderTopLeftRadius,
101 BorderTopRightRadius,
102 BorderBottomRightRadius,
103 BorderBottomLeftRadius,
104 CornerTopLeftShape,
105 CornerTopRightShape,
106 CornerBottomRightShape,
107 CornerBottomLeftShape,
108 BorderTopWidth,
109 BorderRightWidth,
110 BorderBottomWidth,
111 BorderLeftWidth,
112 RowGap,
113 ColumnGap,
114 FontSize,
115 ObjectPosition,
116 AspectRatio,
117 Transform,
118 ]
119 }
120
121 pub fn keyframed() -> impl Iterator<Item = TransitionProperty> {
123 Self::animatable().into_iter().chain([
124 TransitionProperty::OverflowX,
125 TransitionProperty::OverflowY,
126 TransitionProperty::Shading,
127 ])
128 }
129
130 pub fn is_discrete(&self) -> bool {
131 matches!(
132 self,
133 TransitionProperty::OverflowX | TransitionProperty::OverflowY
134 )
135 }
136
137 pub fn name(&self) -> &str {
138 use TransitionProperty::*;
139 match self {
140 Opacity => "opacity",
141 Color => "color",
142 BackgroundColor => "background-color",
143 BorderColor => "border-color",
144 TextDecorationColor => "text-decoration-color",
145 TextShadow => "text-shadow",
146 Fill => "fill",
147 Stroke => "stroke",
148 Width => "width",
149 Height => "height",
150 MinWidth => "min-width",
151 MinHeight => "min-height",
152 MaxWidth => "max-width",
153 MaxHeight => "max-height",
154 PaddingTop => "padding-top",
155 PaddingRight => "padding-right",
156 PaddingBottom => "padding-bottom",
157 PaddingLeft => "padding-left",
158 MarginTop => "margin-top",
159 MarginRight => "margin-right",
160 MarginBottom => "margin-bottom",
161 MarginLeft => "margin-left",
162 BorderTopLeftRadius => "border-top-left-radius",
163 BorderTopRightRadius => "border-top-right-radius",
164 BorderBottomRightRadius => "border-bottom-right-radius",
165 BorderBottomLeftRadius => "border-bottom-left-radius",
166 CornerTopLeftShape => "corner-top-left-shape",
167 CornerTopRightShape => "corner-top-right-shape",
168 CornerBottomRightShape => "corner-bottom-right-shape",
169 CornerBottomLeftShape => "corner-bottom-left-shape",
170 BorderTopWidth => "border-top-width",
171 BorderRightWidth => "border-right-width",
172 BorderBottomWidth => "border-bottom-width",
173 BorderLeftWidth => "border-left-width",
174 OverflowX => "overflow-x",
175 OverflowY => "overflow-y",
176 RowGap => "row-gap",
177 ColumnGap => "column-gap",
178 FontSize => "font-size",
179 ObjectPosition => "object-position",
180 AspectRatio => "aspect-ratio",
181 Transform => "transform",
182 Shading => "--shading",
183 All => "all",
184 Other(name) => name,
185 }
186 }
187}
188
189#[derive(Clone, Copy, Debug, PartialEq, Eq)]
190pub enum StepPosition {
191 JumpStart,
192 JumpEnd,
193 JumpNone,
194 JumpBoth,
195}
196
197#[derive(Clone, Copy, Debug, PartialEq)]
198pub enum Easing {
199 Linear,
200 Ease,
201 EaseIn,
202 EaseOut,
203 EaseInOut,
204 CubicBezier(f32, f32, f32, f32),
205 Steps(u32, StepPosition),
206}
207
208impl Default for Easing {
209 fn default() -> Self {
210 Easing::Ease
211 }
212}
213
214impl Easing {
215 pub fn eval(self, t: f32) -> f32 {
216 self.eval_f64(t as f64) as f32
217 }
218
219 pub fn eval_f64(self, t: f64) -> f64 {
221 match self {
222 Easing::Linear => t,
223 Easing::Ease => cubic_bezier(0.25, 0.1, 0.25, 1.0, t),
224 Easing::EaseIn => cubic_bezier(0.42, 0.0, 1.0, 1.0, t),
225 Easing::EaseOut => cubic_bezier(0.0, 0.0, 0.58, 1.0, t),
226 Easing::EaseInOut => cubic_bezier(0.42, 0.0, 0.58, 1.0, t),
227 Easing::CubicBezier(x1, y1, x2, y2) => {
228 cubic_bezier(x1 as f64, y1 as f64, x2 as f64, y2 as f64, t)
229 }
230 Easing::Steps(count, position) => steps(count, position, t),
231 }
232 }
233}
234
235#[derive(Clone, Debug, PartialEq)]
236pub struct TransitionSpec {
237 pub property: TransitionProperty,
238 pub duration: Duration,
239 pub delay: Delay,
240 pub easing: Easing,
241}
242
243impl TransitionSpec {
244 pub fn is_instant(&self) -> bool {
246 self.delay.wait().is_zero() && self.delay.skip() >= self.duration
247 }
248}
249
250pub fn spec_for<'s>(
251 specs: &'s [TransitionSpec],
252 property: &TransitionProperty,
253) -> Option<&'s TransitionSpec> {
254 specs
255 .iter()
256 .rev()
257 .find(|s| s.property == *property || s.property == TransitionProperty::All)
258}
259
260pub fn covered(specs: &[TransitionSpec]) -> Vec<TransitionProperty> {
261 let mut out: Vec<TransitionProperty> = Vec::new();
262 for s in specs {
263 match &s.property {
264 TransitionProperty::All => {
265 for p in TransitionProperty::animatable() {
266 if !out.contains(&p) {
267 out.push(p);
268 }
269 }
270 }
271 TransitionProperty::Other(_) => {}
272 p => {
273 if !out.contains(p) {
274 out.push(p.clone());
275 }
276 }
277 }
278 }
279 out
280}
281
282fn bezier(a: f64, b: f64, t: f64) -> f64 {
283 let mt = 1.0 - t;
284 3.0 * mt * mt * t * a + 3.0 * mt * t * t * b + t * t * t
285}
286
287fn bezier_slope(a: f64, b: f64, t: f64) -> f64 {
288 let mt = 1.0 - t;
289 3.0 * mt * mt * a + 6.0 * mt * t * (b - a) + 3.0 * t * t * (1.0 - b)
290}
291
292fn solve_t_for_x(x1: f64, x2: f64, x: f64) -> f64 {
293 let mut t = x;
294 for _ in 0..8 {
295 let err = bezier(x1, x2, t) - x;
296 if err.abs() < 1e-7 {
297 return t;
298 }
299 let slope = bezier_slope(x1, x2, t);
300 if slope.abs() < 1e-6 {
301 break;
302 }
303 let next = t - err / slope;
304 if !(0.0..=1.0).contains(&next) {
305 break;
306 }
307 t = next;
308 }
309
310 let (mut lo, mut hi) = (0.0f64, 1.0f64);
311 let mut t = x.clamp(0.0, 1.0);
312 for _ in 0..48 {
313 let v = bezier(x1, x2, t);
314 if (v - x).abs() < 1e-7 {
315 return t;
316 }
317 if v < x {
318 lo = t;
319 } else {
320 hi = t;
321 }
322 t = 0.5 * (lo + hi);
323 }
324 t
325}
326
327fn cubic_bezier(x1: f64, y1: f64, x2: f64, y2: f64, t: f64) -> f64 {
328 if t <= 0.0 {
329 return 0.0;
330 }
331 if t >= 1.0 {
332 return 1.0;
333 }
334 let (x1, x2) = (x1.clamp(0.0, 1.0), x2.clamp(0.0, 1.0));
335 bezier(y1, y2, solve_t_for_x(x1, x2, t))
336}
337
338fn steps(count: u32, position: StepPosition, t: f64) -> f64 {
339 let n = count.max(1) as f64;
340 let mut current = (t * n).floor();
341 if matches!(position, StepPosition::JumpStart | StepPosition::JumpBoth) {
342 current += 1.0;
343 }
344 if t >= 0.0 && current < 0.0 {
345 current = 0.0;
346 }
347 let jumps = match position {
348 StepPosition::JumpStart | StepPosition::JumpEnd => n,
349 StepPosition::JumpNone => n - 1.0,
350 StepPosition::JumpBoth => n + 1.0,
351 };
352 if jumps <= 0.0 {
353 return 0.0;
354 }
355 if t <= 1.0 && current > jumps {
356 current = jumps;
357 }
358 current / jumps
359}
360
361#[derive(Clone, Debug, Default, PartialEq)]
362pub(crate) struct Collector {
363 properties: Option<Vec<Vec<TransitionProperty>>>,
364 durations: Option<Vec<Duration>>,
365 delays: Option<Vec<Delay>>,
366 easings: Option<Vec<Easing>>,
367 seen: bool,
368}
369
370impl Collector {
371 pub(crate) fn declarations(&self) -> Option<Rc<Self>> {
372 self.seen.then(|| Rc::new(self.clone()))
373 }
374
375 pub(crate) fn merge(&mut self, later: &Self) {
376 if later.properties.is_some() {
377 self.properties = later.properties.clone();
378 }
379 if later.durations.is_some() {
380 self.durations = later.durations.clone();
381 }
382 if later.delays.is_some() {
383 self.delays = later.delays.clone();
384 }
385 if later.easings.is_some() {
386 self.easings = later.easings.clone();
387 }
388 self.seen |= later.seen;
389 }
390
391 pub(crate) fn from_specs(specs: &[TransitionSpec]) -> Self {
392 Self {
393 properties: Some(
394 specs
395 .iter()
396 .map(|spec| vec![spec.property.clone()])
397 .collect(),
398 ),
399 durations: Some(specs.iter().map(|spec| spec.duration).collect()),
400 delays: Some(specs.iter().map(|spec| spec.delay).collect()),
401 easings: Some(specs.iter().map(|spec| spec.easing).collect()),
402 seen: true,
403 }
404 }
405
406 pub(crate) fn take(&mut self, p: &Property, diagnostics: &mut Vec<String>) -> bool {
407 match p {
408 Property::Transition(list, _) => {
409 self.seen = true;
410 let mut properties = Vec::with_capacity(list.len());
411 let mut durations = Vec::with_capacity(list.len());
412 let mut delays = Vec::with_capacity(list.len());
413 let mut easings = Vec::with_capacity(list.len());
414 for entry in list.iter() {
415 match expand(&entry.property) {
416 Expansion::None => {}
417 Expansion::Props(props) => properties.push(transitioned(props)),
418 }
419 durations.push(duration_of(
420 &entry.duration,
421 "transition-duration",
422 diagnostics,
423 ));
424 delays.push(delay_of(&entry.delay, "transition-delay", diagnostics));
425 easings.push(easing_of(&entry.timing_function, diagnostics));
426 }
427 self.properties = Some(properties);
428 self.durations = Some(durations);
429 self.delays = Some(delays);
430 self.easings = Some(easings);
431 true
432 }
433 Property::TransitionProperty(list, _) => {
434 self.seen = true;
435 let mut properties = Vec::with_capacity(list.len());
436 for id in list.iter() {
437 match expand(id) {
438 Expansion::None => {}
439 Expansion::Props(props) => properties.push(transitioned(props)),
440 }
441 }
442 self.properties = Some(properties);
443 true
444 }
445 Property::TransitionDuration(list, _) => {
446 self.seen = true;
447 self.durations = Some(
448 list.iter()
449 .map(|t| duration_of(t, "transition-duration", diagnostics))
450 .collect(),
451 );
452 true
453 }
454 Property::TransitionDelay(list, _) => {
455 self.seen = true;
456 self.delays = Some(
457 list.iter()
458 .map(|t| delay_of(t, "transition-delay", diagnostics))
459 .collect(),
460 );
461 true
462 }
463 Property::TransitionTimingFunction(list, _) => {
464 self.seen = true;
465 self.easings = Some(list.iter().map(|e| easing_of(e, diagnostics)).collect());
466 true
467 }
468 Property::Unparsed(u) if is_transition_id(&u.property_id) => {
469 self.seen = true;
470 diagnostics.push(format!(
471 "unresolved value for {} (var()/env() in transitions is not resolved yet, v1)",
472 u.property_id.name()
473 ));
474 true
475 }
476 _ => false,
477 }
478 }
479
480 pub(crate) fn finish(self) -> Option<Vec<TransitionSpec>> {
481 if !self.seen {
482 return None;
483 }
484 let entries = self
485 .properties
486 .unwrap_or_else(|| vec![vec![TransitionProperty::All]]);
487 if entries.is_empty() {
488 return Some(Vec::new());
489 }
490 let durations = self.durations.unwrap_or_default();
491 let delays = self.delays.unwrap_or_default();
492 let easings = self.easings.unwrap_or_default();
493
494 fn pick<T: Copy + Default>(list: &[T], i: usize) -> T {
495 if list.is_empty() {
496 T::default()
497 } else {
498 list[i % list.len()]
499 }
500 }
501
502 let mut out = Vec::new();
503 for (i, props) in entries.iter().enumerate() {
504 let d = pick(&durations, i);
505 let delay = pick(&delays, i);
506 let e = if easings.is_empty() {
507 Easing::Ease
508 } else {
509 easings[i % easings.len()]
510 };
511 for property in props {
512 out.push(TransitionSpec {
513 property: property.clone(),
514 duration: d,
515 delay,
516 easing: e,
517 });
518 }
519 }
520 Some(out)
521 }
522}
523
524fn is_transition_id(id: &PropertyId) -> bool {
525 matches!(
526 id,
527 PropertyId::Transition(_)
528 | PropertyId::TransitionProperty(_)
529 | PropertyId::TransitionDuration(_)
530 | PropertyId::TransitionDelay(_)
531 | PropertyId::TransitionTimingFunction(_)
532 )
533}
534
535enum Expansion {
536 None,
537 Props(Vec<TransitionProperty>),
538}
539
540fn transitioned(mut props: Vec<TransitionProperty>) -> Vec<TransitionProperty> {
541 props.retain(|p| !p.is_discrete());
542 props
543}
544
545fn expand(id: &PropertyId) -> Expansion {
546 use TransitionProperty::*;
547 let name = id.name();
548 let one = |p: TransitionProperty| Expansion::Props(vec![p]);
549 match name {
550 "none" => Expansion::None,
551 "all" => one(All),
552 "opacity" => one(Opacity),
553 "color" => one(Color),
554 "background" | "background-color" => one(BackgroundColor),
555 "border" => Expansion::Props(vec![
556 BorderColor,
557 BorderTopWidth,
558 BorderRightWidth,
559 BorderBottomWidth,
560 BorderLeftWidth,
561 ]),
562 "border-color" => one(BorderColor),
563 "border-width" => Expansion::Props(vec![
564 BorderTopWidth,
565 BorderRightWidth,
566 BorderBottomWidth,
567 BorderLeftWidth,
568 ]),
569 "border-top-width" => one(BorderTopWidth),
570 "border-right-width" => one(BorderRightWidth),
571 "border-bottom-width" => one(BorderBottomWidth),
572 "border-left-width" => one(BorderLeftWidth),
573 "overflow" => Expansion::Props(vec![OverflowX, OverflowY]),
574 "overflow-x" => one(OverflowX),
575 "overflow-y" => one(OverflowY),
576 "text-decoration-color" => one(TextDecorationColor),
577 "text-shadow" => one(TextShadow),
578 "fill" => one(Fill),
579 "stroke" => one(Stroke),
580 "width" => one(Width),
581 "height" => one(Height),
582 "min-width" => one(MinWidth),
583 "min-height" => one(MinHeight),
584 "max-width" => one(MaxWidth),
585 "max-height" => one(MaxHeight),
586 "padding" => Expansion::Props(vec![PaddingTop, PaddingRight, PaddingBottom, PaddingLeft]),
587 "padding-top" => one(PaddingTop),
588 "padding-right" => one(PaddingRight),
589 "padding-bottom" => one(PaddingBottom),
590 "padding-left" => one(PaddingLeft),
591 "margin" => Expansion::Props(vec![MarginTop, MarginRight, MarginBottom, MarginLeft]),
592 "margin-top" => one(MarginTop),
593 "margin-right" => one(MarginRight),
594 "margin-bottom" => one(MarginBottom),
595 "margin-left" => one(MarginLeft),
596 "padding-inline" => Expansion::Props(vec![PaddingLeft, PaddingRight]),
597 "padding-block" => Expansion::Props(vec![PaddingTop, PaddingBottom]),
598 "padding-inline-start" => one(PaddingLeft),
599 "padding-inline-end" => one(PaddingRight),
600 "padding-block-start" => one(PaddingTop),
601 "padding-block-end" => one(PaddingBottom),
602 "margin-inline" => Expansion::Props(vec![MarginLeft, MarginRight]),
603 "margin-block" => Expansion::Props(vec![MarginTop, MarginBottom]),
604 "margin-inline-start" => one(MarginLeft),
605 "margin-inline-end" => one(MarginRight),
606 "margin-block-start" => one(MarginTop),
607 "margin-block-end" => one(MarginBottom),
608 "border-radius" => Expansion::Props(vec![
609 BorderTopLeftRadius,
610 BorderTopRightRadius,
611 BorderBottomRightRadius,
612 BorderBottomLeftRadius,
613 ]),
614 "border-top-left-radius" => one(BorderTopLeftRadius),
615 "border-top-right-radius" => one(BorderTopRightRadius),
616 "border-bottom-right-radius" => one(BorderBottomRightRadius),
617 "border-bottom-left-radius" => one(BorderBottomLeftRadius),
618 "corner-shape" => Expansion::Props(vec![
619 CornerTopLeftShape,
620 CornerTopRightShape,
621 CornerBottomRightShape,
622 CornerBottomLeftShape,
623 ]),
624 "corner-top-left-shape" | "corner-start-start-shape" => one(CornerTopLeftShape),
625 "corner-top-right-shape" | "corner-start-end-shape" => one(CornerTopRightShape),
626 "corner-bottom-right-shape" | "corner-end-end-shape" => one(CornerBottomRightShape),
627 "corner-bottom-left-shape" | "corner-end-start-shape" => one(CornerBottomLeftShape),
628 "corner-top-shape" | "corner-block-start-shape" => {
629 Expansion::Props(vec![CornerTopLeftShape, CornerTopRightShape])
630 }
631 "corner-bottom-shape" | "corner-block-end-shape" => {
632 Expansion::Props(vec![CornerBottomLeftShape, CornerBottomRightShape])
633 }
634 "corner-left-shape" | "corner-inline-start-shape" => {
635 Expansion::Props(vec![CornerTopLeftShape, CornerBottomLeftShape])
636 }
637 "corner-right-shape" | "corner-inline-end-shape" => {
638 Expansion::Props(vec![CornerTopRightShape, CornerBottomRightShape])
639 }
640 "gap" => Expansion::Props(vec![RowGap, ColumnGap]),
641 "row-gap" => one(RowGap),
642 "column-gap" => one(ColumnGap),
643 "font-size" => one(FontSize),
644 "object-position" => one(ObjectPosition),
645 "aspect-ratio" => one(AspectRatio),
646 "transform" => one(Transform),
647 "--shading" => one(Shading),
650 other => one(Other(Rc::from(other))),
651 }
652}
653
654pub(crate) fn animates(name: &str) -> bool {
655 match expand(&PropertyId::from(name)) {
656 Expansion::None => false,
657 Expansion::Props(list) => list
658 .iter()
659 .any(|p| !matches!(p, TransitionProperty::All | TransitionProperty::Other(_))),
660 }
661}
662
663pub fn parse_easing(text: &str) -> Option<Easing> {
666 use lightningcss::stylesheet::ParserOptions;
667 let id = PropertyId::from("animation-timing-function");
668 match Property::parse_string(id, text.trim(), ParserOptions::default()).ok()? {
669 Property::AnimationTimingFunction(list, _) if list.len() == 1 => {
670 let mut diagnostics = Vec::new();
671 let easing = easing_of(&list[0], &mut diagnostics);
672 diagnostics.is_empty().then_some(easing)
673 }
674 _ => None,
675 }
676}
677
678pub(crate) fn duration_of(t: &Time, what: &str, diagnostics: &mut Vec<String>) -> Duration {
679 let ms = t.to_ms();
680 if !ms.is_finite() {
681 diagnostics.push(format!("non-finite {what} treated as 0s"));
682 return Duration::ZERO;
683 }
684 if ms < 0.0 {
685 diagnostics.push(format!(
686 "negative {what} ({ms}ms) is not supported yet (v1) — clamped to 0s"
687 ));
688 return Duration::ZERO;
689 }
690 Duration::from_secs_f64((ms as f64 / 1000.0).min(MAX_TIME_SECS))
692}
693
694pub(crate) fn delay_of(t: &Time, what: &str, diagnostics: &mut Vec<String>) -> Delay {
695 let ms = t.to_ms();
696 if !ms.is_finite() {
697 diagnostics.push(format!("non-finite {what} treated as 0s"));
698 return Delay::ZERO;
699 }
700 Delay::from_secs_f64(ms as f64 / 1000.0)
701}
702
703#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
705pub struct Delay {
706 nanos: i64,
707}
708
709impl Delay {
710 pub const ZERO: Delay = Delay { nanos: 0 };
711
712 pub fn from_secs_f64(secs: f64) -> Self {
713 let secs = secs.clamp(-MAX_TIME_SECS, MAX_TIME_SECS);
714 Delay {
715 nanos: (secs * 1e9).round() as i64,
716 }
717 }
718
719 pub fn is_zero(self) -> bool {
720 self.nanos == 0
721 }
722
723 pub fn as_secs_f64(self) -> f64 {
724 self.nanos as f64 / 1e9
725 }
726
727 pub fn wait(self) -> Duration {
729 Duration::from_nanos(self.nanos.max(0) as u64)
730 }
731
732 pub fn skip(self) -> Duration {
734 Duration::from_nanos(self.nanos.min(0).unsigned_abs())
735 }
736
737 pub fn active(self, elapsed: Duration) -> Option<Duration> {
739 let wait = self.wait();
740 (elapsed >= wait).then(|| elapsed - wait + self.skip())
741 }
742
743 pub fn end_after(self, run: Duration) -> Option<Duration> {
745 Some(self.wait().checked_add(run)?.saturating_sub(self.skip()))
746 }
747}
748
749impl From<Duration> for Delay {
750 fn from(d: Duration) -> Self {
751 Delay::from_secs_f64(d.as_secs_f64())
752 }
753}
754
755pub(crate) const MAX_TIME_SECS: f64 = 1.0e9;
756
757pub(crate) fn easing_of(e: &EasingFunction, diagnostics: &mut Vec<String>) -> Easing {
758 match e {
759 EasingFunction::Linear => Easing::Linear,
760 EasingFunction::Ease => Easing::Ease,
761 EasingFunction::EaseIn => Easing::EaseIn,
762 EasingFunction::EaseOut => Easing::EaseOut,
763 EasingFunction::EaseInOut => Easing::EaseInOut,
764 EasingFunction::CubicBezier { x1, y1, x2, y2 } => {
765 if !(0.0..=1.0).contains(x1) || !(0.0..=1.0).contains(x2) {
766 diagnostics.push(format!(
767 "cubic-bezier x control points must be within 0..1 ({x1}, {x2}) — clamped"
768 ));
769 }
770 Easing::CubicBezier(x1.clamp(0.0, 1.0), *y1, x2.clamp(0.0, 1.0), *y2)
771 }
772 EasingFunction::Steps { count, position } => {
773 let position = match position {
774 CssStepPosition::Start => StepPosition::JumpStart,
775 CssStepPosition::End => StepPosition::JumpEnd,
776 CssStepPosition::JumpNone => StepPosition::JumpNone,
777 CssStepPosition::JumpBoth => StepPosition::JumpBoth,
778 };
779 let mut count = (*count).max(1) as u32;
780 if position == StepPosition::JumpNone && count < 2 {
781 diagnostics.push("steps(<2, jump-none) is invalid CSS — treated as 2".into());
782 count = 2;
783 }
784 Easing::Steps(count, position)
785 }
786 }
787}
788
789#[cfg(test)]
790mod tests {
791 use super::*;
792 use lightningcss::declaration::DeclarationBlock;
793 use lightningcss::stylesheet::ParserOptions;
794
795 fn parse(body: &str) -> (Option<Vec<TransitionSpec>>, Vec<String>) {
796 let mut diagnostics = Vec::new();
797 let block = DeclarationBlock::parse_string(body, ParserOptions::default())
798 .expect("declaration block parses");
799 let mut collector = Collector::default();
800 for p in block
801 .declarations
802 .iter()
803 .chain(block.important_declarations.iter())
804 {
805 assert!(
806 collector.take(p, &mut diagnostics),
807 "non-transition property in test body: {p:?}"
808 );
809 }
810 (collector.finish(), diagnostics)
811 }
812
813 fn specs(body: &str) -> Vec<TransitionSpec> {
814 parse(body).0.expect("block declared a transition")
815 }
816
817 fn ms(n: u64) -> Duration {
818 Duration::from_millis(n)
819 }
820
821 #[test]
822 fn shorthand_single_property() {
823 let s = specs("transition: opacity 200ms ease-in 50ms");
824 assert_eq!(
825 s,
826 vec![TransitionSpec {
827 property: TransitionProperty::Opacity,
828 duration: ms(200),
829 delay: ms(50).into(),
830 easing: Easing::EaseIn,
831 }]
832 );
833 }
834
835 #[test]
836 fn logical_margin_and_padding_names_transition_their_physical_sides() {
837 let props = |body: &str| -> Vec<TransitionProperty> {
838 specs(body).into_iter().map(|s| s.property).collect()
839 };
840 use TransitionProperty::*;
841 assert_eq!(
842 props("transition: margin-inline 1s"),
843 vec![MarginLeft, MarginRight]
844 );
845 assert_eq!(
846 props("transition: padding-block 1s"),
847 vec![PaddingTop, PaddingBottom]
848 );
849 assert_eq!(props("transition: margin-inline-end 1s"), vec![MarginRight]);
850 assert_eq!(
851 props("transition: padding-block-start 1s"),
852 vec![PaddingTop]
853 );
854 }
855
856 #[test]
857 fn shorthand_defaults_to_all_with_ease() {
858 let s = specs("transition: 300ms");
859 assert_eq!(s.len(), 1);
860 assert_eq!(s[0].property, TransitionProperty::All);
861 assert_eq!(s[0].duration, ms(300));
862 assert_eq!(s[0].delay, Delay::ZERO);
863 assert_eq!(s[0].easing, Easing::Ease);
864 }
865
866 #[test]
867 fn shorthand_comma_list() {
868 let s = specs("transition: opacity 1s linear, color 2s ease-out 100ms");
869 assert_eq!(s.len(), 2);
870 assert_eq!(s[0].property, TransitionProperty::Opacity);
871 assert_eq!(s[0].duration, Duration::from_secs(1));
872 assert_eq!(s[0].easing, Easing::Linear);
873 assert_eq!(s[1].property, TransitionProperty::Color);
874 assert_eq!(s[1].duration, Duration::from_secs(2));
875 assert_eq!(s[1].delay, ms(100).into());
876 assert_eq!(s[1].easing, Easing::EaseOut);
877 }
878
879 #[test]
880 fn longhands_zip_and_cycle() {
881 let s = specs(
882 "transition-property: opacity, color, width; \
883 transition-duration: 100ms, 200ms; \
884 transition-delay: 10ms; \
885 transition-timing-function: linear, ease-in",
886 );
887 assert_eq!(s.len(), 3);
888 assert_eq!(s[0].duration, ms(100));
889 assert_eq!(s[1].duration, ms(200));
890 assert_eq!(s[2].duration, ms(100));
891 assert!(s.iter().all(|x| x.delay == ms(10).into()));
892 assert_eq!(s[2].easing, Easing::Linear);
893 }
894
895 #[test]
896 fn duration_only_longhand_means_all() {
897 let s = specs("transition-duration: 250ms");
898 assert_eq!(s.len(), 1);
899 assert_eq!(s[0].property, TransitionProperty::All);
900 assert_eq!(s[0].duration, ms(250));
901 }
902
903 #[test]
904 fn transition_none_clears() {
905 assert_eq!(specs("transition: none"), Vec::new());
906 assert_eq!(specs("transition-property: none"), Vec::new());
907 }
908
909 #[test]
910 fn shorthand_resets_earlier_longhands() {
911 let s = specs("transition-duration: 5s; transition: opacity 100ms");
912 assert_eq!(s.len(), 1);
913 assert_eq!(s[0].duration, ms(100));
914 }
915
916 #[test]
917 fn longhand_after_shorthand_overrides_component() {
918 let s = specs("transition: opacity 100ms; transition-duration: 900ms");
919 assert_eq!(s.len(), 1);
920 assert_eq!(s[0].property, TransitionProperty::Opacity);
921 assert_eq!(s[0].duration, ms(900));
922 }
923
924 #[test]
925 fn shorthand_names_expand_to_longhands() {
926 let s = specs("transition: padding 100ms, border-radius 200ms, gap 300ms");
927 let names: Vec<&str> = s.iter().map(|x| x.property.name()).collect();
928 assert_eq!(
929 names,
930 vec![
931 "padding-top",
932 "padding-right",
933 "padding-bottom",
934 "padding-left",
935 "border-top-left-radius",
936 "border-top-right-radius",
937 "border-bottom-right-radius",
938 "border-bottom-left-radius",
939 "row-gap",
940 "column-gap",
941 ]
942 );
943 assert!(s[..4].iter().all(|x| x.duration == ms(100)));
944 assert!(s[4..8].iter().all(|x| x.duration == ms(200)));
945 assert!(s[8..].iter().all(|x| x.duration == ms(300)));
946 }
947
948 #[test]
949 fn a_huge_time_is_capped_and_stays_addable() {
950 let s = specs("transition: opacity 1e20s 1e20s");
951 assert_eq!(s[0].duration, Duration::from_secs(1_000_000_000));
952 assert_eq!(s[0].delay, Duration::from_secs(1_000_000_000).into());
953 let _ = std::time::Instant::now() + s[0].delay.wait() + s[0].duration;
954 }
955
956 #[test]
957 fn a_negative_delay_is_kept() {
958 let (s, _) = parse("transition: opacity 1s -200ms");
959 assert_eq!(s.unwrap()[0].delay.skip(), ms(200));
960 }
961
962 #[test]
963 fn spec_for_prefers_the_last_matching_entry() {
964 let s = specs("transition: all 1s, opacity 2s");
965 let opacity = spec_for(&s, &TransitionProperty::Opacity).unwrap();
966 assert_eq!(opacity.duration, Duration::from_secs(2));
967 let color = spec_for(&s, &TransitionProperty::Color).unwrap();
968 assert_eq!(color.duration, Duration::from_secs(1));
969 assert!(spec_for(&s, &TransitionProperty::Width).is_some());
970 }
971
972 #[test]
973 fn covered_expands_all_and_skips_unsupported() {
974 let s = specs("transition: all 1s, transform 1s");
975 assert_eq!(covered(&s).len(), ANIMATABLE_COUNT);
976 let s = specs("transition: filter 1s");
977 assert!(covered(&s).is_empty());
978 let s = specs("transition: transform 1s");
979 assert_eq!(covered(&s), vec![TransitionProperty::Transform]);
980 let s = specs("transition: opacity 1s, opacity 2s");
981 assert_eq!(covered(&s), vec![TransitionProperty::Opacity]);
982 }
983
984 #[test]
985 fn border_widths_transition_and_overflow_does_not() {
986 let s = specs("transition: border-width 1s, overflow 1s");
987 assert_eq!(
988 covered(&s),
989 vec![
990 TransitionProperty::BorderTopWidth,
991 TransitionProperty::BorderRightWidth,
992 TransitionProperty::BorderBottomWidth,
993 TransitionProperty::BorderLeftWidth,
994 ]
995 );
996 assert!(!covered(&specs("transition: all 1s")).contains(&TransitionProperty::OverflowX));
997 assert!(animates("overflow") && animates("border-top-width"));
998 }
999
1000 const EPS: f32 = 1e-3;
1001
1002 #[test]
1003 fn script_easing_keeps_double_progress_and_step_boundaries() {
1004 let progress = 0.123456789123;
1005 assert_eq!(Easing::Linear.eval_f64(progress), progress);
1006 let step = Easing::Steps(10, StepPosition::JumpEnd);
1007 assert_eq!(step.eval_f64(0.3 - 1e-12), 0.2);
1008 assert_eq!(step.eval_f64(0.3), 0.3);
1009 assert!(
1010 (Easing::Ease.eval_f64(0.5) - Easing::CubicBezier(0.25, 0.1, 0.25, 1.0).eval_f64(0.5))
1011 .abs()
1012 < 1e-8
1013 );
1014 }
1015
1016 #[test]
1017 fn easing_endpoints_are_exact() {
1018 for e in [
1019 Easing::Linear,
1020 Easing::Ease,
1021 Easing::EaseIn,
1022 Easing::EaseOut,
1023 Easing::EaseInOut,
1024 Easing::CubicBezier(0.7, -0.4, 0.3, 1.4),
1025 ] {
1026 assert_eq!(e.eval(0.0), 0.0, "{e:?}");
1027 assert_eq!(e.eval(1.0), 1.0, "{e:?}");
1028 }
1029 }
1030
1031 #[test]
1032 fn cubic_bezier_matches_known_values() {
1033 assert!((Easing::Ease.eval(0.5) - 0.802_4).abs() < EPS);
1034 assert!((Easing::EaseIn.eval(0.5) - 0.315_4).abs() < EPS);
1035 assert!((Easing::EaseOut.eval(0.5) - 0.684_6).abs() < EPS);
1036 assert!((Easing::EaseInOut.eval(0.5) - 0.5).abs() < EPS);
1037 for t in [0.1, 0.25, 0.5, 0.75, 0.9] {
1038 assert!(
1039 (Easing::Ease.eval(t) - Easing::CubicBezier(0.25, 0.1, 0.25, 1.0).eval(t)).abs()
1040 < 1e-5
1041 );
1042 }
1043 }
1044
1045 #[test]
1046 fn cubic_bezier_identity_and_monotonicity() {
1047 let identity = Easing::CubicBezier(1.0 / 3.0, 1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0);
1048 for i in 0..=20 {
1049 let t = i as f32 / 20.0;
1050 assert!((identity.eval(t) - t).abs() < EPS, "t={t}");
1051 }
1052 let mut prev = -1.0;
1053 for i in 0..=100 {
1054 let v = Easing::Ease.eval(i as f32 / 100.0);
1055 assert!(v >= prev - 1e-6, "ease is not monotonic at {i}");
1056 prev = v;
1057 }
1058 }
1059
1060 #[test]
1061 fn cubic_bezier_solver_agrees_with_brute_force() {
1062 let (x1, y1, x2, y2) = (0.68, -0.55, 0.265, 1.55);
1063 let curve = Easing::CubicBezier(x1, y1, x2, y2);
1064 for i in 1..100 {
1065 let x = i as f64 / 100.0;
1066 let mut best = (f64::MAX, 0.0f64);
1067 for j in 0..=200_000 {
1068 let s = j as f64 / 200_000.0;
1069 let d = (bezier(x1 as f64, x2 as f64, s) - x).abs();
1070 if d < best.0 {
1071 best = (d, s);
1072 }
1073 }
1074 let reference = bezier(y1 as f64, y2 as f64, best.1);
1075 assert!(
1076 (curve.eval_f64(x) - reference).abs() < 2e-3,
1077 "x={x}: {} vs {reference}",
1078 curve.eval_f64(x)
1079 );
1080 }
1081 }
1082
1083 #[test]
1084 fn cubic_bezier_can_overshoot() {
1085 let overshoot = Easing::CubicBezier(0.34, 1.56, 0.64, 1.0);
1086 assert!((1..100).any(|i| overshoot.eval(i as f32 / 100.0) > 1.0));
1087 }
1088
1089 #[test]
1090 fn steps_follow_the_css_algorithm() {
1091 let start = Easing::Steps(4, StepPosition::JumpStart);
1092 assert_eq!(start.eval(0.0), 0.25);
1093 assert_eq!(start.eval(0.24), 0.25);
1094 assert_eq!(start.eval(0.26), 0.5);
1095 assert_eq!(start.eval(1.0), 1.0);
1096
1097 let end = Easing::Steps(4, StepPosition::JumpEnd);
1098 assert_eq!(end.eval(0.0), 0.0);
1099 assert_eq!(end.eval(0.24), 0.0);
1100 assert_eq!(end.eval(0.26), 0.25);
1101 assert_eq!(end.eval(0.99), 0.75);
1102 assert_eq!(end.eval(1.0), 1.0);
1103
1104 let none = Easing::Steps(3, StepPosition::JumpNone);
1105 assert_eq!(none.eval(0.0), 0.0);
1106 assert_eq!(none.eval(0.5), 0.5);
1107 assert_eq!(none.eval(1.0), 1.0);
1108
1109 let both = Easing::Steps(3, StepPosition::JumpBoth);
1110 assert!((both.eval(0.0) - 0.25).abs() < 1e-6);
1111 assert!((both.eval(0.5) - 0.5).abs() < 1e-6);
1112 assert_eq!(both.eval(1.0), 1.0);
1113 }
1114
1115 #[test]
1116 fn step_keywords_and_invalid_counts() {
1117 let s = specs("transition: opacity 1s step-start");
1118 assert_eq!(s[0].easing, Easing::Steps(1, StepPosition::JumpStart));
1119 let s = specs("transition: opacity 1s step-end");
1120 assert_eq!(s[0].easing, Easing::Steps(1, StepPosition::JumpEnd));
1121
1122 let (s, _) = parse("transition: opacity 1s steps(1, jump-none)");
1123 assert_eq!(
1124 s.unwrap()[0].easing,
1125 Easing::Steps(2, StepPosition::JumpNone)
1126 );
1127 }
1128
1129 #[test]
1130 fn out_of_range_bezier_x_is_clamped() {
1131 let (s, _) = parse("transition: opacity 1s cubic-bezier(1.5, 0, -0.2, 1)");
1132 assert_eq!(
1133 s.unwrap()[0].easing,
1134 Easing::CubicBezier(1.0, 0.0, 0.0, 1.0)
1135 );
1136 }
1137}