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