Skip to main content

sk_css/
transition.rs

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