1use std::cell::RefCell;
6use std::collections::{HashMap, HashSet};
7use std::rc::Rc;
8use std::time::{Duration, Instant};
9
10use gpui::{
11 AbsoluteLength, DefiniteLength, EffectCrossFade, EffectSpec, Hsla, Interpolate, Length, Pixels,
12 Rems, StyleRefinement, TransformSpec,
13};
14
15use crate::keyframes::{AnimationSpec, FillMode, Keyframes, Phase, PlayState};
16use crate::transition::{covered, spec_for, Delay, Easing, TransitionProperty, TransitionSpec};
17use crate::ComputedStates;
18
19#[derive(Clone, Copy, Debug, PartialEq)]
20enum Animatable {
21 Number(f32),
22 Color(Hsla),
23 BorderColors([Hsla; 4]),
24 Pixels(Pixels),
25 Rems(Rems),
26 Effect(EffectSpec),
29 EffectFade(EffectSpec, EffectSpec, f32),
31 Transform(TransformSpec),
32 Overflow(gpui::Overflow),
33 ObjectPosition(gpui::ObjectPosition),
34 TextShadows(TextShadows),
35}
36
37const MAX_ANIMATED_TEXT_SHADOWS: usize = 4;
39
40#[derive(Clone, Copy, Debug)]
43struct TextShadows {
44 shadows: [gpui::TextShadow; MAX_ANIMATED_TEXT_SHADOWS],
45 len: usize,
46 current: Hsla,
47}
48
49impl TextShadows {
50 fn new(list: &[gpui::TextShadow], current: Hsla) -> Option<Self> {
51 if list.len() > MAX_ANIMATED_TEXT_SHADOWS {
52 return None;
53 }
54 let mut shadows = [gpui::TextShadow::default(); MAX_ANIMATED_TEXT_SHADOWS];
55 shadows[..list.len()].copy_from_slice(list);
56 Some(Self {
57 shadows,
58 len: list.len(),
59 current,
60 })
61 }
62
63 fn list(&self) -> &[gpui::TextShadow] {
64 &self.shadows[..self.len]
65 }
66}
67
68impl PartialEq for TextShadows {
70 fn eq(&self, other: &Self) -> bool {
71 self.list() == other.list()
72 }
73}
74
75#[derive(Clone, Copy, Debug, PartialEq)]
76enum Opaque {
77 Auto,
78 Fraction(f32),
79 Calc(f32, f32),
80 NonSolidFill,
81 UnpaintedSvg,
83 SvgColour(Hsla),
86 LongTextShadowList,
88}
89
90#[derive(Clone, Copy, Debug, PartialEq)]
91enum Slot {
92 Missing,
93 Value(Animatable),
94 Opaque(Opaque),
95}
96
97fn from_absolute(a: AbsoluteLength) -> Animatable {
98 match a {
99 AbsoluteLength::Pixels(p) => Animatable::Pixels(p),
100 AbsoluteLength::Rems(r) => Animatable::Rems(r),
101 }
102}
103
104fn to_absolute(v: Animatable) -> Option<AbsoluteLength> {
105 match v {
106 Animatable::Pixels(p) => Some(AbsoluteLength::Pixels(p)),
107 Animatable::Rems(r) => Some(AbsoluteLength::Rems(r)),
108 _ => None,
109 }
110}
111
112fn slot_absolute(v: Option<AbsoluteLength>) -> Slot {
113 v.map_or(Slot::Missing, |a| Slot::Value(from_absolute(a)))
114}
115
116fn slot_definite(v: Option<DefiniteLength>) -> Slot {
117 match v {
118 None => Slot::Missing,
119 Some(DefiniteLength::Absolute(a)) => Slot::Value(from_absolute(a)),
120 Some(DefiniteLength::Fraction(f)) => Slot::Opaque(Opaque::Fraction(f)),
121 Some(DefiniteLength::Calc { fraction, pixels }) => {
122 Slot::Opaque(Opaque::Calc(fraction, f32::from(pixels)))
123 }
124 }
125}
126
127fn slot_length(v: Option<Length>) -> Slot {
128 match v {
129 None => Slot::Missing,
130 Some(Length::Auto) => Slot::Opaque(Opaque::Auto),
131 Some(Length::Definite(d)) => slot_definite(Some(d)),
132 }
133}
134
135fn slot_color(v: Option<Hsla>) -> Slot {
136 v.map_or(Slot::Missing, |c| Slot::Value(Animatable::Color(c)))
137}
138
139fn slot_text_shadow(r: &StyleRefinement, current: Hsla) -> Slot {
140 match &r.text.text_shadow {
141 None => Slot::Missing,
142 Some(list) => TextShadows::new(list, current)
143 .map_or(Slot::Opaque(Opaque::LongTextShadowList), |shadows| {
144 Slot::Value(Animatable::TextShadows(shadows))
145 }),
146 }
147}
148
149fn slot_of(r: &StyleRefinement, p: &TransitionProperty) -> Slot {
150 use TransitionProperty::*;
151 match p {
152 Opacity => r
153 .opacity
154 .map_or(Slot::Missing, |o| Slot::Value(Animatable::Number(o))),
155 Color => slot_color(r.text.color),
156 BackgroundColor => match &r.background {
157 None => Slot::Missing,
158 Some(gpui::Fill::Color(bg)) => match bg.as_solid() {
159 Some(c) => Slot::Value(Animatable::Color(c)),
160 None => Slot::Opaque(Opaque::NonSolidFill),
161 },
162 },
163 BorderColor => {
164 let side_colors = [
165 &r.vn_border_colors.top,
166 &r.vn_border_colors.right,
167 &r.vn_border_colors.bottom,
168 &r.vn_border_colors.left,
169 ];
170 if r.border_color.is_none() && side_colors.iter().all(|color| color.is_none()) {
171 Slot::Missing
172 } else {
173 let fallback = r.border_color.unwrap_or_default();
174 let colors = side_colors.map(|color| color.flatten().unwrap_or(fallback));
175 if colors.iter().all(|color| *color == colors[0]) {
176 Slot::Value(Animatable::Color(colors[0]))
177 } else {
178 Slot::Value(Animatable::BorderColors(colors))
179 }
180 }
181 }
182 TextDecorationColor => slot_color(
183 r.text
184 .underline
185 .as_ref()
186 .and_then(|u| u.color)
187 .or_else(|| r.text.strikethrough.as_ref().and_then(|st| st.color)),
188 ),
189 TextShadow => slot_text_shadow(r, r.text.color.unwrap_or_else(gpui::black)),
190 Fill | Stroke => Slot::Missing,
193 Width => slot_length(r.size.width),
194 Height => slot_length(r.size.height),
195 MinWidth => slot_length(r.min_size.width),
196 MinHeight => slot_length(r.min_size.height),
197 MaxWidth => slot_length(r.max_size.width),
198 MaxHeight => slot_length(r.max_size.height),
199 PaddingTop => slot_definite(r.padding.top),
200 PaddingRight => slot_definite(r.padding.right),
201 PaddingBottom => slot_definite(r.padding.bottom),
202 PaddingLeft => slot_definite(r.padding.left),
203 MarginTop => slot_length(r.margin.top),
204 MarginRight => slot_length(r.margin.right),
205 MarginBottom => slot_length(r.margin.bottom),
206 MarginLeft => slot_length(r.margin.left),
207 BorderTopLeftRadius => slot_absolute(r.corner_radii.top_left),
208 BorderTopRightRadius => slot_absolute(r.corner_radii.top_right),
209 BorderBottomRightRadius => slot_absolute(r.corner_radii.bottom_right),
210 BorderBottomLeftRadius => slot_absolute(r.corner_radii.bottom_left),
211 BorderTopWidth => slot_absolute(r.border_widths.top),
212 BorderRightWidth => slot_absolute(r.border_widths.right),
213 BorderBottomWidth => slot_absolute(r.border_widths.bottom),
214 BorderLeftWidth => slot_absolute(r.border_widths.left),
215 OverflowX => r
216 .overflow
217 .x
218 .map_or(Slot::Missing, |o| Slot::Value(Animatable::Overflow(o))),
219 OverflowY => r
220 .overflow
221 .y
222 .map_or(Slot::Missing, |o| Slot::Value(Animatable::Overflow(o))),
223 RowGap => slot_definite(r.gap.height),
224 ColumnGap => slot_definite(r.gap.width),
225 FontSize => slot_absolute(r.text.font_size),
226 ObjectPosition => r.vn_object_position.map_or(Slot::Missing, |o| {
227 Slot::Value(Animatable::ObjectPosition(o))
228 }),
229 Shading => r
230 .vn_effect
231 .map_or(Slot::Missing, |e| Slot::Value(Animatable::Effect(e))),
232 Transform => r
233 .vn_transform
234 .map_or(Slot::Missing, |t| Slot::Value(Animatable::Transform(t))),
235 All | Other(_) => Slot::Missing,
236 }
237}
238
239fn slot_inherited(
243 r: &StyleRefinement,
244 p: &TransitionProperty,
245 inherited: Option<Hsla>,
246 extras: &crate::Extras,
247) -> Slot {
248 use TransitionProperty::*;
249 match p {
250 Color => match slot_of(r, p) {
251 Slot::Missing => slot_color(inherited),
252 slot => slot,
253 },
254 Fill => slot_paint(extras.fill, r.text.color.or(inherited)),
258 Stroke => slot_paint(extras.stroke, r.text.color.or(inherited)),
259 TextDecorationColor => match slot_of(r, p) {
260 Slot::Missing if r.text.underline.is_some() || r.text.strikethrough.is_some() => {
261 slot_color(r.text.color.or(inherited))
262 }
263 slot => slot,
264 },
265 TextShadow => slot_text_shadow(r, r.text.color.or(inherited).unwrap_or_else(gpui::black)),
266 _ => slot_of(r, p),
267 }
268}
269
270fn slot_paint(paint: Option<crate::SvgPaint>, color: Option<Hsla>) -> Slot {
271 match paint {
272 None => Slot::Missing,
273 Some(crate::SvgPaint::None) => Slot::Opaque(Opaque::UnpaintedSvg),
274 Some(crate::SvgPaint::Color(c)) => Slot::Opaque(Opaque::SvgColour(c)),
275 Some(_) => slot_color(color),
276 }
277}
278
279fn install(r: &mut StyleRefinement, base: &StyleRefinement, p: &TransitionProperty, v: Animatable) {
280 use TransitionProperty::*;
281 let definite = || to_absolute(v).map(DefiniteLength::Absolute);
282 let length = || to_absolute(v).map(|a| Length::Definite(DefiniteLength::Absolute(a)));
283 let color = || match v {
284 Animatable::Color(c) => Some(c),
285 _ => None,
286 };
287 match p {
288 Opacity => {
289 if let Animatable::Number(n) = v {
290 r.opacity = Some(n.clamp(0.0, 1.0));
293 }
294 }
295 Color => r.text.color = color(),
296 BackgroundColor => r.background = color().map(|c| gpui::Fill::Color(c.into())),
297 BorderColor => match v {
298 Animatable::BorderColors(colors) => {
299 r.border_color = Some(colors[0]);
300 r.vn_border_colors.top = Some(Some(colors[0]));
301 r.vn_border_colors.right = Some(Some(colors[1]));
302 r.vn_border_colors.bottom = Some(Some(colors[2]));
303 r.vn_border_colors.left = Some(Some(colors[3]));
304 }
305 Animatable::Color(color) => {
306 r.border_color = Some(color);
307 r.vn_border_colors = gpui::EdgesRefinement {
308 top: Some(None),
309 right: Some(None),
310 bottom: Some(None),
311 left: Some(None),
312 };
313 }
314 _ => {}
315 },
316 TextDecorationColor => {
320 if let Some(c) = color() {
321 if let Some(mut u) = r
322 .text
323 .underline
324 .clone()
325 .or_else(|| base.text.underline.clone())
326 {
327 u.color = Some(c);
328 r.text.underline = Some(u);
329 }
330 if let Some(mut st) = r
331 .text
332 .strikethrough
333 .clone()
334 .or_else(|| base.text.strikethrough.clone())
335 {
336 st.color = Some(c);
337 r.text.strikethrough = Some(st);
338 }
339 }
340 }
341 TextShadow => {
342 if let Animatable::TextShadows(shadows) = v {
343 r.text.text_shadow = Some(shadows.list().to_vec());
344 }
345 }
346 Fill | Stroke => r.text.color = color().or(r.text.color),
347 Width => r.size.width = length(),
348 Height => r.size.height = length(),
349 MinWidth => r.min_size.width = length(),
350 MinHeight => r.min_size.height = length(),
351 MaxWidth => r.max_size.width = length(),
352 MaxHeight => r.max_size.height = length(),
353 PaddingTop => r.padding.top = definite(),
354 PaddingRight => r.padding.right = definite(),
355 PaddingBottom => r.padding.bottom = definite(),
356 PaddingLeft => r.padding.left = definite(),
357 MarginTop => r.margin.top = length(),
358 MarginRight => r.margin.right = length(),
359 MarginBottom => r.margin.bottom = length(),
360 MarginLeft => r.margin.left = length(),
361 BorderTopLeftRadius => r.corner_radii.top_left = to_absolute(v),
362 BorderTopRightRadius => r.corner_radii.top_right = to_absolute(v),
363 BorderBottomRightRadius => r.corner_radii.bottom_right = to_absolute(v),
364 BorderBottomLeftRadius => r.corner_radii.bottom_left = to_absolute(v),
365 BorderTopWidth => r.border_widths.top = to_absolute(v),
366 BorderRightWidth => r.border_widths.right = to_absolute(v),
367 BorderBottomWidth => r.border_widths.bottom = to_absolute(v),
368 BorderLeftWidth => r.border_widths.left = to_absolute(v),
369 OverflowX | OverflowY => {
370 if let Animatable::Overflow(o) = v {
371 if matches!(p, OverflowX) {
372 r.overflow.x = Some(o);
373 } else {
374 r.overflow.y = Some(o);
375 }
376 }
377 }
378 RowGap => r.gap.height = definite(),
379 ColumnGap => r.gap.width = definite(),
380 FontSize => r.text.font_size = to_absolute(v),
381 ObjectPosition => {
382 if let Animatable::ObjectPosition(o) = v {
383 r.vn_object_position = Some(o);
384 }
385 }
386 Shading => match v {
387 Animatable::Effect(spec) => {
388 r.vn_effect = Some(spec);
389 r.vn_effect_fade = None;
390 }
391 Animatable::EffectFade(from, to, progress) => {
392 r.vn_effect = Some(to);
393 r.vn_effect_fade = Some(EffectCrossFade { from, progress });
394 }
395 _ => {}
396 },
397 Transform => {
398 if let Animatable::Transform(spec) = v {
399 r.vn_transform = Some(spec);
400 }
401 }
402 All | Other(_) => {}
403 }
404}
405
406fn clear(r: &mut StyleRefinement, p: &TransitionProperty) {
407 use TransitionProperty::*;
408 match p {
409 Opacity => r.opacity = None,
410 Color => r.text.color = None,
411 TextDecorationColor => {
412 if let Some(u) = r.text.underline.as_mut() {
413 u.color = None;
414 }
415 if let Some(st) = r.text.strikethrough.as_mut() {
416 st.color = None;
417 }
418 }
419 TextShadow => r.text.text_shadow = None,
420 Fill | Stroke => {}
424 BackgroundColor => r.background = None,
425 BorderColor => {
426 r.border_color = None;
427 r.vn_border_colors = Default::default();
428 }
429 Width => r.size.width = None,
430 Height => r.size.height = None,
431 MinWidth => r.min_size.width = None,
432 MinHeight => r.min_size.height = None,
433 MaxWidth => r.max_size.width = None,
434 MaxHeight => r.max_size.height = None,
435 PaddingTop => r.padding.top = None,
436 PaddingRight => r.padding.right = None,
437 PaddingBottom => r.padding.bottom = None,
438 PaddingLeft => r.padding.left = None,
439 MarginTop => r.margin.top = None,
440 MarginRight => r.margin.right = None,
441 MarginBottom => r.margin.bottom = None,
442 MarginLeft => r.margin.left = None,
443 BorderTopLeftRadius => r.corner_radii.top_left = None,
444 BorderTopRightRadius => r.corner_radii.top_right = None,
445 BorderBottomRightRadius => r.corner_radii.bottom_right = None,
446 BorderBottomLeftRadius => r.corner_radii.bottom_left = None,
447 BorderTopWidth => r.border_widths.top = None,
448 BorderRightWidth => r.border_widths.right = None,
449 BorderBottomWidth => r.border_widths.bottom = None,
450 BorderLeftWidth => r.border_widths.left = None,
451 OverflowX => r.overflow.x = None,
452 OverflowY => r.overflow.y = None,
453 RowGap => r.gap.height = None,
454 ColumnGap => r.gap.width = None,
455 FontSize => r.text.font_size = None,
456 ObjectPosition => r.vn_object_position = None,
457 Shading => {
458 r.vn_effect = None;
459 r.vn_effect_fade = None;
460 }
461 Transform => r.vn_transform = None,
462 All | Other(_) => {}
463 }
464}
465
466fn copy_property(dst: &mut StyleRefinement, src: &StyleRefinement, p: &TransitionProperty) {
467 use TransitionProperty::*;
468 match p {
469 Opacity => dst.opacity = src.opacity,
470 Color => dst.text.color = src.text.color,
471 TextDecorationColor => {
472 dst.text.underline = src.text.underline.clone();
473 dst.text.strikethrough = src.text.strikethrough.clone();
474 }
475 TextShadow => dst.text.text_shadow = src.text.text_shadow.clone(),
476 Fill | Stroke => {}
477 BackgroundColor => dst.background = src.background.clone(),
478 BorderColor => {
479 dst.border_color = src.border_color;
480 dst.vn_border_colors = src.vn_border_colors.clone();
481 }
482 Width => dst.size.width = src.size.width,
483 Height => dst.size.height = src.size.height,
484 MinWidth => dst.min_size.width = src.min_size.width,
485 MinHeight => dst.min_size.height = src.min_size.height,
486 MaxWidth => dst.max_size.width = src.max_size.width,
487 MaxHeight => dst.max_size.height = src.max_size.height,
488 PaddingTop => dst.padding.top = src.padding.top,
489 PaddingRight => dst.padding.right = src.padding.right,
490 PaddingBottom => dst.padding.bottom = src.padding.bottom,
491 PaddingLeft => dst.padding.left = src.padding.left,
492 MarginTop => dst.margin.top = src.margin.top,
493 MarginRight => dst.margin.right = src.margin.right,
494 MarginBottom => dst.margin.bottom = src.margin.bottom,
495 MarginLeft => dst.margin.left = src.margin.left,
496 BorderTopLeftRadius => dst.corner_radii.top_left = src.corner_radii.top_left,
497 BorderTopRightRadius => dst.corner_radii.top_right = src.corner_radii.top_right,
498 BorderBottomRightRadius => dst.corner_radii.bottom_right = src.corner_radii.bottom_right,
499 BorderBottomLeftRadius => dst.corner_radii.bottom_left = src.corner_radii.bottom_left,
500 BorderTopWidth => dst.border_widths.top = src.border_widths.top,
501 BorderRightWidth => dst.border_widths.right = src.border_widths.right,
502 BorderBottomWidth => dst.border_widths.bottom = src.border_widths.bottom,
503 BorderLeftWidth => dst.border_widths.left = src.border_widths.left,
504 OverflowX => dst.overflow.x = src.overflow.x,
505 OverflowY => dst.overflow.y = src.overflow.y,
506 RowGap => dst.gap.height = src.gap.height,
507 ColumnGap => dst.gap.width = src.gap.width,
508 FontSize => dst.text.font_size = src.text.font_size,
509 ObjectPosition => dst.vn_object_position = src.vn_object_position,
510 Shading => {
511 dst.vn_effect = src.vn_effect;
512 dst.vn_effect_fade = src.vn_effect_fade;
513 }
514 Transform => dst.vn_transform = src.vn_transform,
515 All | Other(_) => {}
516 }
517}
518
519pub fn strip_transitioned(
520 rung: &StyleRefinement,
521 transitions: &[TransitionSpec],
522) -> Option<StyleRefinement> {
523 if transitions.is_empty() {
524 return None;
525 }
526 let properties = covered(transitions);
527 let mut out = rung.clone();
528 let mut touched = false;
529 for p in &properties {
530 if !matches!(slot_of(rung, p), Slot::Missing) {
531 clear(&mut out, p);
532 touched = true;
533 }
534 }
535 touched.then_some(out)
536}
537
538fn initial(p: &TransitionProperty) -> Option<Animatable> {
539 use TransitionProperty::*;
540 match p {
541 Opacity => Some(Animatable::Number(1.0)),
542 BackgroundColor => Some(Animatable::Color(Hsla {
543 h: 0.0,
544 s: 0.0,
545 l: 0.0,
546 a: 0.0,
547 })),
548 PaddingTop
549 | PaddingRight
550 | PaddingBottom
551 | PaddingLeft
552 | MarginTop
553 | MarginRight
554 | MarginBottom
555 | MarginLeft
556 | BorderTopLeftRadius
557 | BorderTopRightRadius
558 | BorderBottomRightRadius
559 | BorderBottomLeftRadius
560 | BorderTopWidth
561 | BorderRightWidth
562 | BorderBottomWidth
563 | BorderLeftWidth
564 | RowGap
565 | ColumnGap => Some(Animatable::Pixels(Pixels::from(0.0))),
566 OverflowX | OverflowY => Some(Animatable::Overflow(gpui::Overflow::Visible)),
567 Transform => Some(Animatable::Transform(TransformSpec::IDENTITY)),
568 ObjectPosition => Some(Animatable::ObjectPosition(gpui::ObjectPosition::default())),
569 Shading => Some(Animatable::Effect(EffectSpec::NONE)),
570 TextShadow => TextShadows::new(&[], gpui::black()).map(Animatable::TextShadows),
571 _ => None,
572 }
573}
574
575fn unify(a: Animatable, b: Animatable) -> Option<(Animatable, Animatable)> {
576 use Animatable::*;
577 match (a, b) {
578 (Number(_), Number(_))
579 | (Color(_), Color(_))
580 | (Pixels(_), Pixels(_))
581 | (Rems(_), Rems(_)) => Some((a, b)),
582 (BorderColors(_), BorderColors(_)) => Some((a, b)),
583 (Color(color), BorderColors(colors)) => {
584 Some((BorderColors([color; 4]), BorderColors(colors)))
585 }
586 (BorderColors(colors), Color(color)) => {
587 Some((BorderColors(colors), BorderColors([color; 4])))
588 }
589 (Effect(_), Effect(_)) | (EffectFade(..), Effect(_)) => Some((a, b)),
590 (Transform(_), Transform(_)) => Some((a, b)),
591 (ObjectPosition(_), ObjectPosition(_)) => Some((a, b)),
592 (TextShadows(_), TextShadows(_)) => Some((a, b)),
593 (Pixels(p), Rems(r)) if r.0 == 0.0 => Some((Pixels(p), Pixels(gpui::Pixels::from(0.0)))),
594 (Pixels(p), Rems(r)) if p.as_f32() == 0.0 => Some((Rems(gpui::Rems(0.0)), Rems(r))),
595 (Rems(r), Pixels(p)) if p.as_f32() == 0.0 => Some((Rems(r), Rems(gpui::Rems(0.0)))),
596 (Rems(r), Pixels(p)) if r.0 == 0.0 => Some((Pixels(gpui::Pixels::from(0.0)), Pixels(p))),
597 _ => None,
598 }
599}
600
601fn lerp(from: Animatable, to: Animatable, t: f32) -> Animatable {
602 use Animatable::*;
603 match (from, to) {
604 (Number(a), Number(b)) => Number(f32::interpolate(a, b, t)),
605 (Color(a), Color(b)) => Color(lerp_color(a, b, t)),
606 (BorderColors(a), BorderColors(b)) => BorderColors(std::array::from_fn(|index| {
607 lerp_color(a[index], b[index], t)
608 })),
609 (Pixels(a), Pixels(b)) => Pixels(gpui::Pixels::interpolate(a, b, t)),
610 (Rems(a), Rems(b)) => Rems(gpui::Rems::interpolate(a, b, t)),
611 (Effect(a), Effect(b)) if a.interpolates_with(&b) => Effect(lerp_effect(a, b, t)),
612 (Effect(a), Effect(b)) => EffectFade(a, b, t),
613 (EffectFade(x, y, s), Effect(c)) if c.interpolates_with(&y) => {
616 EffectFade(x, lerp_effect(y, c, t), s + (1.0 - s) * t)
617 }
618 (EffectFade(x, y, s), Effect(c)) if c.interpolates_with(&x) => {
619 EffectFade(y, lerp_effect(x, c, t), (1.0 - s) + s * t)
620 }
621 (EffectFade(x, y, s), Effect(c)) => {
622 lerp(Effect(if s >= 0.5 { y } else { x }), Effect(c), t)
623 }
624 (Transform(a), Transform(b)) => Transform(a.interpolate(b, t)),
625 (ObjectPosition(a), ObjectPosition(b)) => ObjectPosition(gpui::ObjectPosition {
626 x_fraction: f32::interpolate(a.x_fraction, b.x_fraction, t),
627 x_offset: gpui::Pixels::interpolate(a.x_offset, b.x_offset, t),
628 y_fraction: f32::interpolate(a.y_fraction, b.y_fraction, t),
629 y_offset: gpui::Pixels::interpolate(a.y_offset, b.y_offset, t),
630 }),
631 (TextShadows(a), TextShadows(b)) => TextShadows(lerp_text_shadows(a, b, t)),
632 _ => to,
633 }
634}
635
636fn lerp_text_shadows(from: TextShadows, to: TextShadows, t: f32) -> TextShadows {
638 let len = from.len.max(to.len);
639 let mut out = to;
640 out.len = len;
641 for index in 0..len {
642 let pick = |shadows: &TextShadows, other: &TextShadows| match shadows.list().get(index) {
643 Some(shadow) => (*shadow, shadow.color.unwrap_or(shadows.current)),
644 None => {
645 let color = other.list()[index]
646 .color
647 .unwrap_or(other.current)
648 .opacity(0.0);
649 (gpui::TextShadow::default(), color)
650 }
651 };
652 let (a, a_color) = pick(&from, &to);
653 let (b, b_color) = pick(&to, &from);
654 out.shadows[index] = gpui::TextShadow {
655 color: match (from.list().get(index), to.list().get(index)) {
656 (Some(x), Some(y)) if x.color.is_none() && y.color.is_none() => None,
657 _ => Some(lerp_color(a_color, b_color, t)),
658 },
659 offset: gpui::point(
660 Pixels::interpolate(a.offset.x, b.offset.x, t),
661 Pixels::interpolate(a.offset.y, b.offset.y, t),
662 ),
663 blur_radius: Pixels::interpolate(a.blur_radius, b.blur_radius, t).max(gpui::px(0.)),
664 };
665 }
666 out
667}
668
669fn lerp_effect(a: EffectSpec, b: EffectSpec, t: f32) -> EffectSpec {
670 let mut spec = b;
671 for (slot, value) in spec.params.iter_mut().enumerate() {
672 *value = f32::interpolate(a.params[slot], b.params[slot], t);
673 }
674 spec.animated = a.animated || b.animated;
677 spec
678}
679
680fn lerp_color(from: Hsla, to: Hsla, t: f32) -> Hsla {
683 if from == to {
684 return to;
685 }
686 let (a, b) = (gpui::Rgba::from(from), gpui::Rgba::from(to));
687 let alpha = f32::interpolate(a.a, b.a, t).clamp(0.0, 1.0);
688 if alpha <= 0.0 {
689 return Hsla {
690 a: 0.0,
691 ..if t < 0.5 { from } else { to }
692 };
693 }
694 let channel = |x: f32, y: f32| (f32::interpolate(x * a.a, y * b.a, t) / alpha).clamp(0.0, 1.0);
695 Hsla::from(gpui::Rgba {
696 r: channel(a.r, b.r),
697 g: channel(a.g, b.g),
698 b: channel(a.b, b.b),
699 a: alpha,
700 })
701}
702
703#[derive(Clone, Debug)]
704struct Track {
705 property: TransitionProperty,
706 from: Animatable,
707 to: Animatable,
708 start: Instant,
709 delay: Delay,
710 duration: Duration,
711 easing: Easing,
712}
713
714impl Track {
715 fn progress(&self, now: Instant) -> f32 {
716 let elapsed = now.saturating_duration_since(self.start);
717 let Some(running) = self.delay.active(elapsed) else {
718 return 0.0;
719 };
720 if self.duration.is_zero() {
721 return 1.0;
722 }
723 (running.as_secs_f32() / self.duration.as_secs_f32()).clamp(0.0, 1.0)
724 }
725
726 fn value(&self, now: Instant) -> Animatable {
727 lerp(self.from, self.to, self.easing.eval(self.progress(now)))
728 }
729
730 fn end(&self) -> Instant {
731 self.start + self.delay.end_after(self.duration).unwrap_or(self.duration)
732 }
733
734 fn finished(&self, now: Instant) -> bool {
735 now >= self.end()
736 }
737}
738
739#[derive(Default)]
740pub struct Animator {
741 nodes: HashMap<u32, Vec<Track>>,
742 anims: HashMap<u32, Vec<AnimRun>>,
743 registered_samples: RefCell<HashMap<u32, (Instant, Rc<(StyleRefinement, crate::Extras)>)>>,
744 events: Vec<AnimEvent>,
745 states: HashMap<u32, StyleRefinement>,
748 scripts: HashMap<u32, Vec<script::ScriptAnim>>,
749 script_nodes: HashMap<u32, u32>,
750 timeline_origin: Option<Instant>,
753 warned: HashSet<String>,
754 diagnostics: Vec<String>,
755 reduce_motion: bool,
756}
757
758mod script;
759pub use script::{
760 script_keyframes, ScriptClock, ScriptFrame, ScriptKeyframeNotes, ScriptSample, ScriptTiming,
761};
762
763impl Animator {
764 pub fn new() -> Animator {
765 Animator::default()
766 }
767
768 pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
771 if reduce_motion && !self.reduce_motion {
772 self.registered_samples.get_mut().clear();
773 self.nodes.clear();
774 let now = Instant::now();
775 for (node, runs) in std::mem::take(&mut self.anims) {
776 for run in runs {
777 self.cancel_event(node, &run, now);
778 }
779 }
780 }
781 self.reduce_motion = reduce_motion;
782 }
783
784 pub fn on_computed(
787 &mut self,
788 node: u32,
789 old: Option<&ComputedStates>,
790 new: &ComputedStates,
791 now: Instant,
792 ) {
793 if self.reduce_motion {
794 self.nodes.remove(&node);
795 return;
796 }
797 let Some(old) = old else {
798 self.nodes.remove(&node);
799 return;
800 };
801
802 for spec in new.transitions.iter() {
803 if let TransitionProperty::Other(name) = &spec.property {
804 self.warn_once(format!("transition of {name} not animatable yet"));
805 }
806 }
807
808 if new.transitions.is_empty() {
809 self.nodes.remove(&node);
812 self.states.remove(&node);
813 return;
814 }
815
816 let properties = covered(&new.transitions);
817 let mut tracks = self.nodes.remove(&node).unwrap_or_default();
818 tracks.retain(|t| properties.contains(&t.property));
819
820 for property in &properties {
821 let Some(spec) = spec_for(&new.transitions, property) else {
822 continue;
823 };
824 let index = tracks.iter().position(|t| t.property == *property);
825 let running = index.map(|i| tracks[i].value(now));
826
827 let from_slot = match running {
828 Some(v) => Slot::Value(v),
829 None => slot_inherited(&old.base, property, old.color, &old.extras),
830 };
831 let to_slot = slot_inherited(&new.base, property, new.color, &new.extras);
832
833 match self.endpoints(from_slot, to_slot, property) {
834 Endpoints::Pair(from, to) => {
835 if let Some(i) = index {
836 if tracks[i].to == to {
837 continue;
838 }
839 }
840 if from == to || spec.is_instant() {
841 if let Some(i) = index {
842 tracks.remove(i);
843 }
844 continue;
845 }
846 let track = Track {
847 property: property.clone(),
848 from,
849 to,
850 start: now,
851 delay: spec.delay,
852 duration: spec.duration,
853 easing: spec.easing,
854 };
855 match index {
856 Some(i) => tracks[i] = track,
857 None => tracks.push(track),
858 }
859 }
860 Endpoints::Snap => {
861 if let Some(i) = index {
862 tracks.remove(i);
863 }
864 }
865 }
866 }
867
868 if tracks.is_empty() {
869 self.nodes.remove(&node);
870 } else {
871 self.nodes.insert(node, tracks);
872 }
873 }
874
875 pub fn on_state(
876 &mut self,
877 node: u32,
878 computed: &ComputedStates,
879 target: Option<&StyleRefinement>,
880 now: Instant,
881 ) {
882 if computed.transitions.is_empty() {
883 self.states.remove(&node);
884 self.nodes.remove(&node);
885 return;
886 }
887 let properties = covered(&computed.transitions);
888 let base = &*computed.base;
889
890 let mut hold = StyleRefinement::default();
893 let mut holds_anything = false;
894 if let Some(target) = target {
895 for p in &properties {
896 let to = slot_of(target, p);
897 if matches!(to, Slot::Missing) {
898 continue;
899 }
900 if to == slot_inherited(base, p, computed.color, &computed.extras) {
901 continue;
902 }
903 match to {
904 Slot::Value(v) => {
905 install(&mut hold, base, p, v);
906 holds_anything = true;
907 }
908 _ => {
909 copy_property(&mut hold, target, p);
910 holds_anything = true;
911 }
912 }
913 }
914 }
915
916 if self.reduce_motion {
917 self.nodes.remove(&node);
918 if holds_anything {
919 self.states.insert(node, hold);
920 } else {
921 self.states.remove(&node);
922 }
923 return;
924 }
925
926 let previous = self.states.get(&node).cloned();
927 let mut tracks = self.nodes.remove(&node).unwrap_or_default();
928 tracks.retain(|t| properties.contains(&t.property));
929
930 for property in &properties {
931 let Some(spec) = spec_for(&computed.transitions, property) else {
932 continue;
933 };
934 let index = tracks.iter().position(|t| t.property == *property);
935 let running = index.map(|i| tracks[i].value(now));
936 let from_slot = match running {
937 Some(v) => Slot::Value(v),
938 None => match previous.as_ref().map(|p| slot_of(p, property)) {
939 Some(Slot::Missing) | None => {
940 slot_inherited(base, property, computed.color, &computed.extras)
941 }
942 Some(s) => s,
943 },
944 };
945 let to_slot = match slot_of(&hold, property) {
946 Slot::Missing => slot_inherited(base, property, computed.color, &computed.extras),
947 s => s,
948 };
949
950 match self.endpoints(from_slot, to_slot, property) {
951 Endpoints::Pair(from, to) => {
952 if let Some(i) = index {
953 if tracks[i].to == to {
954 continue;
955 }
956 }
957 if from == to || spec.is_instant() {
958 if let Some(i) = index {
959 tracks.remove(i);
960 }
961 continue;
962 }
963 let track = Track {
964 property: property.clone(),
965 from,
966 to,
967 start: now,
968 delay: spec.delay,
969 duration: spec.duration,
970 easing: spec.easing,
971 };
972 match index {
973 Some(i) => tracks[i] = track,
974 None => tracks.push(track),
975 }
976 }
977 Endpoints::Snap => {
978 if let Some(i) = index {
979 tracks.remove(i);
980 }
981 }
982 }
983 }
984
985 if tracks.is_empty() {
986 self.nodes.remove(&node);
987 } else {
988 self.nodes.insert(node, tracks);
989 }
990 if holds_anything {
991 self.states.insert(node, hold);
992 } else {
993 self.states.remove(&node);
994 }
995 }
996
997 pub fn holds_state(&self, node: u32) -> bool {
998 self.states.contains_key(&node)
999 }
1000
1001 pub fn overlay(
1002 &self,
1003 node: u32,
1004 base: &StyleRefinement,
1005 now: Instant,
1006 ) -> Option<StyleRefinement> {
1007 let mut r = self.animation_overlay(node, base, now);
1008 if let Some(hold) = self.states.get(&node) {
1009 use gpui::Refineable as _;
1010 r.get_or_insert_with(StyleRefinement::default).refine(hold);
1011 }
1012 if let Some(tracks) = self.nodes.get(&node).filter(|t| !t.is_empty()) {
1013 let out = r.get_or_insert_with(StyleRefinement::default);
1014 for track in tracks {
1015 install(out, base, &track.property, track.value(now));
1016 }
1017 }
1018 self.script_overlay(node, base, now, &mut r);
1021 r
1022 }
1023
1024 pub fn any_active(&self, now: Instant) -> bool {
1025 self.nodes
1026 .values()
1027 .any(|tracks| tracks.iter().any(|t| !t.finished(now)))
1028 }
1029
1030 pub fn settles_at(&self) -> Option<Instant> {
1031 self.nodes
1032 .values()
1033 .flat_map(|tracks| tracks.iter())
1034 .map(Track::end)
1035 .max()
1036 }
1037
1038 pub fn finish_settled(&mut self, now: Instant) -> bool {
1041 let mut events = Vec::new();
1042 self.nodes.retain(|&node, tracks| {
1043 tracks.retain(|t| {
1044 if !t.finished(now) {
1045 return true;
1046 }
1047 events.push(AnimEvent {
1048 node,
1049 kind: AnimEventKind::TransitionEnd,
1050 name: t.property.name().to_string(),
1051 elapsed: t.duration.as_secs_f32(),
1052 });
1053 false
1054 });
1055 !tracks.is_empty()
1056 });
1057 let settled = !events.is_empty();
1058 self.events.append(&mut events);
1059 settled
1060 }
1061
1062 pub fn gc(&mut self, alive: &dyn Fn(u32) -> bool) {
1063 self.nodes.retain(|&id, _| alive(id));
1064 self.anims.retain(|&id, _| alive(id));
1065 self.registered_samples.get_mut().retain(|&id, _| alive(id));
1066 self.states.retain(|&id, _| alive(id));
1067 self.events.retain(|e| alive(e.node));
1068 self.scripts.retain(|&id, _| alive(id));
1071 self.script_nodes.retain(|_, node| alive(*node));
1072 }
1073
1074 pub fn clear(&mut self) {
1077 self.registered_samples.get_mut().clear();
1078 self.nodes.clear();
1079 self.states.clear();
1080 self.anims.clear();
1081 self.events.clear();
1082 }
1083
1084 pub fn is_idle(&self) -> bool {
1085 self.nodes.is_empty() && self.anims.is_empty() && self.scripts.is_empty()
1086 }
1087
1088 pub fn take_diagnostics(&mut self) -> Vec<String> {
1089 std::mem::take(&mut self.diagnostics)
1090 }
1091
1092 fn warn_once(&mut self, message: String) {
1093 if self.warned.insert(message.clone()) {
1094 self.diagnostics.push(message);
1095 }
1096 }
1097
1098 fn endpoints(&mut self, from: Slot, to: Slot, property: &TransitionProperty) -> Endpoints {
1099 if from == to {
1100 return Endpoints::Snap;
1101 }
1102 let (from, to) = match (from, to) {
1103 (Slot::Value(a), Slot::Value(b)) => (a, b),
1104 (Slot::Missing, Slot::Value(b)) => match initial(property) {
1105 Some(a) => (a, b),
1106 None => {
1107 self.warn_once(format!(
1108 "transition of {} from an unset value is not animatable yet (v1) — snapping",
1109 property.name()
1110 ));
1111 return Endpoints::Snap;
1112 }
1113 },
1114 (Slot::Value(a), Slot::Missing) => match initial(property) {
1115 Some(b) => (a, b),
1116 None => {
1117 self.warn_once(format!(
1118 "transition of {} to an unset value is not animatable yet (v1) — snapping",
1119 property.name()
1120 ));
1121 return Endpoints::Snap;
1122 }
1123 },
1124 (Slot::Opaque(Opaque::LongTextShadowList), _)
1125 | (_, Slot::Opaque(Opaque::LongTextShadowList)) => {
1126 self.warn_once(format!(
1127 "transition of {} with more than {MAX_ANIMATED_TEXT_SHADOWS} shadows is not \
1128 animatable — snapping. Animate a shorter list",
1129 property.name()
1130 ));
1131 return Endpoints::Snap;
1132 }
1133 (Slot::Opaque(Opaque::SvgColour(_)), _) | (_, Slot::Opaque(Opaque::SvgColour(_))) => {
1134 self.warn_once(format!(
1135 "transition of {} to or from a concrete SVG paint colour is not animatable \
1136 yet (v1) — snapping",
1137 property.name()
1138 ));
1139 return Endpoints::Snap;
1140 }
1141 _ => {
1142 self.warn_once(format!(
1143 "transition of {} between percentage/auto endpoints is not animatable yet \
1144 (v1) — snapping",
1145 property.name()
1146 ));
1147 return Endpoints::Snap;
1148 }
1149 };
1150 match unify(from, to) {
1151 Some((from, to)) => Endpoints::Pair(from, to),
1152 None => {
1153 self.warn_once(format!(
1154 "transition of {} between different length units is not animatable yet (v1) \
1155 — snapping",
1156 property.name()
1157 ));
1158 Endpoints::Snap
1159 }
1160 }
1161 }
1162}
1163
1164enum Endpoints {
1165 Pair(Animatable, Animatable),
1166 Snap,
1167}
1168
1169impl Animator {
1170 #[cfg(test)]
1171 fn overlay_test(&self, node: u32, now: Instant) -> Option<StyleRefinement> {
1172 self.overlay(node, &StyleRefinement::default(), now)
1173 }
1174}
1175
1176#[cfg(test)]
1177mod tests {
1178 use super::*;
1179 use gpui::{px, relative, rems, Rgba};
1180 use std::rc::Rc;
1181
1182 fn states(base: StyleRefinement, css: &str) -> ComputedStates {
1183 let transitions = if css.is_empty() {
1184 Vec::new()
1185 } else {
1186 let mut diagnostics = Vec::new();
1187 let (_, t) = crate::parse_inline_with_transitions(css, &mut diagnostics);
1188 assert!(diagnostics.is_empty(), "{diagnostics:?}");
1189 t
1190 };
1191 ComputedStates {
1192 base: Rc::new(base),
1193 transitions: Rc::new(transitions),
1194 ..Default::default()
1195 }
1196 }
1197
1198 fn with_opacity(v: f32) -> StyleRefinement {
1199 let mut r = StyleRefinement::default();
1200 r.opacity = Some(v);
1201 r
1202 }
1203
1204 fn with_width(w: Length) -> StyleRefinement {
1205 let mut r = StyleRefinement::default();
1206 r.size.width = Some(w);
1207 r
1208 }
1209
1210 fn with_radius(radius: AbsoluteLength) -> StyleRefinement {
1211 let mut r = StyleRefinement::default();
1212 r.corner_radii.top_left = Some(radius);
1213 r
1214 }
1215
1216 fn with_opacity_and_radius(o: f32, radius: f32) -> StyleRefinement {
1217 let mut r = with_radius(px(radius).into());
1218 r.opacity = Some(o);
1219 r
1220 }
1221
1222 fn opacity_of(r: &StyleRefinement) -> f32 {
1223 r.opacity.expect("overlay carries opacity")
1224 }
1225
1226 fn t0() -> Instant {
1227 Instant::now()
1228 }
1229
1230 #[test]
1231 fn first_computation_does_not_animate() {
1232 let mut a = Animator::new();
1233 let now = t0();
1234 let new = states(with_opacity(0.0), "transition: opacity 1s linear");
1235 a.on_computed(1, None, &new, now);
1236 assert!(a.overlay(1, &StyleRefinement::default(), now).is_none());
1237 assert!(!a.any_active(now));
1238 }
1239
1240 #[test]
1241 fn diff_start_interpolate_settle() {
1242 let mut a = Animator::new();
1243 let now = t0();
1244 let old = states(with_opacity(0.0), "transition: opacity 1s linear");
1245 let new = states(with_opacity(1.0), "transition: opacity 1s linear");
1246
1247 a.on_computed(1, Some(&old), &new, now);
1248 assert!(a.any_active(now));
1249 assert!(
1250 (opacity_of(&a.overlay(1, &StyleRefinement::default(), now).unwrap()) - 0.0).abs()
1251 < 1e-6
1252 );
1253
1254 let half = now + Duration::from_millis(500);
1255 assert!(
1256 (opacity_of(&a.overlay(1, &StyleRefinement::default(), half).unwrap()) - 0.5).abs()
1257 < 1e-3
1258 );
1259
1260 let end = now + Duration::from_millis(1000);
1261 assert!(
1262 (opacity_of(&a.overlay(1, &StyleRefinement::default(), end).unwrap()) - 1.0).abs()
1263 < 1e-6
1264 );
1265 assert!(!a.any_active(end));
1266
1267 a.finish_settled(end);
1268 assert!(a.overlay(1, &StyleRefinement::default(), end).is_none());
1269 assert!(a.is_idle());
1270 }
1271
1272 #[test]
1273 fn delay_holds_the_start_value() {
1274 let mut a = Animator::new();
1275 let now = t0();
1276 let old = states(with_opacity(0.0), "transition: opacity 1s linear 500ms");
1277 let new = states(with_opacity(1.0), "transition: opacity 1s linear 500ms");
1278 a.on_computed(1, Some(&old), &new, now);
1279
1280 for at in [0, 200, 499] {
1281 let v = opacity_of(&a.overlay_test(1, now + Duration::from_millis(at)).unwrap());
1282 assert!(
1283 v.abs() < 1e-6,
1284 "value moved during the delay at {at}ms: {v}"
1285 );
1286 }
1287 let v = opacity_of(
1288 &a.overlay_test(1, now + Duration::from_millis(1000))
1289 .unwrap(),
1290 );
1291 assert!((v - 0.5).abs() < 1e-3, "{v}");
1292 assert!(a.any_active(now + Duration::from_millis(1000)));
1293 assert!(!a.any_active(now + Duration::from_millis(1500)));
1294 }
1295
1296 #[test]
1297 fn a_negative_delay_starts_part_way_through() {
1298 let mut a = Animator::new();
1299 let now = t0();
1300 let old = states(with_opacity(0.0), "transition: opacity 1s linear -250ms");
1301 let new = states(with_opacity(1.0), "transition: opacity 1s linear -250ms");
1302 a.on_computed(1, Some(&old), &new, now);
1303
1304 let v = opacity_of(&a.overlay_test(1, now).unwrap());
1305 assert!((v - 0.25).abs() < 1e-3, "{v}");
1306 assert!(a.any_active(now + Duration::from_millis(700)));
1307 assert!(!a.any_active(now + Duration::from_millis(750)));
1308
1309 let mut b = Animator::new();
1310 let skipped = "transition: opacity 1s linear -1s";
1311 b.on_computed(
1312 1,
1313 Some(&states(with_opacity(0.0), skipped)),
1314 &states(with_opacity(1.0), skipped),
1315 now,
1316 );
1317 assert!(b.overlay(1, &StyleRefinement::default(), now).is_none());
1318 }
1319
1320 #[test]
1321 fn zero_combined_duration_snaps() {
1322 let mut a = Animator::new();
1323 let now = t0();
1324 let old = states(with_opacity(0.0), "transition: opacity 0s");
1325 let new = states(with_opacity(1.0), "transition: opacity 0s");
1326 a.on_computed(1, Some(&old), &new, now);
1327 assert!(a.overlay(1, &StyleRefinement::default(), now).is_none());
1328 }
1329
1330 #[test]
1331 fn zero_duration_with_delay_jumps_after_the_delay() {
1332 let mut a = Animator::new();
1333 let now = t0();
1334 let old = states(with_opacity(0.0), "transition: opacity 0s 300ms");
1335 let new = states(with_opacity(1.0), "transition: opacity 0s 300ms");
1336 a.on_computed(1, Some(&old), &new, now);
1337 assert!(opacity_of(&a.overlay_test(1, now + Duration::from_millis(100)).unwrap()) < 1e-6);
1338 assert!(
1339 (opacity_of(&a.overlay_test(1, now + Duration::from_millis(400)).unwrap()) - 1.0).abs()
1340 < 1e-6
1341 );
1342 }
1343
1344 #[test]
1345 fn retarget_preserves_visual_continuity() {
1346 let mut a = Animator::new();
1347 let now = t0();
1348 let css = "transition: opacity 1s linear";
1349 let zero = states(with_opacity(0.0), css);
1350 let one = states(with_opacity(1.0), css);
1351
1352 a.on_computed(1, Some(&zero), &one, now);
1353 let mid = now + Duration::from_millis(400);
1354 let at_interrupt = opacity_of(&a.overlay(1, &StyleRefinement::default(), mid).unwrap());
1355 assert!((at_interrupt - 0.4).abs() < 1e-3, "{at_interrupt}");
1356
1357 a.on_computed(1, Some(&one), &zero, mid);
1358 let resumed = opacity_of(&a.overlay(1, &StyleRefinement::default(), mid).unwrap());
1359 assert!(
1360 (resumed - at_interrupt).abs() < 1e-4,
1361 "jumped on retarget: {at_interrupt} -> {resumed}"
1362 );
1363
1364 let later = mid + Duration::from_millis(200);
1365 let v = opacity_of(&a.overlay(1, &StyleRefinement::default(), later).unwrap());
1366 assert!(v < at_interrupt, "{v} should be below {at_interrupt}");
1367 assert!((v - 0.32).abs() < 1e-2, "{v}");
1368 let done = mid + Duration::from_millis(1000);
1369 assert!(opacity_of(&a.overlay(1, &StyleRefinement::default(), done).unwrap()).abs() < 1e-6);
1370 }
1371
1372 #[test]
1373 fn restyle_with_the_same_target_does_not_restart() {
1374 let mut a = Animator::new();
1375 let now = t0();
1376 let css = "transition: opacity 1s linear";
1377 let zero = states(with_opacity(0.0), css);
1378 let one = states(with_opacity(1.0), css);
1379 a.on_computed(1, Some(&zero), &one, now);
1380
1381 let mid = now + Duration::from_millis(500);
1382 a.on_computed(1, Some(&one), &one, mid);
1383 let v = opacity_of(&a.overlay(1, &StyleRefinement::default(), mid).unwrap());
1384 assert!((v - 0.5).abs() < 1e-3, "restarted: {v}");
1385 assert!(!a.any_active(now + Duration::from_millis(1000)));
1386 }
1387
1388 #[test]
1389 fn colors_interpolate_in_srgb() {
1390 let mut a = Animator::new();
1391 let now = t0();
1392 let red: Hsla = Rgba {
1393 r: 1.0,
1394 g: 0.0,
1395 b: 0.0,
1396 a: 1.0,
1397 }
1398 .into();
1399 let blue: Hsla = Rgba {
1400 r: 0.0,
1401 g: 0.0,
1402 b: 1.0,
1403 a: 1.0,
1404 }
1405 .into();
1406 fn mk(c: Hsla) -> StyleRefinement {
1407 let mut r = StyleRefinement::default();
1408 r.background = Some(gpui::Fill::Color(c.into()));
1409 r
1410 }
1411 let old = states(mk(red), "transition: background-color 1s linear");
1412 let new = states(mk(blue), "transition: background-color 1s linear");
1413 a.on_computed(1, Some(&old), &new, now);
1414
1415 let half = a.overlay_test(1, now + Duration::from_millis(500)).unwrap();
1416 let c = half
1417 .background
1418 .unwrap()
1419 .color()
1420 .unwrap()
1421 .as_solid()
1422 .unwrap();
1423 let c = Rgba::from(c);
1426 assert!(
1427 (c.r - 0.5).abs() < 1e-3 && c.g < 1e-3 && (c.b - 0.5).abs() < 1e-3,
1428 "{c:?}"
1429 );
1430 }
1431
1432 #[test]
1435 fn a_colour_fading_in_from_transparent_keeps_its_colour() {
1436 let white: Hsla = Rgba {
1437 r: 1.0,
1438 g: 1.0,
1439 b: 1.0,
1440 a: 1.0,
1441 }
1442 .into();
1443 let clear = Hsla {
1444 h: 0.0,
1445 s: 0.0,
1446 l: 0.0,
1447 a: 0.0,
1448 };
1449 let quarter = Rgba::from(lerp_color(clear, white, 0.25));
1450 assert!((quarter.a - 0.25).abs() < 1e-3, "{quarter:?}");
1451 assert!(
1452 quarter.r > 0.999 && quarter.g > 0.999 && quarter.b > 0.999,
1453 "{quarter:?}"
1454 );
1455 let gray: Hsla = Rgba {
1456 r: 0.5,
1457 g: 0.5,
1458 b: 0.5,
1459 a: 1.0,
1460 }
1461 .into();
1462 let blue: Hsla = Rgba {
1463 r: 0.0,
1464 g: 0.0,
1465 b: 1.0,
1466 a: 1.0,
1467 }
1468 .into();
1469 let half = Rgba::from(lerp_color(gray, blue, 0.5));
1470 assert!(
1471 (half.r - 0.25).abs() < 1e-3 && (half.g - 0.25).abs() < 1e-3,
1472 "{half:?}"
1473 );
1474 assert!((half.b - 0.75).abs() < 1e-3, "{half:?}");
1475 let over = lerp_color(gray, blue, 1.4);
1476 assert!((0.0..=1.0).contains(&over.l) && (0.0..=1.0).contains(&over.a));
1477 }
1478
1479 #[test]
1480 fn pixel_lengths_interpolate() {
1481 let mut a = Animator::new();
1482 let now = t0();
1483 let old = states(with_width(px(100.0).into()), "transition: width 1s linear");
1484 let new = states(with_width(px(200.0).into()), "transition: width 1s linear");
1485 a.on_computed(1, Some(&old), &new, now);
1486 let overlay = a.overlay_test(1, now + Duration::from_millis(250)).unwrap();
1487 assert_eq!(overlay.size.width, Some(px(125.0).into()));
1488 }
1489
1490 #[test]
1491 fn object_position_interpolates_from_its_centred_initial_value() {
1492 let css = "transition: object-position 1s linear";
1493 let at = |x_fraction: f32, x_offset: f32| {
1494 let mut r = StyleRefinement::default();
1495 r.vn_object_position = Some(gpui::ObjectPosition {
1496 x_fraction,
1497 x_offset: px(x_offset),
1498 ..Default::default()
1499 });
1500 r
1501 };
1502 let mut a = Animator::new();
1503 let now = t0();
1504 a.on_computed(
1505 1,
1506 Some(&states(at(0.0, 0.0), css)),
1507 &states(at(1.0, -20.0), css),
1508 now,
1509 );
1510 let quarter = a.overlay_test(1, now + Duration::from_millis(250)).unwrap();
1511 assert_eq!(
1512 quarter.vn_object_position,
1513 Some(at(0.25, -5.0).vn_object_position.unwrap())
1514 );
1515
1516 let mut a = Animator::new();
1517 a.on_computed(
1518 1,
1519 Some(&states(StyleRefinement::default(), css)),
1520 &states(at(1.0, 0.0), css),
1521 now,
1522 );
1523 let half = a.overlay_test(1, now + Duration::from_millis(500)).unwrap();
1524 assert_eq!(half.vn_object_position.map(|p| p.x_fraction), Some(0.75));
1525 }
1526
1527 #[test]
1528 fn text_shadows_interpolate_pairwise_and_pad_with_transparent() {
1529 fn shadowed(shadows: &[gpui::TextShadow]) -> StyleRefinement {
1530 let mut r = StyleRefinement::default();
1531 r.text.text_shadow = Some(shadows.to_vec());
1532 r
1533 }
1534 let shadow = |x: f32, blur: f32, color: Option<Hsla>| gpui::TextShadow {
1535 color,
1536 offset: gpui::point(px(x), px(x)),
1537 blur_radius: px(blur),
1538 };
1539 let red = Hsla::from(Rgba {
1540 r: 1.0,
1541 g: 0.0,
1542 b: 0.0,
1543 a: 1.0,
1544 });
1545 let mut a = Animator::new();
1546 let now = t0();
1547 let css = "transition: text-shadow 1s linear";
1548 let old = states(shadowed(&[shadow(0.0, 0.0, None)]), css);
1549 let new = states(
1550 shadowed(&[shadow(4.0, 8.0, Some(red)), shadow(2.0, 2.0, Some(red))]),
1551 css,
1552 );
1553 a.on_computed(1, Some(&old), &new, now);
1554 let half = a
1555 .overlay_test(1, now + Duration::from_millis(500))
1556 .and_then(|r| r.text.text_shadow)
1557 .expect("text-shadow transitions");
1558 assert_eq!(half.len(), 2);
1559 assert_eq!(half[0].offset.x, px(2.0));
1560 assert_eq!(half[0].blur_radius, px(4.0));
1561 let first = half[0].color.expect("currentColor meets red");
1562 assert!(
1563 first.h != red.h || first.l != red.l,
1564 "mixed with black: {first:?}"
1565 );
1566 assert_eq!(
1567 half[1].offset.x,
1568 px(1.0),
1569 "the shorter list is padded with zeros"
1570 );
1571 assert_eq!(half[1].blur_radius, px(1.0));
1572 let second = half[1].color.expect("a padded shadow is transparent red");
1573 assert!(
1574 (second.a - 0.5).abs() < 1e-3 && second.h == red.h,
1575 "{second:?}"
1576 );
1577 }
1578
1579 #[test]
1580 fn padding_from_unset_uses_the_css_initial_zero() {
1581 let mut a = Animator::new();
1582 let now = t0();
1583 let mut to = StyleRefinement::default();
1584 to.padding.top = Some(px(20.0).into());
1585 let old = states(StyleRefinement::default(), "transition: padding 1s linear");
1586 let new = states(to, "transition: padding 1s linear");
1587 a.on_computed(1, Some(&old), &new, now);
1588 let overlay = a.overlay_test(1, now + Duration::from_millis(500)).unwrap();
1589 assert_eq!(overlay.padding.top, Some(px(10.0).into()));
1590 assert!(a.take_diagnostics().is_empty());
1591 }
1592
1593 #[test]
1594 fn percentage_endpoints_snap() {
1595 let mut a = Animator::new();
1596 let now = t0();
1597 let from = with_width(px(100.0).into());
1598 let to = with_width(Length::Definite(relative(0.5)));
1599 let old = states(from, "transition: width 1s linear");
1600 let new = states(to, "transition: width 1s linear");
1601 a.on_computed(1, Some(&old), &new, now);
1602 assert!(a.overlay(1, &StyleRefinement::default(), now).is_none());
1603 }
1604
1605 #[test]
1606 fn auto_endpoint_snaps() {
1607 let mut a = Animator::new();
1608 let now = t0();
1609 let old = states(with_width(Length::Auto), "transition: width 1s linear");
1610 let new = states(with_width(px(200.0).into()), "transition: width 1s linear");
1611 a.on_computed(1, Some(&old), &new, now);
1612 assert!(a.overlay(1, &StyleRefinement::default(), now).is_none());
1613 assert_eq!(a.take_diagnostics().len(), 1);
1614 }
1615
1616 #[test]
1617 fn unchanged_non_animatable_value_is_silent() {
1618 let mut a = Animator::new();
1619 let now = t0();
1620 let auto = states(with_width(Length::Auto), "transition: width 1s linear");
1621 a.on_computed(1, Some(&auto), &auto, now);
1622 assert!(a.take_diagnostics().is_empty());
1623 }
1624
1625 #[test]
1626 fn an_unsupported_property_does_not_animate() {
1627 let mut a = Animator::new();
1628 let now = t0();
1629 let old = states(with_opacity(0.0), "transition: filter 1s");
1630 let new = states(with_opacity(1.0), "transition: filter 1s");
1631 a.on_computed(1, Some(&old), &new, now);
1632 assert!(a.overlay(1, &StyleRefinement::default(), now).is_none());
1633 }
1634
1635 #[test]
1636 fn all_covers_every_animatable_property() {
1637 let mut a = Animator::new();
1638 let now = t0();
1639 let old = states(
1640 with_opacity_and_radius(0.0, 0.0),
1641 "transition: all 1s linear",
1642 );
1643 let new = states(
1644 with_opacity_and_radius(1.0, 8.0),
1645 "transition: all 1s linear",
1646 );
1647 a.on_computed(1, Some(&old), &new, now);
1648 let overlay = a.overlay_test(1, now + Duration::from_millis(500)).unwrap();
1649 assert!((overlay.opacity.unwrap() - 0.5).abs() < 1e-3);
1650 assert_eq!(overlay.corner_radii.top_left, Some(px(4.0).into()));
1651 }
1652
1653 #[test]
1654 fn removing_the_transition_cancels_running_tracks() {
1655 let mut a = Animator::new();
1656 let now = t0();
1657 let css = "transition: opacity 1s linear";
1658 let old = states(with_opacity(0.0), css);
1659 let new = states(with_opacity(1.0), css);
1660 a.on_computed(1, Some(&old), &new, now);
1661 assert!(a.any_active(now));
1662
1663 let mid = now + Duration::from_millis(300);
1664 let bare = states(with_opacity(1.0), "");
1665 a.on_computed(1, Some(&new), &bare, mid);
1666 assert!(a.overlay(1, &StyleRefinement::default(), mid).is_none());
1667 assert!(!a.any_active(mid));
1668 }
1669
1670 #[test]
1671 fn narrowing_transition_property_cancels_the_dropped_one() {
1672 let mut a = Animator::new();
1673 let now = t0();
1674 let old = states(
1675 with_opacity_and_radius(0.0, 0.0),
1676 "transition: all 1s linear",
1677 );
1678 let new = states(
1679 with_opacity_and_radius(1.0, 8.0),
1680 "transition: all 1s linear",
1681 );
1682 a.on_computed(1, Some(&old), &new, now);
1683 let mid = now + Duration::from_millis(200);
1684 assert!(a
1685 .overlay(1, &StyleRefinement::default(), mid)
1686 .unwrap()
1687 .corner_radii
1688 .top_left
1689 .is_some());
1690
1691 let narrowed = states(
1692 with_opacity_and_radius(1.0, 8.0),
1693 "transition: opacity 1s linear",
1694 );
1695 a.on_computed(1, Some(&new), &narrowed, mid);
1696 let overlay = a.overlay(1, &StyleRefinement::default(), mid).unwrap();
1697 assert!(overlay.corner_radii.top_left.is_none());
1698 assert!(overlay.opacity.is_some());
1699 }
1700
1701 #[test]
1702 fn gc_and_clear_drop_node_state() {
1703 let mut a = Animator::new();
1704 let now = t0();
1705 let css = "transition: opacity 1s linear";
1706 let old = states(with_opacity(0.0), css);
1707 let new = states(with_opacity(1.0), css);
1708 a.on_computed(1, Some(&old), &new, now);
1709 a.on_computed(2, Some(&old), &new, now);
1710 assert!(a.overlay(2, &StyleRefinement::default(), now).is_some());
1711
1712 a.gc(&|id| id == 1);
1713 assert!(a.overlay(2, &StyleRefinement::default(), now).is_none());
1714 assert!(a.overlay(1, &StyleRefinement::default(), now).is_some());
1715
1716 a.clear();
1717 assert!(a.is_idle());
1718 }
1719
1720 #[test]
1721 fn reduce_motion_snaps_and_cancels() {
1722 let mut a = Animator::new();
1723 let now = t0();
1724 let css = "transition: opacity 1s linear";
1725 let old = states(with_opacity(0.0), css);
1726 let new = states(with_opacity(1.0), css);
1727 a.on_computed(1, Some(&old), &new, now);
1728 assert!(a.any_active(now));
1729
1730 a.set_reduce_motion(true);
1731 assert!(a.is_idle());
1732 a.on_computed(1, Some(&old), &new, now);
1733 assert!(a.overlay(1, &StyleRefinement::default(), now).is_none());
1734
1735 a.set_reduce_motion(false);
1736 a.on_computed(1, Some(&old), &new, now);
1737 assert!(a.overlay(1, &StyleRefinement::default(), now).is_some());
1738 }
1739
1740 #[test]
1741 fn settles_at_reports_the_last_end() {
1742 let mut a = Animator::new();
1743 let now = t0();
1744 let old = states(with_opacity(0.0), "transition: opacity 1s linear");
1745 let new = states(with_opacity(1.0), "transition: opacity 1s linear");
1746 a.on_computed(1, Some(&old), &new, now);
1747 let settle = a.settles_at().unwrap();
1748 assert!(settle >= now + Duration::from_millis(999));
1749 assert!(settle <= now + Duration::from_millis(1001));
1750 }
1751
1752 #[test]
1753 fn zero_px_and_zero_rem_unify() {
1754 let mut a = Animator::new();
1755 let now = t0();
1756 let old = states(
1757 with_radius(AbsoluteLength::Rems(rems(0.0))),
1758 "transition: border-radius 1s linear",
1759 );
1760 let new = states(
1761 with_radius(px(10.0).into()),
1762 "transition: border-radius 1s linear",
1763 );
1764 a.on_computed(1, Some(&old), &new, now);
1765 let overlay = a.overlay_test(1, now + Duration::from_millis(500)).unwrap();
1766 assert_eq!(overlay.corner_radii.top_left, Some(px(5.0).into()));
1767 assert!(a.take_diagnostics().is_empty());
1768 }
1769
1770 #[test]
1771 fn mixed_px_rem_endpoints_snap() {
1772 let mut a = Animator::new();
1773 let now = t0();
1774 let old = states(
1775 with_radius(AbsoluteLength::Rems(rems(1.0))),
1776 "transition: border-radius 1s linear",
1777 );
1778 let new = states(
1779 with_radius(px(10.0).into()),
1780 "transition: border-radius 1s linear",
1781 );
1782 a.on_computed(1, Some(&old), &new, now);
1783 assert!(a.overlay(1, &StyleRefinement::default(), now).is_none());
1784 assert_eq!(a.take_diagnostics().len(), 1);
1785 }
1786
1787 #[test]
1788 fn per_property_specs_use_their_own_timing() {
1789 let mut a = Animator::new();
1790 let now = t0();
1791 let css = "transition: opacity 1s linear, border-top-left-radius 2s linear";
1792 let old = states(with_opacity_and_radius(0.0, 0.0), css);
1793 let new = states(with_opacity_and_radius(1.0, 100.0), css);
1794 a.on_computed(1, Some(&old), &new, now);
1795
1796 let at = now + Duration::from_millis(1000);
1797 let overlay = a.overlay(1, &StyleRefinement::default(), at).unwrap();
1798 assert!((overlay.opacity.unwrap() - 1.0).abs() < 1e-6);
1799 assert_eq!(overlay.corner_radii.top_left, Some(px(50.0).into()));
1800 assert!(a.any_active(at));
1801 assert!(!a.any_active(now + Duration::from_millis(2000)));
1802 }
1803
1804 #[test]
1805 fn easing_shapes_the_curve() {
1806 let mut a = Animator::new();
1807 let now = t0();
1808 let old = states(with_opacity(0.0), "transition: opacity 1s ease-in");
1809 let new = states(with_opacity(1.0), "transition: opacity 1s ease-in");
1810 a.on_computed(1, Some(&old), &new, now);
1811 let v = opacity_of(&a.overlay_test(1, now + Duration::from_millis(500)).unwrap());
1812 assert!((v - 0.3154).abs() < 2e-3, "{v}");
1813 }
1814
1815 #[test]
1816 fn overshooting_easing_is_clamped_for_opacity() {
1817 let mut a = Animator::new();
1818 let now = t0();
1819 let css = "transition: opacity 1s cubic-bezier(0.34, 1.8, 0.64, 1)";
1820 let old = states(with_opacity(0.0), css);
1821 let new = states(with_opacity(1.0), css);
1822 a.on_computed(1, Some(&old), &new, now);
1823 for step in 0..=20 {
1824 let v = opacity_of(
1825 &a.overlay_test(1, now + Duration::from_millis(step * 50))
1826 .unwrap(),
1827 );
1828 assert!((0.0..=1.0).contains(&v), "opacity left 0..1: {v}");
1829 }
1830 }
1831
1832 fn with_shading(value: &str) -> StyleRefinement {
1833 let mut diagnostics = Vec::new();
1834 let r = crate::parse_inline(&format!("--shading: {value}"), &mut diagnostics);
1835 assert!(diagnostics.is_empty(), "{diagnostics:?}");
1836 assert!(r.vn_effect.is_some(), "--shading: {value} did not map");
1837 r
1838 }
1839
1840 fn shading_of(r: &StyleRefinement) -> EffectSpec {
1841 r.vn_effect.expect("overlay carries --shading")
1842 }
1843
1844 #[test]
1845 fn effect_params_interpolate() {
1846 let mut a = Animator::new();
1847 let now = t0();
1848 let css = "transition: --shading 1s linear";
1849 let old = states(with_shading("frost(0.2, 8px)"), css);
1850 let new = states(with_shading("frost(0.8, 20px)"), css);
1851 a.on_computed(1, Some(&old), &new, now);
1852
1853 let half = shading_of(&a.overlay_test(1, now + Duration::from_millis(500)).unwrap());
1854 assert_eq!(half.id, gpui::effect_id::FROST);
1855 assert!((half.params[0] - 0.5).abs() < 1e-3, "{}", half.params[0]);
1856 assert!((half.params[1] - 14.0).abs() < 1e-3, "{}", half.params[1]);
1857 assert_eq!(half.backdrop_blur_radius(), half.params[1]);
1858 assert!(a.take_diagnostics().is_empty());
1859
1860 let end = shading_of(
1861 &a.overlay_test(1, now + Duration::from_millis(1000))
1862 .unwrap(),
1863 );
1864 assert_eq!(end.params[0], 0.8);
1865 assert_eq!(end.params[1], 20.0);
1866 }
1867
1868 #[test]
1869 fn effect_color_params_interpolate_componentwise() {
1870 let mut a = Animator::new();
1871 let now = t0();
1872 let css = "transition: --shading 1s linear";
1873 let old = states(with_shading("glow(#000000, 10px, 0)"), css);
1874 let new = states(with_shading("glow(#ffffff, 30px, 1)"), css);
1875 a.on_computed(1, Some(&old), &new, now);
1876 let half = shading_of(&a.overlay_test(1, now + Duration::from_millis(500)).unwrap());
1877 assert!((half.params[0] - 20.0).abs() < 1e-3);
1878 assert!((half.params[1] - 0.5).abs() < 1e-3);
1879 for channel in 4..7 {
1880 assert!((half.params[channel] - 0.5).abs() < 1e-3, "slot {channel}");
1881 }
1882 assert!((half.bleed() - 20.0).abs() < 1e-3);
1883 }
1884
1885 #[test]
1886 fn the_same_effect_with_another_image_cross_fades() {
1887 crate::mapper::effect::tests::with_user_effects();
1888 let mut a = Animator::new();
1889 let now = t0();
1890 let css = "transition: --shading 1s linear";
1891 let old = states(with_shading("grade(url(a.png), 0)"), css);
1892 let new = states(with_shading("grade(url(b.png), 1)"), css);
1893 a.on_computed(1, Some(&old), &new, now);
1894 let half = a.overlay_test(1, now + Duration::from_millis(500)).unwrap();
1895 let fade = half.vn_effect_fade.expect("a different image cross-fades");
1896 let source = |spec: &EffectSpec| spec.textures[0].unwrap().source;
1897 assert_eq!(source(&fade.from), sk_effects::texture_source("a.png"));
1898 assert_eq!(
1899 source(&shading_of(&half)),
1900 sk_effects::texture_source("b.png")
1901 );
1902 assert_eq!(
1903 fade.from.params[2], 0.0,
1904 "each side keeps its own parameters"
1905 );
1906
1907 let same = states(with_shading("grade(url(b.png), 0.5)"), css);
1908 a.on_computed(2, Some(&new), &same, now);
1909 let r = a.overlay_test(2, now + Duration::from_millis(500)).unwrap();
1910 assert!(r.vn_effect_fade.is_none(), "the same image interpolates");
1911 assert!((shading_of(&r).params[2] - 0.75).abs() < 1e-3);
1912 }
1913
1914 #[test]
1915 fn different_effects_cross_fade() {
1916 let mut a = Animator::new();
1917 let now = t0();
1918 let css = "transition: --shading 1s linear";
1919 let old = states(with_shading("frost(0.5)"), css);
1920 let new = states(with_shading("glow(10px, 0.5)"), css);
1921 a.on_computed(1, Some(&old), &new, now);
1922 let half = a.overlay_test(1, now + Duration::from_millis(250)).unwrap();
1923 let fade = half.vn_effect_fade.expect("a cross-fade");
1924 assert_eq!(fade.from.id, gpui::effect_id::FROST);
1925 assert_eq!(shading_of(&half).id, gpui::effect_id::GLOW);
1926 assert!((fade.progress - 0.25).abs() < 1e-3);
1927 assert!(a.take_diagnostics().is_empty());
1928
1929 let back = states(with_shading("frost(0.5)"), css);
1931 a.on_computed(1, Some(&new), &back, now + Duration::from_millis(250));
1932 let r = a.overlay_test(1, now + Duration::from_millis(750)).unwrap();
1933 let fade = r.vn_effect_fade.expect("still a cross-fade");
1934 assert_eq!(fade.from.id, gpui::effect_id::GLOW);
1935 assert_eq!(shading_of(&r).id, gpui::effect_id::FROST);
1936 assert!((fade.progress - 0.875).abs() < 1e-3);
1937 }
1938
1939 #[test]
1940 fn all_does_not_cover_shading_but_naming_it_does() {
1941 let mut a = Animator::new();
1942 let now = t0();
1943 let all = "transition: all 1s linear";
1944 let old = states(with_shading("frost(0.2)"), all);
1945 let new = states(with_shading("frost(0.8)"), all);
1946 a.on_computed(1, Some(&old), &new, now);
1947 assert!(
1948 a.overlay(1, &StyleRefinement::default(), now).is_none(),
1949 "`all` must not cover --shading"
1950 );
1951 assert!(a.take_diagnostics().is_empty());
1952
1953 let named = "transition: all 1s linear, --shading 1s linear";
1954 let old = states(with_shading("frost(0.2)"), named);
1955 let new = states(with_shading("frost(0.8)"), named);
1956 a.on_computed(2, Some(&old), &new, now);
1957 assert!(a.overlay(2, &StyleRefinement::default(), now).is_some());
1958 }
1959
1960 #[test]
1961 fn transitioning_to_none_fades_out() {
1962 let mut a = Animator::new();
1963 let now = t0();
1964 let css = "transition: --shading 1s linear";
1965 let old = states(with_shading("frost(0.5)"), css);
1966 let new = states(with_shading("none"), css);
1967 a.on_computed(1, Some(&old), &new, now);
1968 let r = a.overlay_test(1, now + Duration::from_millis(500)).unwrap();
1969 assert!(!shading_of(&r).is_some());
1970 assert_eq!(
1971 r.vn_effect_fade.map(|f| f.from.id),
1972 Some(gpui::effect_id::FROST)
1973 );
1974 }
1975
1976 #[test]
1977 fn an_effect_fades_in_from_and_out_to_an_unset_value() {
1978 let mut a = Animator::new();
1979 let now = t0();
1980 let css = "transition: --shading 1s linear";
1981 let unset = states(StyleRefinement::default(), css);
1982 let glow = states(with_shading("glow(10px, 0.5)"), css);
1983
1984 a.on_computed(1, Some(&unset), &glow, now);
1985 let r = a.overlay_test(1, now + Duration::from_millis(250)).unwrap();
1986 assert_eq!(shading_of(&r).id, gpui::effect_id::GLOW);
1987 let fade = r.vn_effect_fade.expect("appearing fades in");
1988 assert!(!fade.from.is_some());
1989 assert!((fade.progress - 0.25).abs() < 1e-3);
1990
1991 let mut a = Animator::new();
1992 a.on_computed(1, Some(&glow), &unset, now);
1993 let r = a.overlay_test(1, now + Duration::from_millis(250)).unwrap();
1994 assert!(!shading_of(&r).is_some());
1995 let fade = r.vn_effect_fade.expect("disappearing fades out");
1996 assert_eq!(fade.from.id, gpui::effect_id::GLOW);
1997 assert!((fade.progress - 0.25).abs() < 1e-3);
1998 }
1999
2000 #[test]
2001 fn an_animated_endpoint_keeps_the_whole_transition_animated() {
2002 let mut a = Animator::new();
2003 let now = t0();
2004 let css = "transition: --shading 1s linear";
2005 let old = states(with_shading("noise(0.1, 2px, 0)"), css);
2006 let new = states(with_shading("noise(0.6, 2px, 24)"), css);
2007 a.on_computed(1, Some(&old), &new, now);
2008 let half = shading_of(&a.overlay_test(1, now + Duration::from_millis(500)).unwrap());
2009 assert!(half.animated, "grain must not freeze mid-transition");
2010 assert!((half.params[0] - 0.35).abs() < 1e-3);
2011 assert!((half.params[2] - 12.0).abs() < 1e-3);
2012 }
2013
2014 fn rgb(r: f32, g: f32, b: f32) -> Hsla {
2015 Rgba { r, g, b, a: 1.0 }.into()
2016 }
2017
2018 fn svg_states(c: Hsla, paint: Option<crate::SvgPaint>, css: &str) -> ComputedStates {
2019 let mut base = StyleRefinement::default();
2020 base.text.color = Some(c);
2021 let mut s = states(base, css);
2022 s.extras = crate::Extras {
2023 fill: paint,
2024 stroke: paint,
2025 ..Default::default()
2026 };
2027 s.color = Some(c);
2028 s
2029 }
2030
2031 #[test]
2032 fn a_fill_track_follows_the_colour_the_sprite_is_tinted_with() {
2033 for css in ["transition: fill 1s linear", "transition: stroke 1s linear"] {
2034 let mut a = Animator::new();
2035 let now = t0();
2036 let (red, blue) = (rgb(1.0, 0.0, 0.0), rgb(0.0, 0.0, 1.0));
2037 let old = svg_states(red, Some(crate::SvgPaint::Current), css);
2038 let new = svg_states(blue, Some(crate::SvgPaint::Current), css);
2039
2040 a.on_computed(1, Some(&old), &new, now);
2041 assert!(a.any_active(now), "{css} must start a track");
2042
2043 let at = |ms: u64| {
2044 a.overlay_test(1, now + Duration::from_millis(ms))
2045 .and_then(|r| r.text.color)
2046 .unwrap_or_else(|| panic!("{css}: no tint at {ms}ms"))
2047 };
2048 let same = |a: Hsla, b: Hsla| {
2049 (a.h - b.h).abs() < 1e-4
2050 && (a.s - b.s).abs() < 1e-4
2051 && (a.l - b.l).abs() < 1e-4
2052 && (a.a - b.a).abs() < 1e-4
2053 };
2054 assert!(same(at(0), red), "{css} starts where it was: {:?}", at(0));
2055 assert!(
2056 same(at(1000), blue),
2057 "{css} ends where it is going: {:?}",
2058 at(1000)
2059 );
2060 let half = at(500);
2061 assert!(
2062 !same(half, red) && !same(half, blue),
2063 "{css} interpolates: {half:?}"
2064 );
2065 }
2066 }
2067
2068 #[test]
2069 fn an_svg_paint_of_none_snaps_instead_of_interpolating() {
2070 let mut a = Animator::new();
2071 let now = t0();
2072 let css = "transition: fill 1s linear";
2073 let old = svg_states(rgb(1.0, 0.0, 0.0), Some(crate::SvgPaint::None), css);
2074 let new = svg_states(rgb(0.0, 0.0, 1.0), Some(crate::SvgPaint::Current), css);
2075
2076 a.on_computed(1, Some(&old), &new, now);
2077 assert!(
2078 !a.any_active(now),
2079 "an unpainted endpoint has nothing to interpolate"
2080 );
2081 assert!(a.overlay_test(1, now).is_none());
2082
2083 let bare = svg_states(rgb(0.0, 0.0, 1.0), None, css);
2084 a.on_computed(2, Some(&bare), &bare, now);
2085 assert!(a.overlay_test(2, now).is_none());
2086 }
2087
2088 #[test]
2089 fn text_decoration_color_animates_without_refining_the_line_away() {
2090 fn decorated(c: Hsla) -> StyleRefinement {
2091 let mut r = StyleRefinement::default();
2092 r.text.underline = Some(gpui::UnderlineStyle {
2093 thickness: px(3.0),
2094 color: Some(c),
2095 wavy: true,
2096 offset: px(2.0),
2097 });
2098 r
2099 }
2100 let mut a = Animator::new();
2101 let now = t0();
2102 let css = "transition: text-decoration-color 1s linear";
2103 let (red, blue) = (rgb(1.0, 0.0, 0.0), rgb(0.0, 0.0, 1.0));
2104 let old = states(decorated(red), css);
2105 let new = states(decorated(blue), css);
2106
2107 a.on_computed(1, Some(&old), &new, now);
2108 assert!(a.any_active(now));
2109 let base = decorated(red);
2110 let half = a
2111 .overlay(1, &base, now + Duration::from_millis(500))
2112 .unwrap();
2113 let u = half
2114 .text
2115 .underline
2116 .clone()
2117 .expect("the overlay carries a decoration");
2118 assert_eq!(
2119 u.thickness,
2120 px(3.0),
2121 "the base's thickness survives the overlay"
2122 );
2123 assert!(u.wavy, "…and so does its waviness");
2124 assert_eq!(u.offset, px(2.0), "…and its offset");
2125 let c = u.color.expect("with a colour of its own");
2126 assert!(c != red && c != blue, "interpolated, not snapped: {c:?}");
2127
2128 let end = a
2129 .overlay(1, &base, now + Duration::from_millis(1000))
2130 .unwrap();
2131 let ended = end
2132 .text
2133 .underline
2134 .and_then(|u| u.color)
2135 .expect("a colour at the end");
2136 assert!(
2137 (ended.h - blue.h).abs() < 1e-4 && (ended.l - blue.l).abs() < 1e-4,
2138 "{ended:?}"
2139 );
2140 }
2141}
2142
2143struct AnimRun {
2146 spec: AnimationSpec,
2147 frames: Rc<Keyframes>,
2148 custom_context: Option<Rc<crate::CustomAnimationContext>>,
2149 start: Instant,
2150 pending: bool,
2151 started: bool,
2152 ended: bool,
2153 paused_for: Duration,
2154 paused_at: Option<Instant>,
2155}
2156
2157impl AnimRun {
2158 fn elapsed(&self, now: Instant) -> Duration {
2159 let raw = now.saturating_duration_since(self.start);
2160 let paused = self.paused_for
2161 + self
2162 .paused_at
2163 .map(|at| now.saturating_duration_since(at))
2164 .unwrap_or_default();
2165 raw.saturating_sub(paused)
2166 }
2167
2168 fn phase(&self, now: Instant) -> Phase {
2169 self.spec.phase(self.elapsed(now))
2170 }
2171
2172 fn paint_progress(&self, now: Instant) -> Option<f32> {
2173 match self.phase(now) {
2174 Phase::Running { progress, .. } => Some(progress),
2175 Phase::Delayed if matches!(self.spec.fill, FillMode::Backwards | FillMode::Both) => {
2176 Some(self.spec.phase(self.spec.delay.wait()).progress_or(0.0))
2177 }
2178 Phase::Finished { progress }
2179 if matches!(self.spec.fill, FillMode::Forwards | FillMode::Both) =>
2180 {
2181 Some(progress)
2182 }
2183 _ => None,
2184 }
2185 }
2186
2187 fn elapsed_seconds(&self, now: Instant) -> f32 {
2188 self.spec.active_time(self.elapsed(now)).as_secs_f32()
2189 }
2190}
2191
2192#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2193pub enum AnimEventKind {
2194 TransitionEnd,
2195 AnimationStart,
2196 AnimationEnd,
2197 AnimationCancel,
2198}
2199
2200#[derive(Clone, Debug)]
2201pub struct AnimEvent {
2202 pub node: u32,
2203 pub kind: AnimEventKind,
2204 pub name: String,
2205 pub elapsed: f32,
2207}
2208
2209impl Animator {
2210 pub fn on_computed_animations(
2211 &mut self,
2212 node: u32,
2213 new: &ComputedStates,
2214 now: Instant,
2215 resolve: &dyn Fn(&str) -> Option<Rc<Keyframes>>,
2216 ) {
2217 self.registered_samples.get_mut().remove(&node);
2218 let wanted: Vec<AnimationSpec> = if self.reduce_motion {
2219 Vec::new()
2220 } else {
2221 new.animations
2222 .iter()
2223 .filter(|s| !s.is_inert())
2224 .cloned()
2225 .collect()
2226 };
2227
2228 if wanted.is_empty() {
2229 if let Some(runs) = self.anims.remove(&node) {
2230 for run in runs {
2231 self.cancel_event(node, &run, now);
2232 }
2233 }
2234 return;
2235 }
2236
2237 let mut previous = self.anims.remove(&node).unwrap_or_default();
2238 let mut runs: Vec<AnimRun> = Vec::with_capacity(wanted.len());
2239 for spec in wanted {
2240 let existing = previous.iter().position(|r| r.spec.name == spec.name);
2244 let Some(frames) = resolve(&spec.name) else {
2245 self.warn_once(format!(
2246 "`animation-name: {}` names no @keyframes block in the stylesheet — \
2247 nothing animates (a browser behaves the same way)",
2248 spec.name
2249 ));
2250 continue;
2251 };
2252 match existing {
2253 Some(i) => {
2254 let mut run = previous.remove(i);
2255 match (run.paused_at, spec.play_state) {
2256 (None, PlayState::Paused) => run.paused_at = Some(now),
2257 (Some(at), PlayState::Running) => {
2258 run.paused_for += now.saturating_duration_since(at);
2259 run.paused_at = None;
2260 }
2261 _ => {}
2262 }
2263 run.spec = spec;
2264 run.frames = frames;
2265 run.custom_context = new.custom_animation.clone();
2266 runs.push(run);
2267 }
2268 None => {
2269 runs.push(AnimRun {
2270 paused_at: (spec.play_state == PlayState::Paused).then_some(now),
2271 spec,
2272 frames,
2273 custom_context: new.custom_animation.clone(),
2274 start: now,
2275 pending: true,
2276 started: false,
2277 ended: false,
2278 paused_for: Duration::ZERO,
2279 });
2280 }
2281 }
2282 }
2283 let leftovers: Vec<AnimRun> = previous;
2284 for run in leftovers {
2285 self.cancel_event(node, &run, now);
2286 }
2287 if runs.is_empty() {
2288 self.anims.remove(&node);
2289 } else {
2290 self.anims.insert(node, runs);
2291 }
2292 }
2293
2294 pub fn cancel_animations(&mut self, node: u32, now: Instant) {
2295 self.registered_samples.get_mut().remove(&node);
2296 if let Some(runs) = self.anims.remove(&node) {
2297 for run in runs {
2298 self.cancel_event(node, &run, now);
2299 }
2300 }
2301 }
2302
2303 pub fn has_animations(&self, node: u32) -> bool {
2304 self.anims.contains_key(&node)
2305 }
2306
2307 pub fn animations_finished(&self, node: u32, now: Instant) -> bool {
2309 self.anims.get(&node).is_none_or(|runs| {
2310 runs.iter().all(|run| {
2311 run.paused_at.is_none() && matches!(run.phase(now), Phase::Finished { .. })
2312 })
2313 })
2314 }
2315
2316 fn cancel_event(&mut self, node: u32, run: &AnimRun, now: Instant) {
2317 if run.ended {
2320 return;
2321 }
2322 self.events.push(AnimEvent {
2323 node,
2324 kind: AnimEventKind::AnimationCancel,
2325 name: run.spec.name.to_string(),
2326 elapsed: run.elapsed_seconds(now).max(0.0),
2327 });
2328 }
2329
2330 pub fn tick(&mut self, now: Instant) {
2331 self.registered_samples.get_mut().clear();
2332 let mut events = Vec::new();
2333 for (&node, runs) in self.anims.iter_mut() {
2334 for run in runs.iter_mut() {
2335 if run.pending {
2336 run.pending = false;
2337 run.start = now;
2338 if run.paused_at.is_some() {
2339 run.paused_at = Some(now);
2340 }
2341 }
2342 let phase = run.phase(now);
2343 if !run.started && !matches!(phase, Phase::Delayed) {
2344 run.started = true;
2345 events.push(AnimEvent {
2346 node,
2347 kind: AnimEventKind::AnimationStart,
2348 name: run.spec.name.to_string(),
2349 elapsed: run.spec.active_time(Duration::ZERO).as_secs_f32(),
2350 });
2351 }
2352 if !run.ended && matches!(phase, Phase::Finished { .. }) {
2353 run.ended = true;
2354 events.push(AnimEvent {
2355 node,
2356 kind: AnimEventKind::AnimationEnd,
2357 name: run.spec.name.to_string(),
2358 elapsed: run
2359 .spec
2360 .total()
2361 .map(|t| run.spec.active_time(t).as_secs_f32())
2362 .unwrap_or(0.0),
2363 });
2364 }
2365 }
2366 }
2367 self.events.append(&mut events);
2368 }
2369
2370 pub fn take_events(&mut self) -> Vec<AnimEvent> {
2371 std::mem::take(&mut self.events)
2372 }
2373
2374 pub fn moving_nodes(&self, now: Instant) -> impl Iterator<Item = u32> + '_ {
2375 let tracks = self
2376 .nodes
2377 .iter()
2378 .filter(move |(_, tracks)| tracks.iter().any(|t| !t.finished(now)))
2379 .map(|(&node, _)| node);
2380 let runs = self
2381 .anims
2382 .iter()
2383 .filter(move |(_, runs)| {
2384 runs.iter().any(|run| match run.phase(now) {
2385 Phase::Finished { .. } => false,
2386 Phase::Delayed | Phase::Running { .. } => run.paused_at.is_none(),
2387 })
2388 })
2389 .map(|(&node, _)| node);
2390 let timeline = self.timeline_ms(now);
2391 let scripts = self
2392 .scripts
2393 .iter()
2394 .filter(move |(_, list)| list.iter().any(|a| a.running(timeline)))
2395 .map(|(&node, _)| node);
2396 tracks.chain(runs).chain(scripts)
2397 }
2398
2399 pub fn any_animation(&self, now: Instant) -> bool {
2400 let css = self
2401 .anims
2402 .values()
2403 .flatten()
2404 .any(|run| match run.phase(now) {
2405 Phase::Finished { .. } => false,
2406 Phase::Delayed | Phase::Running { .. } => run.paused_at.is_none(),
2407 });
2408 css || {
2409 let timeline = self.timeline_ms(now);
2410 self.scripts.values().flatten().any(|a| a.running(timeline))
2411 }
2412 }
2413
2414 pub fn animated_extras(&self, node: u32, now: Instant) -> Option<crate::Extras> {
2415 self.registered_overlay(node, now)
2416 .map(|sample| sample.1.clone())
2417 }
2418
2419 fn registered_overlay(
2420 &self,
2421 node: u32,
2422 now: Instant,
2423 ) -> Option<Rc<(StyleRefinement, crate::Extras)>> {
2424 if let Some((at, sample)) = self.registered_samples.borrow().get(&node) {
2425 if *at == now {
2426 return Some(sample.clone());
2427 }
2428 }
2429 let runs = self.anims.get(&node)?;
2430 let mut context = None;
2431 let mut samples = Vec::new();
2432 for run in runs {
2433 let Some(scope) = &run.custom_context else {
2434 continue;
2435 };
2436 let Some(progress) = run.paint_progress(now) else {
2437 continue;
2438 };
2439 for registration in &scope.registrations {
2440 if scope.important_custom.contains(®istration.name) {
2441 continue;
2442 }
2443 let declares = |step: &crate::Keyframe| {
2444 scope.keyframe_value(step, ®istration.name).is_some()
2445 };
2446 let Some(segment) = run.frames.segment_steps(&declares, progress) else {
2447 continue;
2448 };
2449 let implicit = scope
2450 .vars
2451 .get(®istration.name)
2452 .and_then(crate::registered::percentage)
2453 .unwrap_or(registration.initial);
2454 let from = segment
2455 .from
2456 .and_then(|step| scope.keyframe_value(step, ®istration.name))
2457 .unwrap_or(implicit);
2458 let to = segment
2459 .to
2460 .and_then(|step| scope.keyframe_value(step, ®istration.name))
2461 .unwrap_or(implicit);
2462 let t = segment
2463 .easing
2464 .unwrap_or(run.spec.easing)
2465 .eval(segment.t.clamp(0., 1.));
2466 samples.push((registration.name.clone(), from + (to - from) * t));
2467 context = Some(scope);
2468 }
2469 }
2470 context.map(|scope| {
2471 let sample = Rc::new(scope.sample(&samples));
2472 self.registered_samples
2473 .borrow_mut()
2474 .insert(node, (now, sample.clone()));
2475 sample
2476 })
2477 }
2478
2479 fn animation_overlay(
2480 &self,
2481 node: u32,
2482 base: &StyleRefinement,
2483 now: Instant,
2484 ) -> Option<StyleRefinement> {
2485 let runs = self.anims.get(&node)?;
2486 let mut out = self
2487 .registered_overlay(node, now)
2488 .map(|sample| sample.0.clone());
2489 for run in runs {
2490 let progress = match run.phase(now) {
2491 Phase::Running { progress, .. } => progress,
2492 Phase::Delayed => {
2493 if !matches!(run.spec.fill, FillMode::Backwards | FillMode::Both) {
2494 continue;
2495 }
2496 run.spec.phase(run.spec.delay.wait()).progress_or(0.0)
2497 }
2498 Phase::Finished { progress } => {
2499 if !matches!(run.spec.fill, FillMode::Forwards | FillMode::Both) {
2500 continue;
2501 }
2502 progress
2503 }
2504 };
2505 let r = out.get_or_insert_with(StyleRefinement::default);
2506 apply_keyframes(r, base, &run.frames, &run.spec, progress);
2507 }
2508 out
2509 }
2510}
2511
2512impl Phase {
2513 fn progress_or(self, default: f32) -> f32 {
2514 match self {
2515 Phase::Running { progress, .. } | Phase::Finished { progress } => progress,
2516 Phase::Delayed => default,
2517 }
2518 }
2519}
2520
2521fn apply_keyframes(
2522 out: &mut StyleRefinement,
2523 base: &StyleRefinement,
2524 frames: &Keyframes,
2525 spec: &AnimationSpec,
2526 progress: f32,
2527) {
2528 for property in TransitionProperty::keyframed() {
2529 let declares: &dyn Fn(&StyleRefinement) -> bool =
2530 &|r: &StyleRefinement| slot_of(r, &property) != Slot::Missing;
2531 let Some(segment) = frames.segment(declares, progress) else {
2532 continue;
2533 };
2534 let implicit = || match slot_of(base, &property) {
2537 Slot::Missing => initial(&property).map_or(Slot::Missing, Slot::Value),
2538 slot => slot,
2539 };
2540 let from = segment
2541 .from
2542 .map(|k| slot_of(&k.style, &property))
2543 .unwrap_or_else(implicit);
2544 let to = segment
2545 .to
2546 .map(|k| slot_of(&k.style, &property))
2547 .unwrap_or_else(implicit);
2548 let (Slot::Value(a), Slot::Value(b)) = (from, to) else {
2549 if let Slot::Value(v) = from {
2550 install(out, base, &property, v);
2551 } else if let Slot::Value(v) = to {
2552 install(out, base, &property, v);
2553 }
2554 continue;
2555 };
2556 let Some((a, b)) = unify(a, b) else {
2557 install(out, base, &property, if segment.t < 0.5 { a } else { b });
2558 continue;
2559 };
2560 let easing = segment.easing.unwrap_or(spec.easing);
2561 install(
2562 out,
2563 base,
2564 &property,
2565 lerp(a, b, easing.eval(segment.t.clamp(0.0, 1.0))),
2566 );
2567 }
2568}
2569
2570#[cfg(test)]
2571mod border_colors_regressions {
2572 use super::*;
2573 #[test]
2574 fn transition_interpolates_each_border_side_and_uniform_shorthand_resets_it() {
2575 let mut before = StyleRefinement::default();
2576 before.border_color = Some(gpui::red());
2577 before.vn_border_colors.left = Some(Some(gpui::blue()));
2578 let mut after = StyleRefinement::default();
2579 after.border_color = Some(gpui::green());
2580 let (Slot::Value(a), Slot::Value(b)) = (
2581 slot_of(&before, &TransitionProperty::BorderColor),
2582 slot_of(&after, &TransitionProperty::BorderColor),
2583 ) else {
2584 panic!("border endpoints missing")
2585 };
2586 let (a, b) = unify(a, b).expect("uniform and per-side colours interpolate");
2587 let mut overlay = StyleRefinement::default();
2588 install(
2589 &mut overlay,
2590 &after,
2591 &TransitionProperty::BorderColor,
2592 lerp(a, b, 0.5),
2593 );
2594 assert_ne!(overlay.vn_border_colors.left, overlay.vn_border_colors.top);
2595 install(
2596 &mut overlay,
2597 &before,
2598 &TransitionProperty::BorderColor,
2599 Animatable::Color(gpui::green()),
2600 );
2601 assert_eq!(overlay.vn_border_colors.left, Some(None));
2602 clear(&mut overlay, &TransitionProperty::BorderColor);
2603 assert_eq!(overlay.vn_border_colors.left, None);
2604 assert_eq!(overlay.border_color, None);
2605 }
2606}