1use std::rc::Rc;
6use std::time::Instant;
7
8use gpui::{Hsla, StyleRefinement};
9
10use super::{initial, install, lerp, size_pair, slot_of, unify, Animatable, Animator, Slot};
11use crate::keyframes::{Direction, FillMode, Keyframe, Keyframes};
12use crate::transition::{Easing, TransitionProperty};
13
14#[derive(Clone, Copy, Debug, PartialEq)]
15pub struct ScriptTiming {
16 pub delay: f64,
17 pub end_delay: f64,
18 pub duration: f64,
19 pub iterations: f64,
20 pub iteration_start: f64,
21 pub direction: Direction,
22 pub fill: FillMode,
23 pub easing: Easing,
24}
25
26impl Default for ScriptTiming {
27 fn default() -> Self {
28 ScriptTiming {
29 delay: 0.0,
30 end_delay: 0.0,
31 duration: 0.0,
32 iterations: 1.0,
33 iteration_start: 0.0,
34 direction: Direction::Normal,
35 fill: FillMode::None,
36 easing: Easing::Linear,
37 }
38 }
39}
40
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42enum Phase {
43 Before,
44 Active,
45 After,
46}
47
48#[derive(Clone, Copy, Debug, Default, PartialEq)]
49pub struct ScriptSample {
50 pub progress: Option<f64>,
51 pub current_iteration: Option<f64>,
52}
53
54impl ScriptTiming {
55 pub fn active_duration(&self) -> f64 {
56 if self.duration == 0.0 || self.iterations == 0.0 {
57 0.0
58 } else {
59 self.duration * self.iterations
60 }
61 }
62
63 pub fn end_time(&self) -> f64 {
64 (self.delay + self.active_duration() + self.end_delay).max(0.0)
65 }
66
67 pub fn progress(&self, local: f64, backwards: bool) -> Option<f64> {
68 self.sample(Some(local), backwards).progress
69 }
70
71 pub fn sample(&self, local: Option<f64>, backwards: bool) -> ScriptSample {
72 let Some(local) = local else {
73 return ScriptSample::default();
74 };
75 let active = self.active_duration();
76 let end = self.end_time();
77 let before_active = self.delay.min(end).max(0.0);
78 let active_after = (self.delay + active).min(end).max(0.0);
79 let phase = if local < before_active || (backwards && local == before_active) {
80 Phase::Before
81 } else if local > active_after || (!backwards && local == active_after) {
82 Phase::After
83 } else {
84 Phase::Active
85 };
86 let active_time = match phase {
87 Phase::Before => matches!(self.fill, FillMode::Backwards | FillMode::Both)
88 .then(|| (local - self.delay).max(0.0)),
89 Phase::Active => Some(local - self.delay),
90 Phase::After => matches!(self.fill, FillMode::Forwards | FillMode::Both)
91 .then(|| (local - self.delay).min(active).max(0.0)),
92 };
93 let Some(active_time) = active_time else {
94 return ScriptSample::default();
95 };
96 let overall = if self.duration == 0.0 {
97 if phase == Phase::Before {
98 self.iteration_start
99 } else {
100 self.iteration_start + self.iterations
101 }
102 } else {
103 active_time / self.duration + self.iteration_start
104 };
105 let mut simple = if overall.is_finite() {
106 overall % 1.0
107 } else {
108 self.iteration_start % 1.0
109 };
110 if simple == 0.0
113 && phase != Phase::Before
114 && active_time == active
115 && self.iterations != 0.0
116 {
117 simple = 1.0;
118 }
119 let iteration = if phase == Phase::After && self.iterations.is_infinite() {
120 f64::INFINITY
121 } else if simple == 1.0 {
122 overall.floor() - 1.0
123 } else {
124 overall.floor()
125 };
126 let forwards = match self.direction {
127 Direction::Normal => true,
128 Direction::Reverse => false,
129 Direction::Alternate | Direction::AlternateReverse => {
130 let d = if self.direction == Direction::AlternateReverse {
131 iteration + 1.0
132 } else {
133 iteration
134 };
135 !d.is_finite() || d % 2.0 == 0.0
136 }
137 };
138 let directed = if forwards { simple } else { 1.0 - simple };
139 ScriptSample {
140 progress: Some(self.easing.eval_f64(directed)),
141 current_iteration: Some(iteration),
142 }
143 }
144}
145
146#[derive(Clone, Copy, Debug, PartialEq)]
147pub struct ScriptClock {
148 pub start: Option<f64>,
149 pub hold: Option<f64>,
150 pub rate: f64,
151}
152
153impl Default for ScriptClock {
154 fn default() -> Self {
155 ScriptClock {
156 start: None,
157 hold: None,
158 rate: 1.0,
159 }
160 }
161}
162
163impl ScriptClock {
164 pub fn current(&self, timeline: Option<f64>) -> Option<f64> {
165 self.hold
166 .or_else(|| Some((timeline? - self.start?) * self.rate))
167 }
168}
169
170pub(super) struct ScriptAnim {
171 pub(super) id: u32,
172 pub(super) frames: Rc<Keyframes>,
173 pub(super) timing: ScriptTiming,
174 pub(super) clock: ScriptClock,
175}
176
177impl ScriptAnim {
178 pub(super) fn running(&self, timeline: Option<f64>) -> bool {
179 if self.clock.hold.is_some() || self.clock.rate == 0.0 {
180 return false;
181 }
182 let Some(current) = self.clock.current(timeline) else {
183 return false;
184 };
185 if self.clock.rate > 0.0 {
186 current < self.timing.end_time()
187 } else {
188 current > 0.0
189 }
190 }
191
192 fn progress(&self, timeline: Option<f64>) -> Option<f64> {
193 let current = self.clock.current(timeline)?;
194 self.timing.progress(current, self.clock.rate < 0.0)
195 }
196}
197
198impl Animator {
199 pub fn set_timeline_origin(&mut self, origin: Instant) {
200 self.timeline_origin = Some(origin);
201 }
202
203 pub(super) fn timeline_ms(&self, now: Instant) -> Option<f64> {
204 self.timeline_origin
205 .map(|origin| now.saturating_duration_since(origin).as_secs_f64() * 1000.0)
206 }
207
208 pub fn script_set(&mut self, id: u32, node: u32, frames: Rc<Keyframes>, timing: ScriptTiming) {
209 let mut clock = ScriptClock::default();
210 if let Some(old) = self.script_nodes.get(&id).copied() {
211 if let Some(list) = self.scripts.get_mut(&old) {
212 if let Some(a) = list.iter_mut().find(|a| a.id == id) {
213 if old == node {
214 a.frames = frames;
215 a.timing = timing;
216 return;
217 }
218 clock = a.clock;
219 }
220 list.retain(|a| a.id != id);
221 if list.is_empty() {
222 self.scripts.remove(&old);
223 }
224 }
225 }
226 self.script_nodes.insert(id, node);
227 let list = self.scripts.entry(node).or_default();
228 let at = list.iter().position(|a| a.id > id).unwrap_or(list.len());
231 list.insert(
232 at,
233 ScriptAnim {
234 id,
235 frames,
236 timing,
237 clock,
238 },
239 );
240 }
241
242 pub fn has_script_animations(&self, node: u32) -> bool {
243 self.scripts.contains_key(&node)
244 }
245
246 pub fn script_node(&self, id: u32) -> Option<u32> {
247 self.script_nodes.get(&id).copied()
248 }
249
250 pub fn script_clock(&mut self, id: u32, clock: ScriptClock) -> Option<u32> {
251 let node = *self.script_nodes.get(&id)?;
252 let a = self
253 .scripts
254 .get_mut(&node)?
255 .iter_mut()
256 .find(|a| a.id == id)?;
257 a.clock = clock;
258 Some(node)
259 }
260
261 pub fn script_drop(&mut self, id: u32) -> Option<u32> {
262 let node = self.script_nodes.remove(&id)?;
263 if let Some(list) = self.scripts.get_mut(&node) {
264 list.retain(|a| a.id != id);
265 if list.is_empty() {
266 self.scripts.remove(&node);
267 }
268 }
269 Some(node)
270 }
271
272 pub fn script_values(
273 &self,
274 id: u32,
275 base: &StyleRefinement,
276 now: Instant,
277 ) -> Option<Vec<(String, String)>> {
278 let node = *self.script_nodes.get(&id)?;
279 let a = self.scripts.get(&node)?.iter().find(|a| a.id == id)?;
280 let mut out = Vec::new();
281 let Some(progress) = a.progress(self.timeline_ms(now)) else {
282 return Some(out);
283 };
284 let mut r = StyleRefinement::default();
285 apply_script_keyframes(
286 &mut r,
287 base,
288 &a.frames,
289 progress,
290 self.keywords.contains(&node),
291 );
292 for property in TransitionProperty::keyframed() {
293 if let Slot::Value(v) = slot_of(&r, &property) {
294 if let Some(css) = css_value(v) {
295 out.push((property.name().to_string(), css));
296 }
297 }
298 }
299 Some(out)
300 }
301
302 pub(super) fn script_overlay(
303 &self,
304 node: u32,
305 base: &StyleRefinement,
306 now: Instant,
307 out: &mut Option<StyleRefinement>,
308 ) {
309 let Some(list) = self.scripts.get(&node) else {
310 return;
311 };
312 let timeline = self.timeline_ms(now);
313 for a in list {
314 let Some(progress) = a.progress(timeline) else {
315 continue;
316 };
317 let r = out.get_or_insert_with(StyleRefinement::default);
318 apply_script_keyframes(r, base, &a.frames, progress, self.keywords.contains(&node));
319 }
320 }
321}
322
323fn apply_script_keyframes(
324 out: &mut StyleRefinement,
325 base: &StyleRefinement,
326 frames: &Keyframes,
327 progress: f64,
328 keywords: bool,
329) {
330 let p = progress as f32;
331 for property in TransitionProperty::keyframed() {
332 let mut list: Vec<(f32, Option<&Keyframe>)> = Vec::new();
333 for k in frames
334 .steps
335 .iter()
336 .filter(|k| slot_of(&k.style, &property) != Slot::Missing)
337 {
338 list.push((k.offset, Some(k)));
339 }
340 let (Some(&(first, _)), Some(&(last, _))) = (list.first(), list.last()) else {
341 continue;
342 };
343 if first != 0.0 {
344 list.insert(0, (0.0, None));
345 }
346 if last != 1.0 {
347 list.push((1.0, None));
348 }
349 let implicit = || match slot_of(base, &property) {
350 Slot::Missing => initial(&property).map_or(Slot::Missing, Slot::Value),
351 slot => slot,
352 };
353 let value =
354 |k: Option<&Keyframe>| k.map_or_else(implicit, |k| slot_of(&k.style, &property));
355 let zeros = list.iter().filter(|(o, _)| *o == 0.0).count();
356 let ones = list.iter().filter(|(o, _)| *o == 1.0).count();
357 let lone = if p < 0.0 && zeros > 1 {
358 Some(list[0].1)
359 } else if p >= 1.0 && ones > 1 {
360 Some(list[list.len() - 1].1)
361 } else {
362 None
363 };
364 if let Some(k) = lone {
365 if let Slot::Value(v) = value(k) {
366 install(out, base, &property, v);
367 }
368 continue;
369 }
370 let start = if p < 0.0 {
371 0
372 } else if p >= 1.0 {
373 list.len() - 2
374 } else {
375 list.iter()
376 .rposition(|(o, _)| *o <= p && *o < 1.0)
377 .unwrap_or(0)
378 };
379 let ((o0, k0), (o1, k1)) = (list[start], list[start + 1]);
380 let distance = if o1 > o0 { (p - o0) / (o1 - o0) } else { 0.0 };
381 let eased = k0
382 .and_then(|k| k.easing)
383 .unwrap_or(Easing::Linear)
384 .eval(distance);
385 let (from, to) = (value(k0), value(k1));
386 let (from, to) = size_pair(from, to, &property, keywords).unwrap_or((from, to));
387 let (Slot::Value(a), Slot::Value(b)) = (from, to) else {
388 if let Slot::Value(v) = from {
389 install(out, base, &property, v);
390 } else if let Slot::Value(v) = to {
391 install(out, base, &property, v);
392 }
393 continue;
394 };
395 match unify(a, b) {
396 Some((a, b)) => install(out, base, &property, lerp(a, b, eased)),
397 None => install(out, base, &property, if eased < 0.5 { a } else { b }),
398 }
399 }
400}
401
402fn css_value(v: Animatable) -> Option<String> {
403 Some(match v {
404 Animatable::Number(n) => format!("{n}"),
405 Animatable::Color(c) => css_color(c),
406 Animatable::BorderColors(colors) => colors.map(css_color).join(" "),
407 Animatable::Pixels(p) => format!("{}px", p.as_f32()),
408 Animatable::Rems(r) => format!("{}rem", r.0),
409 Animatable::Transform(t) => crate::transform_css(t),
410 Animatable::Overflow(o) => match o {
411 gpui::Overflow::Visible => "visible",
412 gpui::Overflow::Clip => "clip",
413 gpui::Overflow::Hidden => "hidden",
414 gpui::Overflow::Scroll => "scroll",
415 }
416 .to_string(),
417 Animatable::ObjectPosition(p) => {
418 let axis = |fraction: f32, offset: gpui::Pixels| {
419 format!("calc({}% + {}px)", fraction * 100.0, offset.as_f32())
420 };
421 format!(
422 "{} {}",
423 axis(p.x_fraction, p.x_offset),
424 axis(p.y_fraction, p.y_offset)
425 )
426 }
427 Animatable::CornerShape(s) => crate::corner_shape::to_css(s),
428 Animatable::TextShadows(shadows) => crate::text_shadow_css(shadows.list(), shadows.current),
429 Animatable::Size(form) => form.length().to_string(),
430 Animatable::Effect(_) | Animatable::EffectFade(..) => return None,
431 })
432}
433
434fn css_color(c: Hsla) -> String {
435 let c = gpui::Rgba::from(c);
436 let ch = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
437 let (r, g, b) = (ch(c.r), ch(c.g), ch(c.b));
438 if c.a >= 1.0 {
439 format!("rgb({r}, {g}, {b})")
440 } else {
441 format!(
442 "rgba({r}, {g}, {b}, {})",
443 (c.a.clamp(0.0, 1.0) * 1000.0).round() / 1000.0
444 )
445 }
446}
447
448pub struct ScriptFrame {
449 pub offset: f32,
450 pub easing: Option<Easing>,
451 pub decls: Vec<(String, String)>,
452}
453
454#[derive(Default, Debug)]
455pub struct ScriptKeyframeNotes {
456 pub ignored: Vec<String>,
457 pub diagnostics: Vec<String>,
458}
459
460pub fn script_keyframes(
461 frames: &[ScriptFrame],
462 vars: &crate::Vars,
463 env: &crate::Env,
464) -> (Rc<Keyframes>, ScriptKeyframeNotes) {
465 let mut notes = ScriptKeyframeNotes::default();
466 let mut steps = Vec::with_capacity(frames.len());
467 for frame in frames {
468 let mut body = String::new();
469 for (name, value) in &frame.decls {
470 if !crate::transition::animates(name) {
471 if !notes.ignored.contains(name) {
472 notes.ignored.push(name.clone());
473 }
474 continue;
475 }
476 body.push_str(name);
477 body.push_str(": ");
478 body.push_str(value);
479 body.push_str("; ");
480 }
481 let parsed = crate::mapper::parse_inline_style(&body, &mut notes.diagnostics);
482 let mut style = parsed.refinement.map(|r| (*r).clone()).unwrap_or_default();
483 let mut extras = crate::Extras::default();
484 for (name, raw) in &parsed.dynamic {
485 crate::mapper::apply_dynamic(
486 name,
487 raw,
488 vars,
489 env,
490 &mut style,
491 &mut extras,
492 &mut notes.diagnostics,
493 );
494 }
495 steps.push(Keyframe {
496 offset: frame.offset,
497 easing: frame.easing,
498 style: Rc::new(style),
499 dynamic: None,
500 custom: None,
501 });
502 }
503 steps.sort_by(|a, b| a.offset.total_cmp(&b.offset));
504 (
505 Rc::new(Keyframes {
506 steps,
507 dynamic: false,
508 }),
509 notes,
510 )
511}
512
513#[cfg(test)]
514mod tests {
515 use super::*;
516 use crate::transition::StepPosition;
517 use std::time::Duration;
518
519 fn timing(duration: f64) -> ScriptTiming {
520 ScriptTiming {
521 duration,
522 ..ScriptTiming::default()
523 }
524 }
525
526 fn frames(list: &[(f32, &str)]) -> Rc<Keyframes> {
527 let frames: Vec<ScriptFrame> = list
528 .iter()
529 .map(|(offset, body)| ScriptFrame {
530 offset: *offset,
531 easing: None,
532 decls: body
533 .split(';')
534 .filter_map(|d| d.split_once(':'))
535 .map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))
536 .collect(),
537 })
538 .collect();
539 script_keyframes(&frames, &crate::Vars::default(), &crate::Env::default()).0
540 }
541
542 fn animator() -> (Animator, Instant) {
543 let mut a = Animator::new();
544 let t0 = Instant::now();
545 a.set_timeline_origin(t0);
546 (a, t0)
547 }
548
549 fn at(t0: Instant, ms: u64) -> Instant {
550 t0 + Duration::from_millis(ms)
551 }
552
553 fn playing(start: f64) -> ScriptClock {
554 ScriptClock {
555 start: Some(start),
556 hold: None,
557 rate: 1.0,
558 }
559 }
560
561 fn opacity(a: &Animator, node: u32, now: Instant) -> Option<f32> {
562 a.overlay(node, &StyleRefinement::default(), now)
563 .and_then(|r| r.opacity)
564 }
565
566 fn translate_y(a: &Animator, node: u32, now: Instant) -> f32 {
567 let r = a
568 .overlay(node, &StyleRefinement::default(), now)
569 .expect("in effect");
570 match r.vn_transform.expect("a transform").translate.1 {
571 gpui::TransformLength::Pixels(p) => p,
572 other => panic!("{other:?}"),
573 }
574 }
575
576 #[test]
577 fn script_metadata_and_paint_share_boundaries_and_double_precision() {
578 let t = timing(1_000_000_000.0);
579 assert_eq!(t.sample(None, false), ScriptSample::default());
580 assert_eq!(t.sample(Some(-1.0), false), ScriptSample::default());
581 let local = 123_456_789.123;
582 let sample = t.sample(Some(local), false);
583 assert_eq!(sample.progress, Some(local / t.duration));
584 assert_eq!(sample.current_iteration, Some(0.0));
585 assert_eq!(sample.progress, t.progress(local, false));
586 let t = ScriptTiming {
587 duration: 1000.0,
588 iterations: 3.0,
589 direction: Direction::Alternate,
590 fill: FillMode::Both,
591 ..t
592 };
593 assert_eq!(
594 t.sample(Some(3000.0), false),
595 ScriptSample {
596 progress: Some(1.0),
597 current_iteration: Some(2.0)
598 }
599 );
600 let infinite = ScriptTiming {
601 duration: f64::INFINITY,
602 ..t
603 };
604 assert_eq!(
605 infinite.sample(Some(f64::INFINITY), false).progress,
606 Some(1.0)
607 );
608 }
609
610 #[test]
611 fn the_timing_model_follows_the_spec() {
612 let t = timing(1000.0);
613 assert_eq!(t.progress(-1.0, false), None, "before, no fill");
614 assert_eq!(t.progress(0.0, false), Some(0.0));
615 assert_eq!(t.progress(250.0, false), Some(0.25));
616 assert_eq!(t.progress(1000.0, false), None);
617 assert_eq!(t.progress(1000.0, true), Some(1.0));
618
619 let filled = ScriptTiming {
620 fill: FillMode::Both,
621 delay: 100.0,
622 ..t
623 };
624 assert_eq!(
625 filled.progress(0.0, false),
626 Some(0.0),
627 "backwards fill holds the start"
628 );
629 assert_eq!(
630 filled.progress(5000.0, false),
631 Some(1.0),
632 "forwards fill holds the end"
633 );
634
635 let alt = ScriptTiming {
636 iterations: 3.0,
637 direction: Direction::Alternate,
638 fill: FillMode::Forwards,
639 ..t
640 };
641 assert_eq!(alt.progress(250.0, false), Some(0.25));
642 assert_eq!(alt.progress(1250.0, false), Some(0.75));
643 assert_eq!(alt.progress(2250.0, false), Some(0.25));
644 assert_eq!(alt.progress(9000.0, false), Some(1.0));
645 let two = ScriptTiming {
646 iterations: 2.0,
647 ..alt
648 };
649 assert_eq!(two.progress(9000.0, false), Some(0.0));
650
651 let shifted = ScriptTiming {
652 iteration_start: 0.5,
653 ..t
654 };
655 assert_eq!(shifted.progress(250.0, false), Some(0.75));
656
657 let instant = ScriptTiming {
658 duration: 0.0,
659 fill: FillMode::Forwards,
660 ..t
661 };
662 assert_eq!(instant.progress(10.0, false), Some(1.0));
663
664 let stepped = ScriptTiming {
665 easing: Easing::Steps(4, StepPosition::JumpEnd),
666 ..t
667 };
668 assert_eq!(stepped.progress(600.0, false), Some(0.5));
669 assert_eq!(t.end_time(), 1000.0);
670 assert_eq!(
671 ScriptTiming {
672 end_delay: 500.0,
673 delay: 200.0,
674 ..t
675 }
676 .end_time(),
677 1700.0
678 );
679 assert_eq!(
680 ScriptTiming {
681 end_delay: -5000.0,
682 ..t
683 }
684 .end_time(),
685 0.0
686 );
687 }
688
689 #[test]
690 fn an_effect_animates_out_to_the_unset_value() {
691 let (mut a, t0) = animator();
692 a.script_set(
693 1,
694 7,
695 frames(&[(0.0, "--shading: glow(10px, 0.5)")]),
696 timing(1000.0),
697 );
698 a.script_clock(1, playing(0.0));
699 let r = a
700 .overlay(7, &StyleRefinement::default(), at(t0, 750))
701 .expect("in effect");
702 assert!(!r.vn_effect.expect("an effect slot").is_some());
703 let fade = r.vn_effect_fade.expect("the glow fades out");
704 assert_eq!(fade.from.id, gpui::effect_id::GLOW);
705 assert!((fade.progress - 0.75).abs() < 1e-3);
706 }
707
708 #[test]
709 fn a_playing_animation_paints_from_its_clock_and_stops_at_the_end() {
710 let (mut a, t0) = animator();
711 a.script_set(
712 1,
713 7,
714 frames(&[(0.0, "opacity: 0"), (1.0, "opacity: 1")]),
715 timing(1000.0),
716 );
717 assert_eq!(
718 opacity(&a, 7, at(t0, 100)),
719 None,
720 "idle until it has a clock"
721 );
722 assert!(!a.any_animation(at(t0, 100)));
723
724 a.script_clock(1, playing(100.0));
725 let v = opacity(&a, 7, at(t0, 600)).unwrap();
726 assert!((v - 0.5).abs() < 1e-3, "{v}");
727 assert!(a.any_animation(at(t0, 600)));
728 assert_eq!(a.moving_nodes(at(t0, 600)).collect::<Vec<_>>(), vec![7]);
729 assert_eq!(opacity(&a, 7, at(t0, 1200)), None);
730 assert!(!a.any_animation(at(t0, 1200)));
731 assert_eq!(a.moving_nodes(at(t0, 1200)).count(), 0);
732 }
733
734 #[test]
735 fn a_held_clock_paints_its_time_and_is_not_moving() {
736 let (mut a, t0) = animator();
737 a.script_set(
738 1,
739 7,
740 frames(&[(0.0, "opacity: 0"), (1.0, "opacity: 1")]),
741 timing(1000.0),
742 );
743 a.script_clock(
744 1,
745 ScriptClock {
746 start: None,
747 hold: Some(250.0),
748 rate: 1.0,
749 },
750 );
751 let v = opacity(&a, 7, at(t0, 5000)).unwrap();
752 assert!((v - 0.25).abs() < 1e-3, "{v}");
753 assert!(
754 !a.any_animation(at(t0, 5000)),
755 "paused: no reason to repaint"
756 );
757 a.script_clock(
758 1,
759 ScriptClock {
760 start: Some(2000.0),
761 hold: None,
762 rate: -1.0,
763 },
764 );
765 let v = opacity(&a, 7, at(t0, 1250)).unwrap();
766 assert!((v - 0.75).abs() < 1e-3, "{v}");
767 assert!(a.any_animation(at(t0, 1250)));
768 }
769
770 #[test]
771 fn an_overshooting_easing_extrapolates_the_last_interval() {
772 let (mut a, t0) = animator();
773 let back_out = Easing::CubicBezier(0.34, 1.56, 0.64, 1.0);
774 a.script_set(
775 1,
776 3,
777 frames(&[
778 (0.0, "transform: translateY(-100px)"),
779 (1.0, "transform: translateY(-120px)"),
780 ]),
781 ScriptTiming {
782 easing: back_out,
783 ..timing(900.0)
784 },
785 );
786 a.script_clock(1, playing(0.0));
787 let deepest = (1..90)
788 .map(|i| translate_y(&a, 3, at(t0, i * 10)))
789 .fold(f32::MAX, f32::min);
790 assert!(deepest < -121.0, "no overshoot: {deepest}");
791 }
792
793 #[test]
794 fn implicit_ends_take_the_underlying_value_and_later_animations_win() {
795 let (mut a, t0) = animator();
796 let mut base = StyleRefinement::default();
797 base.opacity = Some(0.2);
798 a.script_set(1, 9, frames(&[(1.0, "opacity: 1")]), timing(1000.0));
799 a.script_clock(1, playing(0.0));
800 let v = a.overlay(9, &base, at(t0, 500)).unwrap().opacity.unwrap();
801 assert!((v - 0.6).abs() < 1e-3, "{v}");
802 a.script_set(
803 2,
804 9,
805 frames(&[(0.0, "opacity: 0"), (1.0, "opacity: 0")]),
806 timing(1000.0),
807 );
808 a.script_clock(2, playing(0.0));
809 assert_eq!(a.overlay(9, &base, at(t0, 500)).unwrap().opacity, Some(0.0));
810 assert_eq!(a.script_drop(2), Some(9));
811 let v = a.overlay(9, &base, at(t0, 500)).unwrap().opacity.unwrap();
812 assert!((v - 0.6).abs() < 1e-3, "{v}");
813 }
814
815 #[test]
816 fn script_animations_sit_above_css_ones_and_survive_a_sheet_swap() {
817 let (mut a, t0) = animator();
818 a.script_set(
819 1,
820 4,
821 frames(&[(0.0, "opacity: 0.5"), (1.0, "opacity: 0.5")]),
822 timing(1000.0),
823 );
824 a.script_clock(1, playing(0.0));
825 a.clear();
826 assert_eq!(opacity(&a, 4, at(t0, 100)), Some(0.5));
827 a.gc(&|id| id != 4);
828 assert_eq!(opacity(&a, 4, at(t0, 100)), None, "its node is gone");
829 assert!(a.is_idle());
830 }
831
832 #[test]
833 fn a_new_target_keeps_the_clock() {
834 let (mut a, t0) = animator();
835 let f = frames(&[(0.0, "opacity: 0"), (1.0, "opacity: 1")]);
836 a.script_set(1, 4, f.clone(), timing(1000.0));
837 a.script_clock(1, playing(0.0));
838 a.script_set(1, 5, f, timing(1000.0));
839 assert_eq!(opacity(&a, 4, at(t0, 500)), None);
840 let v = opacity(&a, 5, at(t0, 500)).unwrap();
841 assert!((v - 0.5).abs() < 1e-3, "{v}");
842 }
843
844 #[test]
845 fn keyframe_easing_shapes_its_own_interval() {
846 let (mut a, t0) = animator();
847 let f = vec![
848 ScriptFrame {
849 offset: 0.0,
850 easing: Some(Easing::Steps(2, StepPosition::JumpEnd)),
851 decls: vec![("opacity".into(), "0".into())],
852 },
853 ScriptFrame {
854 offset: 0.5,
855 easing: None,
856 decls: vec![("opacity".into(), "1".into())],
857 },
858 ScriptFrame {
859 offset: 1.0,
860 easing: None,
861 decls: vec![("opacity".into(), "0".into())],
862 },
863 ];
864 let (k, _) = script_keyframes(&f, &crate::Vars::default(), &crate::Env::default());
865 a.script_set(1, 2, k, timing(1000.0));
866 a.script_clock(1, playing(0.0));
867 assert_eq!(opacity(&a, 2, at(t0, 100)), Some(0.0));
868 assert_eq!(opacity(&a, 2, at(t0, 300)), Some(0.5));
869 let v = opacity(&a, 2, at(t0, 750)).unwrap();
870 assert!((v - 0.5).abs() < 1e-2, "{v}");
871 }
872
873 #[test]
874 fn unanimatable_properties_are_reported_not_painted() {
875 let f = vec![ScriptFrame {
876 offset: 1.0,
877 easing: None,
878 decls: vec![
879 ("filter".into(), "blur(4px)".into()),
880 ("opacity".into(), "0.5".into()),
881 ("display".into(), "none".into()),
882 ],
883 }];
884 let (k, notes) = script_keyframes(&f, &crate::Vars::default(), &crate::Env::default());
885 assert_eq!(
886 notes.ignored,
887 vec!["filter".to_string(), "display".to_string()]
888 );
889 assert_eq!(k.steps[0].style.opacity, Some(0.5));
890 assert_eq!(k.steps[0].style.display, None);
891 }
892
893 #[test]
894 fn a_keyframe_value_resolves_against_the_target_s_custom_properties() {
895 let env = crate::Env::default();
896 let own = ("--to".to_string(), "0.25".to_string());
897 let vars = crate::vars::resolve(
898 &Rc::new(crate::Vars::default()),
899 &[&own],
900 &env,
901 &mut Vec::new(),
902 );
903 let f = vec![ScriptFrame {
904 offset: 1.0,
905 easing: None,
906 decls: vec![("opacity".into(), "var(--to)".into())],
907 }];
908 let (k, _) = script_keyframes(&f, &vars, &env);
909 assert_eq!(k.steps[0].style.opacity, Some(0.25));
910 }
911
912 #[test]
913 fn overflow_flips_halfway_and_border_widths_interpolate() {
914 let (mut a, t0) = animator();
915 let k = frames(&[
916 (0.0, "overflow: visible; border-top-width: 0px"),
917 (1.0, "overflow: hidden; border-top-width: 10px"),
918 ]);
919 a.script_set(1, 2, k, timing(1000.0));
920 a.script_clock(1, playing(0.0));
921 let overlay = |ms| {
922 a.overlay(2, &StyleRefinement::default(), at(t0, ms))
923 .expect("in effect")
924 };
925 let early = overlay(250);
926 assert_eq!(early.overflow.x, Some(gpui::Overflow::Visible));
927 assert_eq!(
928 early.border_widths.top,
929 Some(gpui::AbsoluteLength::Pixels(gpui::px(2.5)))
930 );
931 let late = overlay(750);
932 assert_eq!(late.overflow.x, Some(gpui::Overflow::Hidden));
933 assert_eq!(late.overflow.y, Some(gpui::Overflow::Hidden));
934 assert_eq!(
935 a.script_values(1, &StyleRefinement::default(), at(t0, 750))
936 .unwrap()
937 .into_iter()
938 .filter(|(name, _)| name.starts_with("overflow"))
939 .collect::<Vec<_>>(),
940 vec![
941 ("overflow-x".to_string(), "hidden".to_string()),
942 ("overflow-y".to_string(), "hidden".to_string())
943 ]
944 );
945 }
946
947 #[test]
948 fn commit_styles_serialises_the_current_values() {
949 let (mut a, t0) = animator();
950 a.script_set(
951 1,
952 2,
953 frames(&[
954 (0.0, "opacity: 0; transform: translateY(0px)"),
955 (1.0, "opacity: 1; transform: translateY(-20px)"),
956 ]),
957 ScriptTiming {
958 fill: FillMode::Forwards,
959 ..timing(1000.0)
960 },
961 );
962 a.script_clock(1, playing(0.0));
963 let values = a
964 .script_values(1, &StyleRefinement::default(), at(t0, 2000))
965 .unwrap();
966 assert!(
967 values.contains(&("opacity".to_string(), "1".to_string())),
968 "{values:?}"
969 );
970 assert!(
971 values.contains(&("transform".to_string(), "translate(0px, -20px)".to_string())),
972 "{values:?}"
973 );
974 assert_eq!(a.script_values(9, &StyleRefinement::default(), t0), None);
975 }
976
977 #[test]
978 fn easing_text_parses_like_the_cascade_and_refuses_linear_functions() {
979 use crate::transition::parse_easing;
980 assert_eq!(parse_easing("ease-out"), Some(Easing::EaseOut));
981 assert_eq!(
982 parse_easing("cubic-bezier(0.34, 1.56, 0.64, 1)"),
983 Some(Easing::CubicBezier(0.34, 1.56, 0.64, 1.0))
984 );
985 assert_eq!(
986 parse_easing("steps(4, end)"),
987 Some(Easing::Steps(4, StepPosition::JumpEnd))
988 );
989 assert_eq!(parse_easing("linear(0, 1)"), None);
990 assert_eq!(parse_easing("bogus"), None);
991 }
992}
993
994#[cfg(test)]
995mod border_css_regression {
996 use super::*;
997 #[test]
998 fn committed_border_animation_keeps_four_side_colours() {
999 let colors = [
1000 gpui::red(),
1001 gpui::green(),
1002 gpui::blue(),
1003 Hsla::transparent_black(),
1004 ];
1005 assert_eq!(
1006 css_value(Animatable::BorderColors(colors)),
1007 Some(colors.map(css_color).join(" "))
1008 );
1009 }
1010}