diff --git a/src/Avalonia.Animation/Animators/Animator`1.cs b/src/Avalonia.Animation/Animators/Animator`1.cs index d784227620..23afa76bf6 100644 --- a/src/Avalonia.Animation/Animators/Animator`1.cs +++ b/src/Avalonia.Animation/Animators/Animator`1.cs @@ -79,15 +79,15 @@ namespace Avalonia.Animation.Animators T oldValue, newValue; - if (firstKeyframe.isNeutral) - oldValue = neutralValue; + if (!firstKeyframe.isNeutral && firstKeyframe.Value is T firstKeyframeValue) + oldValue = firstKeyframeValue; else - oldValue = (T)firstKeyframe.Value; + oldValue = neutralValue; - if (lastKeyframe.isNeutral) - newValue = neutralValue; + if (!lastKeyframe.isNeutral && lastKeyframe.Value is T lastKeyframeValue) + newValue = lastKeyframeValue; else - newValue = (T)lastKeyframe.Value; + newValue = neutralValue; if (lastKeyframe.KeySpline != null) progress = lastKeyframe.KeySpline.GetSplineProgress(progress); diff --git a/tests/Avalonia.Animation.UnitTests/AnimatableTests.cs b/tests/Avalonia.Animation.UnitTests/AnimatableTests.cs index b01fb70f58..26d8059eec 100644 --- a/tests/Avalonia.Animation.UnitTests/AnimatableTests.cs +++ b/tests/Avalonia.Animation.UnitTests/AnimatableTests.cs @@ -1,5 +1,7 @@ using System; +using Avalonia.Animation.Animators; using Avalonia.Controls; +using Avalonia.Controls.Shapes; using Avalonia.Data; using Avalonia.Layout; using Avalonia.Media; @@ -100,6 +102,71 @@ namespace Avalonia.Animation.UnitTests Times.Never); } + + [Theory] + [InlineData(null)] //null value + [InlineData("stringValue")] //string value + public void Invalid_Values_In_Animation_Should_Not_Crash_Animations(object invalidValue) + { + var keyframe1 = new KeyFrame() + { + Setters = + { + new Setter(Layoutable.WidthProperty, 1d), + }, + KeyTime = TimeSpan.FromSeconds(0) + }; + + var keyframe2 = new KeyFrame() + { + Setters = + { + new Setter(Layoutable.WidthProperty, 2d), + }, + KeyTime = TimeSpan.FromSeconds(2), + }; + + var keyframe3 = new KeyFrame() + { + Setters = + { + new Setter(Layoutable.WidthProperty, invalidValue), + }, + KeyTime = TimeSpan.FromSeconds(3), + }; + + var animation = new Animation() + { + Duration = TimeSpan.FromSeconds(3), + Children = + { + keyframe1, + keyframe2, + keyframe3 + }, + IterationCount = new IterationCount(5), + PlaybackDirection = PlaybackDirection.Alternate, + }; + + var rect = new Rectangle() + { + Width = 11, + }; + + var originalValue = rect.Width; + + var clock = new TestClock(); + var animationRun = animation.RunAsync(rect, clock); + + clock.Step(TimeSpan.Zero); + Assert.Equal(rect.Width, 1); + clock.Step(TimeSpan.FromSeconds(2)); + Assert.Equal(rect.Width, 2); + clock.Step(TimeSpan.FromSeconds(3)); + //here we have invalid value so value should be expected and set to initial original value + Assert.Equal(rect.Width, originalValue); + } + [Fact] public void Transition_Is_Not_Applied_When_StyleTrigger_Changes_With_LocalValue_Present() {