From c2291bd8614b8715f98b11bab0c9c8b2f0fbc9ae Mon Sep 17 00:00:00 2001 From: Alexandre Zollinger Chohfi Date: Wed, 25 Nov 2026 13:47:34 -0800 Subject: [PATCH 1/5] Skip unchanged renders for rebuilt animation declarations (#1702) Since #1552 the shallow skip compares AnimationExtras with record equality, and .Keyframes(), .ScrollLinked(), implicit transitions, .WithTransitions() and .InteractionStates() rebuild arrays and WinUI objects on every render, so an unchanged element using them never skipped. .ScrollLinked() also restarted its expressions on every parent render. The declarations now compare by value: keyframe definitions and arrays, scroll expressions with the same ScrollViewer, implicit transition durations and components, theme transition settings per WinUI type, and solid brushes by color. AnimationExtras stays compiler-generated, so a new field is still compared. A changed or removed declaration still updates (#1536). ShallowEquals compares animations after the element's own properties, so an element that changed anyway doesn't pay for the WinUI reads. An update that leaves .ScrollLinked() unchanged no longer restarts its expressions unless the element declares another animation. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 10 ++ docs/_pipeline/templates/animation.md.dt | 11 +- docs/guide/animation.md | 11 +- src/Reactor/Animation/AnimationEquality.cs | 114 ++++++++++++ src/Reactor/Animation/InteractionStates.cs | 21 ++- src/Reactor/Animation/KeyframeBuilder.cs | 13 ++ src/Reactor/Animation/ScrollAnimation.cs | 16 +- src/Reactor/Core/Element.cs | 68 ++++++-- src/Reactor/Core/Reconciler.Update.cs | 11 +- src/Reactor/Core/Reconciler.cs | 5 + .../SelfTest/Fixtures/AnimateModifierTests.cs | 165 ++++++++++++++++++ .../SelfTest/SelfTestFixtureRegistry.cs | 2 + .../AnimationExtrasEqualityTests.cs | 36 +++- 13 files changed, 446 insertions(+), 37 deletions(-) create mode 100644 src/Reactor/Animation/AnimationEquality.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 89c659bf5b..44a7e5e6a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -207,6 +207,16 @@ Conventions for contributors: ### Fixed +- **Elements using `.Keyframes()`, `.ScrollLinked()`, an implicit transition such as + `.OpacityTransition()`, `.WithTransitions()` or `.InteractionStates()` skip unchanged renders + again (issue #1702; follow-up to #1536, spec 014).** Each render rebuilds these declarations with + new arrays and WinUI objects, and the skip check compared those by reference, so such an element + always ran a full update. `.ScrollLinked()` also restarted its expressions every time. The + declarations now compare by value: keyframes, scroll expressions with the same `ScrollViewer`, + transition durations and settings, and solid brushes by color. A changed or removed declaration + still updates. An update for another reason no longer restarts unchanged scroll expressions, + unless the element also declares another animation. + - **Unmount clears a `.Ref` declared on a keyed `Memo` or a `ModifiedElement` (issue #1659).** Those layers mount no control of their own, so the ref points at the control their child mounted, and unmount only cleared refs declared on that control's own element and its decorators. The ref kept diff --git a/docs/_pipeline/templates/animation.md.dt b/docs/_pipeline/templates/animation.md.dt index 3fb68a8fd1..b5d2bd270e 100644 --- a/docs/_pipeline/templates/animation.md.dt +++ b/docs/_pipeline/templates/animation.md.dt @@ -43,11 +43,12 @@ Animation and transition configuration changes are also checked on each render, even when the element's other properties stay the same. For example, changing only `.LayoutAnimation()`'s duration updates the layout animation on the next render. -Value-equivalent plain-data configurations such as `.Animate()` and -`.LayoutAnimation()` can still skip updates. Native objects and arrays use -reference equality: rebuilding `.OpacityTransition()`, `.WithTransitions()`, -`.Keyframes()`, or `.ScrollLinked()` with fresh objects or arrays prevents -skipping, even when the settings match. +Unchanged declarations still skip updates, even though each render rebuilds +them. `.Keyframes()` and `.ScrollLinked()` compare their keyframes and +expressions, implicit transitions such as `.OpacityTransition()` compare their +duration, `.WithTransitions()` compares each theme transition's settings, and +`.InteractionStates()` compares solid brushes by color. Other brushes, and a +`.ScrollLinked()` driven by a different `ScrollViewer`, still count as a change. ## Reference diff --git a/docs/guide/animation.md b/docs/guide/animation.md index 58a9f1fd1a..ce8889a6e4 100644 --- a/docs/guide/animation.md +++ b/docs/guide/animation.md @@ -30,11 +30,12 @@ Animation and transition configuration changes are also checked on each render, even when the element's other properties stay the same. For example, changing only `.LayoutAnimation()`'s duration updates the layout animation on the next render. -Value-equivalent plain-data configurations such as `.Animate()` and -`.LayoutAnimation()` can still skip updates. Native objects and arrays use -reference equality: rebuilding `.OpacityTransition()`, `.WithTransitions()`, -`.Keyframes()`, or `.ScrollLinked()` with fresh objects or arrays prevents -skipping, even when the settings match. +Unchanged declarations still skip updates, even though each render rebuilds +them. `.Keyframes()` and `.ScrollLinked()` compare their keyframes and +expressions, implicit transitions such as `.OpacityTransition()` compare their +duration, `.WithTransitions()` compares each theme transition's settings, and +`.InteractionStates()` compares solid brushes by color. Other brushes, and a +`.ScrollLinked()` driven by a different `ScrollViewer`, still count as a change. ## Reference diff --git a/src/Reactor/Animation/AnimationEquality.cs b/src/Reactor/Animation/AnimationEquality.cs new file mode 100644 index 0000000000..19103b261a --- /dev/null +++ b/src/Reactor/Animation/AnimationEquality.cs @@ -0,0 +1,114 @@ +using System.Runtime.CompilerServices; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Media.Animation; +using XamlTransition = Microsoft.UI.Xaml.Media.Animation.Transition; + +namespace Microsoft.UI.Reactor.Animation; + +/// +/// Value equality for animation declarations that modifiers rebuild on every render (issue #1702). +/// Element skip checks compare these, so two renders that declare the same animation compare +/// equal even though each allocated fresh arrays and WinUI objects. Unknown WinUI types fall +/// back to reference equality. Reading WinUI objects requires the UI thread, like reconcile. +/// +internal static class AnimationEquality +{ + internal static bool SequenceEqual(T[]? a, T[]? b) + { + if (ReferenceEquals(a, b)) return true; + if (a is null || b is null || a.Length != b.Length) return false; + var comparer = EqualityComparer.Default; + for (int i = 0; i < a.Length; i++) + if (!comparer.Equals(a[i], b[i])) return false; + return true; + } + + internal static int SequenceHash(T[]? items) + { + if (items is null) return 0; + var hash = new HashCode(); + foreach (var item in items) hash.Add(item); + return hash.ToHashCode(); + } + + /// Equality for the implicit transitions behind .OpacityTransition() and friends. + internal static bool ImplicitTransitionEqual(object? a, object? b) + { + if (ReferenceEquals(a, b)) return true; + return (a, b) switch + { + (ScalarTransition sa, ScalarTransition sb) => sa.Duration == sb.Duration, + (Vector3Transition va, Vector3Transition vb) => va.Duration == vb.Duration && va.Components == vb.Components, + (BrushTransition ba, BrushTransition bb) => ba.Duration == bb.Duration, + _ => false, + }; + } + + internal static bool ThemeTransitionsEqual(XamlTransition[]? a, XamlTransition[]? b) + { + if (ReferenceEquals(a, b)) return true; + if (a is null || b is null || a.Length != b.Length) return false; + for (int i = 0; i < a.Length; i++) + if (!ThemeTransitionEqual(a[i], b[i])) return false; + return true; + } + + /// + /// Equality for WinUI's theme transitions, by type and settable properties. A transition type + /// missing from this table compares by reference, which only costs a skipped update. + /// + private static bool ThemeTransitionEqual(XamlTransition? a, XamlTransition? b) + { + if (ReferenceEquals(a, b)) return true; + return (a, b) switch + { + (EntranceThemeTransition ea, EntranceThemeTransition eb) => + ea.FromHorizontalOffset == eb.FromHorizontalOffset && ea.FromVerticalOffset == eb.FromVerticalOffset + && ea.IsStaggeringEnabled == eb.IsStaggeringEnabled, + (ContentThemeTransition ca, ContentThemeTransition cb) => + ca.HorizontalOffset == cb.HorizontalOffset && ca.VerticalOffset == cb.VerticalOffset, + (PopupThemeTransition pa, PopupThemeTransition pb) => + pa.FromHorizontalOffset == pb.FromHorizontalOffset && pa.FromVerticalOffset == pb.FromVerticalOffset, + (RepositionThemeTransition ra, RepositionThemeTransition rb) => ra.IsStaggeringEnabled == rb.IsStaggeringEnabled, + (EdgeUIThemeTransition ea, EdgeUIThemeTransition eb) => ea.Edge == eb.Edge, + (PaneThemeTransition pa, PaneThemeTransition pb) => pa.Edge == pb.Edge, + (NavigationThemeTransition na, NavigationThemeTransition nb) => + ReferenceEquals(na.DefaultNavigationTransitionInfo, nb.DefaultNavigationTransitionInfo), + (AddDeleteThemeTransition, AddDeleteThemeTransition) => true, + (ReorderThemeTransition, ReorderThemeTransition) => true, + _ => false, + }; + } + + /// + /// A solid brush compares by color and opacity, the same rule element brush properties use. + /// Other brushes compare by reference. + /// + internal static bool BrushesEqual(Brush? a, Brush? b) + { + if (ReferenceEquals(a, b)) return true; + if (a is null || b is null) return false; + if (a is SolidColorBrush sa && b is SolidColorBrush sb) + return sa.Color == sb.Color && sa.Opacity == sb.Opacity; + return false; + } + + /// Hash for a value compared by reference. + internal static int IdentityHash(object? value) => value is null ? 0 : RuntimeHelpers.GetHashCode(value); +} + +/// +/// An array compared by its elements, for array-valued animation declarations held in +/// . +/// +internal readonly struct ValueArray(T[]? items) : IEquatable> +{ + internal T[]? Items { get; } = items; + + public bool Equals(ValueArray other) => AnimationEquality.SequenceEqual(Items, other.Items); + + public override bool Equals(object? obj) => obj is ValueArray other && Equals(other); + + public override int GetHashCode() => AnimationEquality.SequenceHash(Items); +} diff --git a/src/Reactor/Animation/InteractionStates.cs b/src/Reactor/Animation/InteractionStates.cs index 609f7decf8..f66cf171e1 100644 --- a/src/Reactor/Animation/InteractionStates.cs +++ b/src/Reactor/Animation/InteractionStates.cs @@ -19,7 +19,26 @@ public record InteractionStateValues( // Direct property set (pre-cached brush swap, ~1us) Brush? Background = null, Brush? Foreground = null, - Brush? BorderBrush = null); + Brush? BorderBrush = null) +{ + /// + /// Compares solid brushes by color and opacity, so brushes rebuilt on every render compare + /// equal (issue #1702). Other brushes compare by reference. + /// + public virtual bool Equals(InteractionStateValues? other) + => ReferenceEquals(this, other) + || (other is not null && EqualityContract == other.EqualityContract + && Opacity == other.Opacity && Scale == other.Scale && ScaleV == other.ScaleV + && Translation == other.Translation && Rotation == other.Rotation + && AnimationEquality.BrushesEqual(Background, other.Background) + && AnimationEquality.BrushesEqual(Foreground, other.Foreground) + && AnimationEquality.BrushesEqual(BorderBrush, other.BorderBrush)); + + /// Hashes the brushes' presence only, without reading the WinUI brushes. + public override int GetHashCode() + => HashCode.Combine(EqualityContract, Opacity, Scale, ScaleV, Translation, Rotation, + HashCode.Combine(Background is null, Foreground is null, BorderBrush is null)); +} /// /// Configuration for the .InteractionStates() modifier. diff --git a/src/Reactor/Animation/KeyframeBuilder.cs b/src/Reactor/Animation/KeyframeBuilder.cs index dff2272302..4b182f642b 100644 --- a/src/Reactor/Animation/KeyframeBuilder.cs +++ b/src/Reactor/Animation/KeyframeBuilder.cs @@ -10,6 +10,19 @@ public record KeyframeAnimationDef public TimeSpan Duration { get; init; } = TimeSpan.FromMilliseconds(300); public bool Loop { get; init; } public KeyframeDef[] Keyframes { get; init; } = []; + + /// + /// Compares the keyframes by value, so a definition rebuilt on every render compares equal + /// (issue #1702). + /// + public virtual bool Equals(KeyframeAnimationDef? other) + => ReferenceEquals(this, other) + || (other is not null && EqualityContract == other.EqualityContract + && Duration == other.Duration && Loop == other.Loop + && AnimationEquality.SequenceEqual(Keyframes, other.Keyframes)); + + public override int GetHashCode() + => HashCode.Combine(EqualityContract, Duration, Loop, AnimationEquality.SequenceHash(Keyframes)); } /// diff --git a/src/Reactor/Animation/ScrollAnimation.cs b/src/Reactor/Animation/ScrollAnimation.cs index e9e6eaad41..11950e566e 100644 --- a/src/Reactor/Animation/ScrollAnimation.cs +++ b/src/Reactor/Animation/ScrollAnimation.cs @@ -10,7 +10,21 @@ public record ScrollExpression(string Property, string Expression); /// /// Configuration for scroll-linked expression animations. /// -public record ScrollAnimationConfig(ScrollViewer ScrollViewer, ScrollExpression[] Expressions); +public record ScrollAnimationConfig(ScrollViewer ScrollViewer, ScrollExpression[] Expressions) +{ + /// + /// Compares the same and the expressions by value, so a + /// configuration rebuilt on every render compares equal (issue #1702). + /// + public virtual bool Equals(ScrollAnimationConfig? other) + => ReferenceEquals(this, other) + || (other is not null && EqualityContract == other.EqualityContract + && ReferenceEquals(ScrollViewer, other.ScrollViewer) + && AnimationEquality.SequenceEqual(Expressions, other.Expressions)); + + public override int GetHashCode() + => HashCode.Combine(EqualityContract, AnimationEquality.IdentityHash(ScrollViewer), AnimationEquality.SequenceHash(Expressions)); +} /// /// Fluent builder for constructing scroll-linked expression animations. diff --git a/src/Reactor/Core/Element.cs b/src/Reactor/Core/Element.cs index f130f08bb6..9ea3b523f6 100644 --- a/src/Reactor/Core/Element.cs +++ b/src/Reactor/Core/Element.cs @@ -512,10 +512,10 @@ internal static bool HasBehavioralExtras(Element element) internal static bool ExtrasEqual(Element a, Element b) { if (a.Extensions is null && b.Extensions is null) return true; - return (a.Extensions?.Animations ?? default).Equals(b.Extensions?.Animations ?? default) - && AttachedEqual(a.Attached, b.Attached) + return AttachedEqual(a.Attached, b.Attached) && ThemeBindingsEqual(a.ThemeBindings, b.ThemeBindings) - && ResourceOverridesEqual(a.ResourceOverrides, b.ResourceOverrides); + && ResourceOverridesEqual(a.ResourceOverrides, b.ResourceOverrides) + && (a.Extensions?.Animations ?? default).Equals(b.Extensions?.Animations ?? default); } internal static bool ShallowEquals(Element a, Element b) @@ -529,9 +529,9 @@ internal static bool ShallowEquals(Element a, Element b) // provably null on both sides, so the structural comparisons below are // guaranteed to pass. Skip them (and their null-deref property GETs) for // the common no-extras leaf. - if (!(a.Extensions is null && b.Extensions is null)) + bool hasExtras = !(a.Extensions is null && b.Extensions is null); + if (hasExtras) { - if (!(a.Extensions?.Animations ?? default).Equals(b.Extensions?.Animations ?? default)) return false; if (!AttachedEqual(a.Attached, b.Attached)) return false; if (!ThemeBindingsEqual(a.ThemeBindings, b.ThemeBindings)) return false; // Issue #675 — compare ResourceOverrides for symmetry with ThemeBindings: a @@ -541,6 +541,15 @@ internal static bool ShallowEquals(Element a, Element b) if (!ContextValuesEqual(a.ContextValues, b.ContextValues)) return false; } + // Animations compare last (issue #1702): equal declarations rebuilt on every render + // compare by value, which reads WinUI transitions and brushes, so an element whose own + // properties changed declines before paying for that. + return OwnPropsShallowEqual(a, b) + && (!hasExtras || (a.Extensions?.Animations ?? default).Equals(b.Extensions?.Animations ?? default)); + } + + private static bool OwnPropsShallowEqual(Element a, Element b) + { return (a, b) switch { (TextBlockElement ta, TextBlockElement tb) => @@ -1194,14 +1203,7 @@ private static bool RichTextInlineEqual(RichTextInline a, RichTextInline b) /// style fluent chains. Unwrap the underlying Color for the common /// SolidColorBrush case and fall back to ReferenceEquals for everything else. /// - private static bool BrushesEqual(Brush? a, Brush? b) - { - if (ReferenceEquals(a, b)) return true; - if (a is null || b is null) return false; - if (a is SolidColorBrush sa && b is SolidColorBrush sb) - return sa.Color == sb.Color && sa.Opacity == sb.Opacity; - return false; - } + private static bool BrushesEqual(Brush? a, Brush? b) => Animation.AnimationEquality.BrushesEqual(a, b); /// /// Structural transform comparison. D3PathTranslated allocates a fresh @@ -1860,7 +1862,9 @@ public bool Equals(ExtrasSlot other) /// /// Animation declarations compared together when deciding whether an element can skip an update. -/// Record equality includes every field; arrays and native objects retain their existing equality semantics. +/// Record equality includes every field. Modifiers rebuild these on every render, so each +/// declaration type compares by value (issue #1702), and an array field is held in a +/// to compare its elements. /// internal readonly record struct AnimationExtras { @@ -1871,7 +1875,7 @@ internal readonly record struct AnimationExtras internal Microsoft.UI.Reactor.Animation.ElementTransition? ElementTransition { get; init; } internal Microsoft.UI.Reactor.Animation.InteractionStatesConfig? InteractionStates { get; init; } internal Microsoft.UI.Reactor.Animation.StaggerConfig? StaggerConfig { get; init; } - internal Microsoft.UI.Reactor.Animation.KeyframeEntry[]? KeyframeAnimations { get; init; } + internal Microsoft.UI.Reactor.Animation.ValueArray KeyframeAnimations { get; init; } internal Microsoft.UI.Reactor.Animation.ScrollAnimationConfig? ScrollAnimation { get; init; } internal string? ConnectedAnimationKey { get; init; } } @@ -2003,8 +2007,8 @@ public Microsoft.UI.Reactor.Animation.StaggerConfig? StaggerConfig /// public Microsoft.UI.Reactor.Animation.KeyframeEntry[]? KeyframeAnimations { - get => Animations.KeyframeAnimations; - init => Animations = Animations with { KeyframeAnimations = value }; + get => Animations.KeyframeAnimations.Items; + init => Animations = Animations with { KeyframeAnimations = new(value) }; } /// @@ -2723,6 +2727,23 @@ public record ImplicitTransitions public Vector3Transition? Scale { get; init; } public Vector3Transition? Translation { get; init; } public BrushTransition? Background { get; init; } + + /// + /// Compares each channel's transition by its settings, so a transition rebuilt with the same + /// duration on every render compares equal (issue #1702). + /// + public virtual bool Equals(ImplicitTransitions? other) + => ReferenceEquals(this, other) + || (other is not null && EqualityContract == other.EqualityContract + && Animation.AnimationEquality.ImplicitTransitionEqual(Opacity, other.Opacity) + && Animation.AnimationEquality.ImplicitTransitionEqual(Rotation, other.Rotation) + && Animation.AnimationEquality.ImplicitTransitionEqual(Scale, other.Scale) + && Animation.AnimationEquality.ImplicitTransitionEqual(Translation, other.Translation) + && Animation.AnimationEquality.ImplicitTransitionEqual(Background, other.Background)); + + /// Hashes which channels are set, without reading the WinUI transitions. + public override int GetHashCode() => HashCode.Combine(EqualityContract, + Opacity is null, Rotation is null, Scale is null, Translation is null, Background is null); } /// @@ -2735,6 +2756,19 @@ public record ThemeTransitions { public Microsoft.UI.Xaml.Media.Animation.Transition[]? Children { get; init; } public Microsoft.UI.Xaml.Media.Animation.Transition[]? ItemContainer { get; init; } + + /// + /// Compares the transitions in order by type and settings, so transitions rebuilt on every + /// render compare equal (issue #1702). + /// + public virtual bool Equals(ThemeTransitions? other) + => ReferenceEquals(this, other) + || (other is not null && EqualityContract == other.EqualityContract + && Animation.AnimationEquality.ThemeTransitionsEqual(Children, other.Children) + && Animation.AnimationEquality.ThemeTransitionsEqual(ItemContainer, other.ItemContainer)); + + /// Hashes the transition counts, without reading the WinUI transitions. + public override int GetHashCode() => HashCode.Combine(EqualityContract, Children?.Length ?? -1, ItemContainer?.Length ?? -1); } // Note: Transition is in Microsoft.UI.Xaml.Media.Animation (not imported by default in Element.cs) diff --git a/src/Reactor/Core/Reconciler.Update.cs b/src/Reactor/Core/Reconciler.Update.cs index ed6d734be2..e146791848 100644 --- a/src/Reactor/Core/Reconciler.Update.cs +++ b/src/Reactor/Core/Reconciler.Update.cs @@ -586,9 +586,16 @@ private void ShiftForwardedClaims(UIElement control, int frame, Element? layer = ReleaseRemovedKeyframeChannels(target, keyframes, keyframes, KeyframeReleaseStage.BeforePlayback); ApplyKeyframeAnimations(target, keyframes, this); } - // Apply or clear scroll-linked expression animations (.ScrollLinked() modifier) + // Apply or clear scroll-linked expression animations (.ScrollLinked() modifier). + // Expressions are stateless, so equal ones keep running across an unrelated update + // (issue #1702). Another animation on the element may have replaced one, so restart then. if (newEl.ScrollAnimation is not null) - ApplyScrollAnimation(target, newEl.ScrollAnimation); + { + if (replacedControl || !newEl.ScrollAnimation.Equals(oldEl.ScrollAnimation) + || keyframes is not null || newEl.InteractionStates is not null || newEl.LayoutAnimation is not null + || newEl.AnimationConfig is not null || newEl.ImplicitTransitions is not null) + ApplyScrollAnimation(target, newEl.ScrollAnimation); + } else if (oldEl.ScrollAnimation is not null) ClearScrollAnimation(target, oldEl.ScrollAnimation); diff --git a/src/Reactor/Core/Reconciler.cs b/src/Reactor/Core/Reconciler.cs index a65f185794..b6c8d50847 100644 --- a/src/Reactor/Core/Reconciler.cs +++ b/src/Reactor/Core/Reconciler.cs @@ -7480,12 +7480,17 @@ internal static void ForgetCompositionState(UIElement uie) // Scroll-linked expression animation (.ScrollLinked() modifier) // ════════════════════════════════════════════════════════════════ + // Test-only seam: counts ApplyScrollAnimation calls that started expressions, so a selftest + // can tell an unrelated update from one that restarted the scroll animation (issue #1702). + internal static int DebugScrollAnimationStarts; + /// /// Applies scroll-linked expression animations to an element's Visual. /// internal static void ApplyScrollAnimation(UIElement uie, ScrollAnimationConfig config) { if (config.ScrollViewer is null) return; + DebugScrollAnimationStarts++; ElementPool.MarkVisualTaken(uie); var visual = AnimationHelper.GetElementVisual(uie); var compositor = visual.Compositor; diff --git a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs index 4a3db40517..e71520828c 100644 --- a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs +++ b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs @@ -1,10 +1,15 @@ +using System.Numerics; using Microsoft.UI.Composition; using Microsoft.UI.Reactor.Animation; using Microsoft.UI.Reactor.AppTests.Host.SelfTest; using Microsoft.UI.Reactor.Core; +using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; using Microsoft.UI.Xaml.Hosting; +using Microsoft.UI.Xaml.Media; using static Microsoft.UI.Reactor.Factories; +using XamlAnim = Microsoft.UI.Xaml.Media.Animation; namespace Microsoft.UI.Reactor.AppTests.Host.SelfTest.Fixtures; @@ -214,6 +219,166 @@ void Update(Element next) } } + /// + /// Issue #1702: modifiers rebuild their WinUI transitions, brushes and arrays on every render, + /// so an element declaring the same animations again must still skip, while a changed or + /// removed declaration still updates (#1536). + /// + internal class RebuiltExtrasSkip(Harness h, bool childSkip) : SelfTestFixtureBase(h) + { + private readonly ScrollViewer _viewer = new(); + + public override async Task RunAsync() + { + using var motion = Microsoft.UI.Reactor.Navigation.TransitionEngine.OverrideAnimationsEnabled(true); + var name = childSkip ? "RebuiltExtras_Child" : "RebuiltExtras_Direct"; + await Reconciles(name); + await ScrollRestarts(name); + if (!childSkip) Declarations(); + } + + private Element Wrap(Element element) => childSkip ? VStack(element) : element; + + private ButtonElement Render(int ms = 200, byte red = 255, double entrance = 20, int trigger = 1, string expression = "0") + => Button("Go") + .OpacityTransition(TimeSpan.FromMilliseconds(ms)) + .RotationTransition(TimeSpan.FromMilliseconds(ms)) + .ScaleTransition(new Vector3Transition { Duration = TimeSpan.FromMilliseconds(ms), Components = Vector3TransitionComponents.X }) + .TranslationTransition(new Vector3Transition { Duration = TimeSpan.FromMilliseconds(ms) }) + .WithTransitions(new XamlAnim.EntranceThemeTransition { FromVerticalOffset = entrance }, new XamlAnim.RepositionThemeTransition()) + .InteractionStates(s => s.PointerOver(scale: 1.05f, background: new SolidColorBrush(global::Windows.UI.Color.FromArgb(255, red, 0, 0)))) + .Keyframes("pulse", trigger, static k => k.Duration(300).At(0f, scale: Vector3.One).At(1f, scale: new Vector3(1.1f))) + .ScrollLinked(_viewer, s => s.Expression("CenterPoint.X", expression)); + + private async Task Reconciles(string name) + { + using var reconciler = new Reconciler(); + var current = Wrap(Render()); + var root = reconciler.Mount(current, static () => { })!; + var button = childSkip ? (Button)((StackPanel)root).Children[0] : (Button)root; + H.SetContent(root); + try + { + await Harness.Render(); + var visual = ElementCompositionPreview.GetElementVisual(button); + bool HasOpacityDuration(int milliseconds) => + visual.ImplicitAnimations?.ContainsKey("Opacity") == true + && visual.ImplicitAnimations["Opacity"] is ScalarKeyFrameAnimation scalar + && scalar.Duration == TimeSpan.FromMilliseconds(milliseconds); + bool Skipped(Element next) + { + int skipped = reconciler.DebugElementsSkipped; + var wrapped = Wrap(next); + H.Check(name + "_SameControl", reconciler.Update(current, wrapped, root, static () => { }) is null); + current = wrapped; + return reconciler.DebugElementsSkipped == skipped + 1; + } + + H.Check(name + "_InitialTransition", HasOpacityDuration(200)); + H.Check(name + "_EqualSkips", Skipped(Render())); + H.Check(name + "_ChangedDurationUpdates", !Skipped(Render(ms: 800))); + H.Check(name + "_ChangedDurationApplied", HasOpacityDuration(800)); + H.Check(name + "_EqualAfterChangeSkips", Skipped(Render(ms: 800))); + H.Check(name + "_ChangedBrushUpdates", !Skipped(Render(ms: 800, red: 128))); + H.Check(name + "_ChangedThemeTransitionUpdates", !Skipped(Render(ms: 800, red: 128, entrance: 40))); + H.Check(name + "_ChangedThemeTransitionApplied", button.ContentTransitions is { Count: 2 } transitions + && transitions[0] is XamlAnim.EntranceThemeTransition { FromVerticalOffset: 40 }); + H.Check(name + "_ChangedTriggerUpdates", !Skipped(Render(ms: 800, red: 128, entrance: 40, trigger: 2))); + H.Check(name + "_ChangedScrollUpdates", !Skipped(Render(ms: 800, red: 128, entrance: 40, trigger: 2, expression: "1"))); + H.Check(name + "_RemovedUpdates", !Skipped(Button("Go"))); + H.Check(name + "_RemovedTransition", visual.ImplicitAnimations?.ContainsKey("Opacity") != true); + } + finally + { + reconciler.UnmountChild(root); + H.SetContent(null); + } + } + + // Expressions are stateless, so an update that leaves .ScrollLinked() unchanged keeps them running. + private async Task ScrollRestarts(string name) + { + using var reconciler = new Reconciler(); + ButtonElement Linked(double margin = 0, string value = "0") + => Button("Scroll").Margin(margin).ScrollLinked(_viewer, s => s.Expression("CenterPoint.X", value)); + int starts = Reconciler.DebugScrollAnimationStarts; + var current = Wrap(Linked()); + var root = reconciler.Mount(current, static () => { })!; + H.SetContent(root); + try + { + await Harness.Render(); + H.Check(name + "_ScrollMountStarts", Reconciler.DebugScrollAnimationStarts == starts + 1); + int Restarts(Element next) + { + int before = Reconciler.DebugScrollAnimationStarts; + var wrapped = Wrap(next); + H.Check(name + "_ScrollSameControl", reconciler.Update(current, wrapped, root, static () => { }) is null); + current = wrapped; + return Reconciler.DebugScrollAnimationStarts - before; + } + + H.Check(name + "_ScrollEqualKeeps", Restarts(Linked()) == 0); + H.Check(name + "_ScrollUnrelatedUpdateKeeps", Restarts(Linked(margin: 4)) == 0); + H.Check(name + "_ScrollChangedRestarts", Restarts(Linked(margin: 4, value: "1")) == 1); + // Another animation on the element may have replaced an expression, so restart then. + H.Check(name + "_ScrollWithTransitionRestarts", Restarts(Linked(margin: 8, value: "1").OpacityTransition()) == 1); + } + finally + { + reconciler.UnmountChild(root); + H.SetContent(null); + } + } + + private void Declarations() + { + static bool Same(Element a, Element b) => Element.CanSkipUpdate(a, b) && Element.CanSkipUpdate(b, a); + H.Check("RebuiltExtras_BackgroundEqual", Same(VStack().BackgroundTransition(TimeSpan.FromMilliseconds(200)), + VStack().BackgroundTransition(TimeSpan.FromMilliseconds(200)))); + H.Check("RebuiltExtras_BackgroundChanged", !Same(VStack().BackgroundTransition(TimeSpan.FromMilliseconds(200)), + VStack().BackgroundTransition(TimeSpan.FromMilliseconds(800)))); + H.Check("RebuiltExtras_ScaleComponentsChanged", !Same( + Button("Go").ScaleTransition(new Vector3Transition { Components = Vector3TransitionComponents.X }), + Button("Go").ScaleTransition(new Vector3Transition { Components = Vector3TransitionComponents.Y }))); + H.Check("RebuiltExtras_OtherViewerChanged", !Same( + Button("Go").ScrollLinked(_viewer, static s => s.FadeOut(0, 100)), + Button("Go").ScrollLinked(new ScrollViewer(), static s => s.FadeOut(0, 100)))); + H.Check("RebuiltExtras_GradientBrushByReference", !Same( + Button("Go").InteractionStates(static s => s.PointerOver(background: new LinearGradientBrush())), + Button("Go").InteractionStates(static s => s.PointerOver(background: new LinearGradientBrush())))); + H.Check("RebuiltExtras_ItemContainerEqual", Same( + Button("Go").ItemContainerTransitions(new XamlAnim.AddDeleteThemeTransition()), + Button("Go").ItemContainerTransitions(new XamlAnim.AddDeleteThemeTransition()))); + + void Theme(string type, Func make, Func? changed) + { + H.Check("RebuiltExtras_" + type + "_Equal", Same(Button("Go").WithTransitions(make()), Button("Go").WithTransitions(make()))); + if (changed is not null) + H.Check("RebuiltExtras_" + type + "_Changed", !Same(Button("Go").WithTransitions(make()), Button("Go").WithTransitions(changed()))); + } + Theme("Entrance", static () => new XamlAnim.EntranceThemeTransition { FromHorizontalOffset = 10 }, + static () => new XamlAnim.EntranceThemeTransition { FromHorizontalOffset = 20 }); + Theme("EntranceStagger", static () => new XamlAnim.EntranceThemeTransition { IsStaggeringEnabled = true }, + static () => new XamlAnim.EntranceThemeTransition { IsStaggeringEnabled = false }); + Theme("Content", static () => new XamlAnim.ContentThemeTransition { VerticalOffset = 10 }, + static () => new XamlAnim.ContentThemeTransition { VerticalOffset = 20 }); + Theme("Popup", static () => new XamlAnim.PopupThemeTransition { FromVerticalOffset = 10 }, + static () => new XamlAnim.PopupThemeTransition { FromVerticalOffset = 20 }); + Theme("Reposition", static () => new XamlAnim.RepositionThemeTransition { IsStaggeringEnabled = true }, + static () => new XamlAnim.RepositionThemeTransition { IsStaggeringEnabled = false }); + Theme("EdgeUI", static () => new XamlAnim.EdgeUIThemeTransition { Edge = EdgeTransitionLocation.Left }, + static () => new XamlAnim.EdgeUIThemeTransition { Edge = EdgeTransitionLocation.Right }); + Theme("Pane", static () => new XamlAnim.PaneThemeTransition { Edge = EdgeTransitionLocation.Left }, + static () => new XamlAnim.PaneThemeTransition { Edge = EdgeTransitionLocation.Right }); + var info = new XamlAnim.SlideNavigationTransitionInfo(); + Theme("Navigation", () => new XamlAnim.NavigationThemeTransition { DefaultNavigationTransitionInfo = info }, + static () => new XamlAnim.NavigationThemeTransition { DefaultNavigationTransitionInfo = new XamlAnim.SlideNavigationTransitionInfo() }); + Theme("AddDelete", static () => new XamlAnim.AddDeleteThemeTransition(), static () => new XamlAnim.ReorderThemeTransition()); + Theme("Reorder", static () => new XamlAnim.ReorderThemeTransition(), null); + } + } + internal class MergesWithLayoutAnimation(Harness h) : SelfTestFixtureBase(h) { public override async Task RunAsync() diff --git a/tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs b/tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs index 180706cb0c..f5de3ec222 100644 --- a/tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs +++ b/tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs @@ -977,6 +977,8 @@ internal static class SelfTestFixtureRegistry ("Animate_ConfigurationChildSkip", static harness => new AnimateModifierTests.ConfigurationAcrossUpdates(harness, childSkip: true)), ("Animate_ExtrasAcrossUpdates", static harness => new AnimateModifierTests.ExtrasAcrossUpdates(harness, childSkip: false)), ("Animate_ExtrasChildSkip", static harness => new AnimateModifierTests.ExtrasAcrossUpdates(harness, childSkip: true)), + ("Animate_RebuiltExtrasSkip", static harness => new AnimateModifierTests.RebuiltExtrasSkip(harness, childSkip: false)), + ("Animate_RebuiltExtrasChildSkip", static harness => new AnimateModifierTests.RebuiltExtrasSkip(harness, childSkip: true)), // Animation system — InteractionStates ("InterState_StateMachineTransitions", static harness => new InteractionStatesTests.StateMachineTransitions(harness)), ("InterState_PressedInheritsPointerOver", static harness => new InteractionStatesTests.PressedInheritsFromPointerOver(harness)), diff --git a/tests/Reactor.Tests/AnimationExtrasEqualityTests.cs b/tests/Reactor.Tests/AnimationExtrasEqualityTests.cs index f2130186be..f00dd54d02 100644 --- a/tests/Reactor.Tests/AnimationExtrasEqualityTests.cs +++ b/tests/Reactor.Tests/AnimationExtrasEqualityTests.cs @@ -41,6 +41,29 @@ public void Configuration_Changes_DeclineSkip_While_Equal_Values_Skip(string pro Assert.False(Element.HasBehavioralExtras(cleared)); } + // Issue #1702: each render rebuilds these declarations, so identical ones must still skip. + [Fact] + public void Rebuilt_Equal_Keyframes_And_ScrollLinked_Skip() + { + static Element Render(int trigger, float opacity = 0.5f, float parallax = 0.5f) => Button("Go") + .Keyframes("pulse", trigger, k => k.Duration(400).At(0f, opacity: 1f).At(1f, opacity: opacity, easing: Easing.EaseOut)) + .ScrollLinked(null!, s => s.Parallax(parallax).FadeOut(0, 100)); + + Assert.True(Element.ShallowEquals(Render(1), Render(1))); + Assert.True(Element.CanSkipUpdate(Render(1), Render(1))); + Assert.True(Element.ExtrasEqual(Render(1), Render(1))); + Assert.Equal(Render(1), Render(1)); + Assert.Equal(Render(1).GetHashCode(), Render(1).GetHashCode()); + + foreach (var changed in new[] { Render(2), Render(1, opacity: 0.4f), Render(1, parallax: 0.6f), + Render(1) with { ScrollAnimation = null }, Render(1) with { KeyframeAnimations = null } }) + { + Assert.False(Element.ShallowEquals(Render(1), changed)); + Assert.False(Element.CanSkipUpdate(changed, Render(1))); + Assert.False(Element.ExtrasEqual(Render(1), changed)); + } + } + [Fact] public void Clearing_One_Animation_Preserves_Other_Extras_And_The_Original_Record() { @@ -77,17 +100,18 @@ private static (object First, object Equal, object? Changed) Values(string prope // Native transition values are exercised in the WinUI selftest. return (new ImplicitTransitions(), new ImplicitTransitions(), null); case nameof(Element.ThemeTransitions): - // Arrays keep reference equality, including two distinct empty arrays. - var children = new XamlTransition[0]; - return (new ThemeTransitions { Children = children }, new ThemeTransitions { Children = children }, - new ThemeTransitions { Children = new XamlTransition[0] }); + // Native transition values are exercised in the WinUI selftest. Distinct + // arrays with equal contents compare equal (issue #1702). + return (new ThemeTransitions { Children = new XamlTransition[0] }, new ThemeTransitions { Children = new XamlTransition[0] }, + new ThemeTransitions { ItemContainer = new XamlTransition[0] }); case nameof(Element.InteractionStates): return (new InteractionStatesConfig(PointerOver: new(Opacity: 0.5f)), new InteractionStatesConfig(PointerOver: new(Opacity: 0.5f)), new InteractionStatesConfig(PointerOver: new(Opacity: 0.8f))); case nameof(Element.KeyframeAnimations): - var entries = new[] { new KeyframeEntry("pulse", 1, new KeyframeAnimationDef()) }; - return (entries, entries, entries.ToArray()); + // Distinct arrays with equal entries compare equal; a new trigger replays (issue #1702). + static KeyframeEntry[] Entries(int trigger) => [new KeyframeEntry("pulse", trigger, new KeyframeAnimationDef())]; + return (Entries(1), Entries(1), Entries(2)); case nameof(Element.StaggerConfig): return (new StaggerConfig(TimeSpan.FromMilliseconds(20)), new StaggerConfig(TimeSpan.FromMilliseconds(20)), new StaggerConfig(TimeSpan.FromMilliseconds(40))); From a461b855c09fb1c42ea4dea0e700b880ee097d47 Mon Sep 17 00:00:00 2001 From: Alexandre Zollinger Chohfi Date: Wed, 25 Nov 2026 15:07:52 -0800 Subject: [PATCH 2/5] Address review findings for the animation skip fix (#1702) - Restart scroll expressions on every non-skipped update again. A modifier write on the same channel can replace one, and the value-equality skip already avoids the restarts the issue reported. - Compare keyframe channel owner scopes by sequence, so a skipped equal render doesn't block the deferred modifier reset. - Refresh every element when the "Animation effects" setting changes, since implicit transitions apply that gate and equal elements now skip. - Compare navigation transition infos by type and setting. - Move brush equality to BrushHelper, and note the UI-thread requirement on the public Equals overrides. - Cover each hand-compared field, and fix the docs and CHANGELOG wording. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 10 +-- docs/_pipeline/templates/animation.md.dt | 8 +- docs/guide/animation.md | 8 +- src/Reactor/Animation/AnimationEquality.cs | 22 +++-- src/Reactor/Animation/InteractionStates.cs | 7 +- src/Reactor/Core/Element.cs | 7 +- src/Reactor/Core/Reconciler.Update.cs | 11 +-- src/Reactor/Core/Reconciler.cs | 6 +- src/Reactor/Elements/BrushHelper.cs | 15 ++++ src/Reactor/Hosting/ReactorHost.cs | 13 ++- .../SelfTest/Fixtures/AnimateModifierTests.cs | 83 +++++++++++++++++-- .../Fixtures/TransformModifierFixtures.cs | 23 +++++ .../AnimationExtrasEqualityTests.cs | 29 ++++++- .../Core/ReducedMotionSubscriptionTests.cs | 3 +- 14 files changed, 195 insertions(+), 50 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 44a7e5e6a4..fdc77f230d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -211,11 +211,11 @@ Conventions for contributors: `.OpacityTransition()`, `.WithTransitions()` or `.InteractionStates()` skip unchanged renders again (issue #1702; follow-up to #1536, spec 014).** Each render rebuilds these declarations with new arrays and WinUI objects, and the skip check compared those by reference, so such an element - always ran a full update. `.ScrollLinked()` also restarted its expressions every time. The - declarations now compare by value: keyframes, scroll expressions with the same `ScrollViewer`, - transition durations and settings, and solid brushes by color. A changed or removed declaration - still updates. An update for another reason no longer restarts unchanged scroll expressions, - unless the element also declares another animation. + always ran a full update. `.ScrollLinked()` also restarted its expressions on every parent render. + The declarations now compare by value: keyframes, scroll expressions with the same `ScrollViewer`, + transition durations and settings, and solid brushes by color and opacity. A changed or removed + declaration still updates. Turning Windows' "Animation effects" setting on or off now refreshes + every element in a Reactor window, so implicit transitions on unchanged elements follow it too. - **Unmount clears a `.Ref` declared on a keyed `Memo` or a `ModifiedElement` (issue #1659).** Those layers mount no control of their own, so the ref points at the control their child mounted, and diff --git a/docs/_pipeline/templates/animation.md.dt b/docs/_pipeline/templates/animation.md.dt index b5d2bd270e..d4337b9e8c 100644 --- a/docs/_pipeline/templates/animation.md.dt +++ b/docs/_pipeline/templates/animation.md.dt @@ -46,9 +46,11 @@ only `.LayoutAnimation()`'s duration updates the layout animation on the next re Unchanged declarations still skip updates, even though each render rebuilds them. `.Keyframes()` and `.ScrollLinked()` compare their keyframes and expressions, implicit transitions such as `.OpacityTransition()` compare their -duration, `.WithTransitions()` compares each theme transition's settings, and -`.InteractionStates()` compares solid brushes by color. Other brushes, and a -`.ScrollLinked()` driven by a different `ScrollViewer`, still count as a change. +duration (and axes, for scale and translation), `.WithTransitions()` compares +each theme transition's settings, and `.InteractionStates()` compares solid +brushes by color and opacity. Other brushes, a `.ScrollLinked()` driven by a +different `ScrollViewer`, a continuum navigation transition, and a transition +type Reactor doesn't know still count as a change. ## Reference diff --git a/docs/guide/animation.md b/docs/guide/animation.md index ce8889a6e4..e5365c255f 100644 --- a/docs/guide/animation.md +++ b/docs/guide/animation.md @@ -33,9 +33,11 @@ only `.LayoutAnimation()`'s duration updates the layout animation on the next re Unchanged declarations still skip updates, even though each render rebuilds them. `.Keyframes()` and `.ScrollLinked()` compare their keyframes and expressions, implicit transitions such as `.OpacityTransition()` compare their -duration, `.WithTransitions()` compares each theme transition's settings, and -`.InteractionStates()` compares solid brushes by color. Other brushes, and a -`.ScrollLinked()` driven by a different `ScrollViewer`, still count as a change. +duration (and axes, for scale and translation), `.WithTransitions()` compares +each theme transition's settings, and `.InteractionStates()` compares solid +brushes by color and opacity. Other brushes, a `.ScrollLinked()` driven by a +different `ScrollViewer`, a continuum navigation transition, and a transition +type Reactor doesn't know still count as a change. ## Reference diff --git a/src/Reactor/Animation/AnimationEquality.cs b/src/Reactor/Animation/AnimationEquality.cs index 19103b261a..ad403e9f17 100644 --- a/src/Reactor/Animation/AnimationEquality.cs +++ b/src/Reactor/Animation/AnimationEquality.cs @@ -1,6 +1,5 @@ using System.Runtime.CompilerServices; using Microsoft.UI.Xaml; -using Microsoft.UI.Xaml.Media; using Microsoft.UI.Xaml.Media.Animation; using XamlTransition = Microsoft.UI.Xaml.Media.Animation.Transition; @@ -74,7 +73,7 @@ private static bool ThemeTransitionEqual(XamlTransition? a, XamlTransition? b) (EdgeUIThemeTransition ea, EdgeUIThemeTransition eb) => ea.Edge == eb.Edge, (PaneThemeTransition pa, PaneThemeTransition pb) => pa.Edge == pb.Edge, (NavigationThemeTransition na, NavigationThemeTransition nb) => - ReferenceEquals(na.DefaultNavigationTransitionInfo, nb.DefaultNavigationTransitionInfo), + NavigationInfoEqual(na.DefaultNavigationTransitionInfo, nb.DefaultNavigationTransitionInfo), (AddDeleteThemeTransition, AddDeleteThemeTransition) => true, (ReorderThemeTransition, ReorderThemeTransition) => true, _ => false, @@ -82,16 +81,21 @@ private static bool ThemeTransitionEqual(XamlTransition? a, XamlTransition? b) } /// - /// A solid brush compares by color and opacity, the same rule element brush properties use. - /// Other brushes compare by reference. + /// Navigation transition infos compare by type and setting. A continuum transition names + /// an exit element, so it compares by reference. /// - internal static bool BrushesEqual(Brush? a, Brush? b) + private static bool NavigationInfoEqual(NavigationTransitionInfo? a, NavigationTransitionInfo? b) { if (ReferenceEquals(a, b)) return true; - if (a is null || b is null) return false; - if (a is SolidColorBrush sa && b is SolidColorBrush sb) - return sa.Color == sb.Color && sa.Opacity == sb.Opacity; - return false; + return (a, b) switch + { + (SlideNavigationTransitionInfo sa, SlideNavigationTransitionInfo sb) => sa.Effect == sb.Effect, + (CommonNavigationTransitionInfo ca, CommonNavigationTransitionInfo cb) => ca.IsStaggeringEnabled == cb.IsStaggeringEnabled, + (DrillInNavigationTransitionInfo, DrillInNavigationTransitionInfo) => true, + (EntranceNavigationTransitionInfo, EntranceNavigationTransitionInfo) => true, + (SuppressNavigationTransitionInfo, SuppressNavigationTransitionInfo) => true, + _ => false, + }; } /// Hash for a value compared by reference. diff --git a/src/Reactor/Animation/InteractionStates.cs b/src/Reactor/Animation/InteractionStates.cs index f66cf171e1..e2075aa20a 100644 --- a/src/Reactor/Animation/InteractionStates.cs +++ b/src/Reactor/Animation/InteractionStates.cs @@ -25,14 +25,15 @@ public record InteractionStateValues( /// Compares solid brushes by color and opacity, so brushes rebuilt on every render compare /// equal (issue #1702). Other brushes compare by reference. /// + /// Reads the brushes, so call it on the UI thread that created them. public virtual bool Equals(InteractionStateValues? other) => ReferenceEquals(this, other) || (other is not null && EqualityContract == other.EqualityContract && Opacity == other.Opacity && Scale == other.Scale && ScaleV == other.ScaleV && Translation == other.Translation && Rotation == other.Rotation - && AnimationEquality.BrushesEqual(Background, other.Background) - && AnimationEquality.BrushesEqual(Foreground, other.Foreground) - && AnimationEquality.BrushesEqual(BorderBrush, other.BorderBrush)); + && BrushHelper.BrushesEqual(Background, other.Background) + && BrushHelper.BrushesEqual(Foreground, other.Foreground) + && BrushHelper.BrushesEqual(BorderBrush, other.BorderBrush)); /// Hashes the brushes' presence only, without reading the WinUI brushes. public override int GetHashCode() diff --git a/src/Reactor/Core/Element.cs b/src/Reactor/Core/Element.cs index 9ea3b523f6..9c84e95dad 100644 --- a/src/Reactor/Core/Element.cs +++ b/src/Reactor/Core/Element.cs @@ -1203,7 +1203,7 @@ private static bool RichTextInlineEqual(RichTextInline a, RichTextInline b) /// style fluent chains. Unwrap the underlying Color for the common /// SolidColorBrush case and fall back to ReferenceEquals for everything else. /// - private static bool BrushesEqual(Brush? a, Brush? b) => Animation.AnimationEquality.BrushesEqual(a, b); + private static bool BrushesEqual(Brush? a, Brush? b) => BrushHelper.BrushesEqual(a, b); /// /// Structural transform comparison. D3PathTranslated allocates a fresh @@ -2732,6 +2732,7 @@ public record ImplicitTransitions /// Compares each channel's transition by its settings, so a transition rebuilt with the same /// duration on every render compares equal (issue #1702). /// + /// Reads the WinUI transitions, so call it on the UI thread that created them. public virtual bool Equals(ImplicitTransitions? other) => ReferenceEquals(this, other) || (other is not null && EqualityContract == other.EqualityContract @@ -2759,8 +2760,10 @@ public record ThemeTransitions /// /// Compares the transitions in order by type and settings, so transitions rebuilt on every - /// render compare equal (issue #1702). + /// render compare equal (issue #1702). A transition type Reactor doesn't know, and a + /// ContinuumNavigationTransitionInfo, compare by reference. /// + /// Reads the WinUI transitions, so call it on the UI thread that created them. public virtual bool Equals(ThemeTransitions? other) => ReferenceEquals(this, other) || (other is not null && EqualityContract == other.EqualityContract diff --git a/src/Reactor/Core/Reconciler.Update.cs b/src/Reactor/Core/Reconciler.Update.cs index e146791848..ed6d734be2 100644 --- a/src/Reactor/Core/Reconciler.Update.cs +++ b/src/Reactor/Core/Reconciler.Update.cs @@ -586,16 +586,9 @@ private void ShiftForwardedClaims(UIElement control, int frame, Element? layer = ReleaseRemovedKeyframeChannels(target, keyframes, keyframes, KeyframeReleaseStage.BeforePlayback); ApplyKeyframeAnimations(target, keyframes, this); } - // Apply or clear scroll-linked expression animations (.ScrollLinked() modifier). - // Expressions are stateless, so equal ones keep running across an unrelated update - // (issue #1702). Another animation on the element may have replaced one, so restart then. + // Apply or clear scroll-linked expression animations (.ScrollLinked() modifier) if (newEl.ScrollAnimation is not null) - { - if (replacedControl || !newEl.ScrollAnimation.Equals(oldEl.ScrollAnimation) - || keyframes is not null || newEl.InteractionStates is not null || newEl.LayoutAnimation is not null - || newEl.AnimationConfig is not null || newEl.ImplicitTransitions is not null) - ApplyScrollAnimation(target, newEl.ScrollAnimation); - } + ApplyScrollAnimation(target, newEl.ScrollAnimation); else if (oldEl.ScrollAnimation is not null) ClearScrollAnimation(target, oldEl.ScrollAnimation); diff --git a/src/Reactor/Core/Reconciler.cs b/src/Reactor/Core/Reconciler.cs index b6c8d50847..d8cec1ec21 100644 --- a/src/Reactor/Core/Reconciler.cs +++ b/src/Reactor/Core/Reconciler.cs @@ -7335,7 +7335,9 @@ private static void ReleaseRemovedKeyframeChannels(UIElement uie, KeyframeEntry[ void Release(AnimateProperty property, string name) { - if (!owners.TryGetValue(property, out var owner) || !ReferenceEquals(owner.Scope, previous)) return; + // Sequence equality: an equal render skips its update, so the scope recorded at the + // last apply can be an equal array from an earlier render (issue #1702). + if (!owners.TryGetValue(property, out var owner) || !AnimationEquality.SequenceEqual(owner.Scope, previous)) return; if (current is not null) { var nameKey = owner.Entry.Name; @@ -7481,7 +7483,7 @@ internal static void ForgetCompositionState(UIElement uie) // ════════════════════════════════════════════════════════════════ // Test-only seam: counts ApplyScrollAnimation calls that started expressions, so a selftest - // can tell an unrelated update from one that restarted the scroll animation (issue #1702). + // can tell a skipped render from one that restarted the scroll animation (issue #1702). internal static int DebugScrollAnimationStarts; /// diff --git a/src/Reactor/Elements/BrushHelper.cs b/src/Reactor/Elements/BrushHelper.cs index f57f2811db..ef66b1b3f3 100644 --- a/src/Reactor/Elements/BrushHelper.cs +++ b/src/Reactor/Elements/BrushHelper.cs @@ -99,4 +99,19 @@ private static bool TryParseHex(string hex, out global::Windows.UI.Color parsed) parsed = FallbackGray; return false; } + + /// + /// Structural brush comparison. caches the parsed color but returns a + /// fresh on every call (brushes have thread affinity), so a + /// solid brush compares by color and opacity. Other brushes compare by reference. Reads the + /// brushes, so it runs on the UI thread. + /// + internal static bool BrushesEqual(Brush? a, Brush? b) + { + if (ReferenceEquals(a, b)) return true; + if (a is null || b is null) return false; + if (a is SolidColorBrush sa && b is SolidColorBrush sb) + return sa.Color == sb.Color && sa.Opacity == sb.Opacity; + return false; + } } diff --git a/src/Reactor/Hosting/ReactorHost.cs b/src/Reactor/Hosting/ReactorHost.cs index 87cbd35f82..3720beae00 100644 --- a/src/Reactor/Hosting/ReactorHost.cs +++ b/src/Reactor/Hosting/ReactorHost.cs @@ -1590,8 +1590,17 @@ private void OnColorValuesChanged( private void OnAnimationsEnabledChanged( global::Windows.UI.ViewManagement.UISettings sender, object args) + => ApplyAnimationsEnabled(sender.AnimationsEnabled); + + /// + /// Applies a change of the "Animation effects" setting. Implicit transitions check it when + /// they are applied, and an unchanged element skips its update, so this requests a + /// resource-refresh pass, which updates every element, rather than a plain render + /// (issue #1702). Internal so a selftest can drive it; any thread. + /// + internal void ApplyAnimationsEnabled(bool animationsEnabled) { - var value = !sender.AnimationsEnabled; + var value = !animationsEnabled; // A coincident palette change re-reads the same field through // OnColorValuesChanged, so bail out when nothing actually moved. if (value == _isReducedMotion) return; @@ -1600,6 +1609,8 @@ private void OnAnimationsEnabledChanged( // [ThreadStatic] and this runs on the WinRT notification thread, so a push here // would write a copy the render thread never reads. Render() pushes on the UI // thread every frame, so RequestRender is what actually propagates this. + if (_disposed) return; + _reconciler.RequestResourceRefresh(); RequestRender(); } diff --git a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs index e71520828c..fce8cc7477 100644 --- a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs +++ b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs @@ -234,7 +234,44 @@ public override async Task RunAsync() var name = childSkip ? "RebuiltExtras_Child" : "RebuiltExtras_Direct"; await Reconciles(name); await ScrollRestarts(name); - if (!childSkip) Declarations(); + if (!childSkip) + { + Declarations(); + await AnimationSettingChanges(); + } + } + + // Implicit transitions check the "Animation effects" setting when they're applied, and an + // equal render skips its update, so a change of the setting refreshes every element. + private async Task AnimationSettingChanges() + { + Microsoft.UI.Reactor.Navigation.TransitionEngine.OverrideAnimationsEnabled(true); + var host = H.CreateHost(); + host.Mount(_ => VStack(TextBlock("Motion").OpacityTransition(TimeSpan.FromMilliseconds(200)).AutomationId("motion-target"))); + await Harness.Render(); + host.ApplyAnimationsEnabled(true); + await Harness.Render(); + var target = H.FindControl(t => + Microsoft.UI.Xaml.Automation.AutomationProperties.GetAutomationId(t) == "motion-target"); + H.Check("RebuiltExtras_MotionMounted", target is not null); + if (target is null) return; + var visual = ElementCompositionPreview.GetElementVisual(target); + bool HasKey() => visual.ImplicitAnimations?.ContainsKey("Opacity") == true; + H.Check("RebuiltExtras_MotionKeyInstalled", HasKey()); + + Microsoft.UI.Reactor.Navigation.TransitionEngine.OverrideAnimationsEnabled(false); + host.RequestRender(); + await Harness.Render(); + // Positive control: the equal render skips, so only the setting change can drop the key. + H.Check("RebuiltExtras_MotionEqualRenderSkips", HasKey()); + host.ApplyAnimationsEnabled(false); + await Harness.Render(); + H.Check("RebuiltExtras_MotionOffDropsKey", !HasKey()); + + Microsoft.UI.Reactor.Navigation.TransitionEngine.OverrideAnimationsEnabled(true); + host.ApplyAnimationsEnabled(true); + await Harness.Render(); + H.Check("RebuiltExtras_MotionOnRestoresKey", HasKey()); } private Element Wrap(Element element) => childSkip ? VStack(element) : element; @@ -295,7 +332,8 @@ bool Skipped(Element next) } } - // Expressions are stateless, so an update that leaves .ScrollLinked() unchanged keeps them running. + // An equal render skips its update, so it doesn't restart the expressions. Any other + // update re-applies them, since a modifier write can have replaced one. private async Task ScrollRestarts(string name) { using var reconciler = new Reconciler(); @@ -319,10 +357,8 @@ int Restarts(Element next) } H.Check(name + "_ScrollEqualKeeps", Restarts(Linked()) == 0); - H.Check(name + "_ScrollUnrelatedUpdateKeeps", Restarts(Linked(margin: 4)) == 0); + H.Check(name + "_ScrollOtherUpdateRestarts", Restarts(Linked(margin: 4)) == 1); H.Check(name + "_ScrollChangedRestarts", Restarts(Linked(margin: 4, value: "1")) == 1); - // Another animation on the element may have replaced an expression, so restart then. - H.Check(name + "_ScrollWithTransitionRestarts", Restarts(Linked(margin: 8, value: "1").OpacityTransition()) == 1); } finally { @@ -341,6 +377,23 @@ private void Declarations() H.Check("RebuiltExtras_ScaleComponentsChanged", !Same( Button("Go").ScaleTransition(new Vector3Transition { Components = Vector3TransitionComponents.X }), Button("Go").ScaleTransition(new Vector3Transition { Components = Vector3TransitionComponents.Y }))); + H.Check("RebuiltExtras_RotationChanged", !Same(Button("Go").RotationTransition(TimeSpan.FromMilliseconds(200)), + Button("Go").RotationTransition(TimeSpan.FromMilliseconds(800)))); + H.Check("RebuiltExtras_TranslationChanged", !Same( + Button("Go").TranslationTransition(new Vector3Transition { Duration = TimeSpan.FromMilliseconds(200) }), + Button("Go").TranslationTransition(new Vector3Transition { Duration = TimeSpan.FromMilliseconds(800) }))); + H.Check("RebuiltExtras_ChannelAddedChanged", !Same(Button("Go").RotationTransition(), + Button("Go").RotationTransition().OpacityTransition())); + SolidColorBrush Solid(byte red) => new(global::Windows.UI.Color.FromArgb(255, red, 0, 0)); + H.Check("RebuiltExtras_ForegroundEqual", Same( + Button("Go").InteractionStates(s => s.PointerOver(foreground: Solid(255), borderBrush: Solid(255))), + Button("Go").InteractionStates(s => s.PointerOver(foreground: Solid(255), borderBrush: Solid(255))))); + H.Check("RebuiltExtras_ForegroundChanged", !Same( + Button("Go").InteractionStates(s => s.PointerOver(foreground: Solid(255))), + Button("Go").InteractionStates(s => s.PointerOver(foreground: Solid(128))))); + H.Check("RebuiltExtras_BorderBrushChanged", !Same( + Button("Go").InteractionStates(s => s.PointerOver(borderBrush: Solid(255))), + Button("Go").InteractionStates(s => s.PointerOver(borderBrush: Solid(128))))); H.Check("RebuiltExtras_OtherViewerChanged", !Same( Button("Go").ScrollLinked(_viewer, static s => s.FadeOut(0, 100)), Button("Go").ScrollLinked(new ScrollViewer(), static s => s.FadeOut(0, 100)))); @@ -350,6 +403,9 @@ private void Declarations() H.Check("RebuiltExtras_ItemContainerEqual", Same( Button("Go").ItemContainerTransitions(new XamlAnim.AddDeleteThemeTransition()), Button("Go").ItemContainerTransitions(new XamlAnim.AddDeleteThemeTransition()))); + H.Check("RebuiltExtras_ItemContainerChanged", !Same( + Button("Go").WithTransitions(new XamlAnim.AddDeleteThemeTransition()).ItemContainerTransitions(new XamlAnim.AddDeleteThemeTransition()), + Button("Go").WithTransitions(new XamlAnim.AddDeleteThemeTransition()).ItemContainerTransitions(new XamlAnim.ReorderThemeTransition()))); void Theme(string type, Func make, Func? changed) { @@ -363,17 +419,28 @@ void Theme(string type, Func make, Func new XamlAnim.EntranceThemeTransition { IsStaggeringEnabled = false }); Theme("Content", static () => new XamlAnim.ContentThemeTransition { VerticalOffset = 10 }, static () => new XamlAnim.ContentThemeTransition { VerticalOffset = 20 }); + Theme("ContentHorizontal", static () => new XamlAnim.ContentThemeTransition { HorizontalOffset = 10 }, + static () => new XamlAnim.ContentThemeTransition { HorizontalOffset = 20 }); Theme("Popup", static () => new XamlAnim.PopupThemeTransition { FromVerticalOffset = 10 }, static () => new XamlAnim.PopupThemeTransition { FromVerticalOffset = 20 }); + Theme("PopupHorizontal", static () => new XamlAnim.PopupThemeTransition { FromHorizontalOffset = 10 }, + static () => new XamlAnim.PopupThemeTransition { FromHorizontalOffset = 20 }); Theme("Reposition", static () => new XamlAnim.RepositionThemeTransition { IsStaggeringEnabled = true }, static () => new XamlAnim.RepositionThemeTransition { IsStaggeringEnabled = false }); Theme("EdgeUI", static () => new XamlAnim.EdgeUIThemeTransition { Edge = EdgeTransitionLocation.Left }, static () => new XamlAnim.EdgeUIThemeTransition { Edge = EdgeTransitionLocation.Right }); Theme("Pane", static () => new XamlAnim.PaneThemeTransition { Edge = EdgeTransitionLocation.Left }, static () => new XamlAnim.PaneThemeTransition { Edge = EdgeTransitionLocation.Right }); - var info = new XamlAnim.SlideNavigationTransitionInfo(); - Theme("Navigation", () => new XamlAnim.NavigationThemeTransition { DefaultNavigationTransitionInfo = info }, - static () => new XamlAnim.NavigationThemeTransition { DefaultNavigationTransitionInfo = new XamlAnim.SlideNavigationTransitionInfo() }); + static XamlAnim.NavigationThemeTransition Navigation(XamlAnim.NavigationTransitionInfo info) => new() { DefaultNavigationTransitionInfo = info }; + Theme("NavigationSlide", static () => Navigation(new XamlAnim.SlideNavigationTransitionInfo { Effect = XamlAnim.SlideNavigationTransitionEffect.FromRight }), + static () => Navigation(new XamlAnim.SlideNavigationTransitionInfo { Effect = XamlAnim.SlideNavigationTransitionEffect.FromLeft })); + Theme("NavigationCommon", static () => Navigation(new XamlAnim.CommonNavigationTransitionInfo { IsStaggeringEnabled = true }), + static () => Navigation(new XamlAnim.CommonNavigationTransitionInfo { IsStaggeringEnabled = false })); + Theme("NavigationDrillIn", static () => Navigation(new XamlAnim.DrillInNavigationTransitionInfo()), + static () => Navigation(new XamlAnim.EntranceNavigationTransitionInfo())); + H.Check("RebuiltExtras_NavigationContinuumByReference", !Same( + Button("Go").WithTransitions(Navigation(new XamlAnim.ContinuumNavigationTransitionInfo())), + Button("Go").WithTransitions(Navigation(new XamlAnim.ContinuumNavigationTransitionInfo())))); Theme("AddDelete", static () => new XamlAnim.AddDeleteThemeTransition(), static () => new XamlAnim.ReorderThemeTransition()); Theme("Reorder", static () => new XamlAnim.ReorderThemeTransition(), null); } diff --git a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/TransformModifierFixtures.cs b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/TransformModifierFixtures.cs index f0cca6d2d8..fc8eb07856 100644 --- a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/TransformModifierFixtures.cs +++ b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/TransformModifierFixtures.cs @@ -271,6 +271,29 @@ static KeyframeBuilder Pulse(KeyframeBuilder kf) => kf.Loop().Duration(60000) H.Check("TransformKeyframes_ScaleResetAfterLoopRemoval", loopingVisual.Scale == Vector3.One && loopingVisual.TryGetAnimationController("Scale") is null, $"scale={loopingVisual.Scale}"); + // Issue #1702: a render that rebuilds equal keyframes skips its update, so the channel's + // owner keeps the earlier render's array. Removing the loop must still reset the scale. + var firstScaled = animated.Keyframes("pulse", 1, Pulse).Scale(2); + var equalScaled = animated.Keyframes("pulse", 1, Pulse).Scale(2); + var equalLooping = animated.Keyframes("pulse", 1, Pulse); + loopingReconciler.Update(plainTarget, initialScale, loopingTarget, () => { }); + loopingReconciler.Update(initialScale, firstScaled, loopingTarget, () => { }); + await Harness.Render(); + var equalController = loopingVisual.TryGetAnimationController("Scale"); + H.Check("TransformKeyframes_EqualRenderLoopStarted", equalController is not null); + if (equalController is not null) + { + equalController.Pause(); + equalController.Progress = 0.5f; + } + int skippedBefore = loopingReconciler.DebugElementsSkipped; + loopingReconciler.Update(firstScaled, equalScaled, loopingTarget, () => { }); + H.Check("TransformKeyframes_EqualRenderSkipped", loopingReconciler.DebugElementsSkipped == skippedBefore + 1); + loopingReconciler.Update(equalScaled, equalLooping, loopingTarget, () => { }); + loopingReconciler.Update(equalLooping, plainTarget, loopingTarget, () => { }); + H.Check("TransformKeyframes_ScaleResetAfterEqualRender", loopingVisual.Scale == Vector3.One + && loopingVisual.TryGetAnimationController("Scale") is null, $"scale={loopingVisual.Scale}"); + loopingReconciler.Update(plainTarget, scaled, loopingTarget, () => { }); var restarted = loopingVisual.TryGetAnimationController("Scale"); if (restarted is not null) diff --git a/tests/Reactor.Tests/AnimationExtrasEqualityTests.cs b/tests/Reactor.Tests/AnimationExtrasEqualityTests.cs index f00dd54d02..d92d40d678 100644 --- a/tests/Reactor.Tests/AnimationExtrasEqualityTests.cs +++ b/tests/Reactor.Tests/AnimationExtrasEqualityTests.cs @@ -1,3 +1,4 @@ +using System.Numerics; using Microsoft.UI.Reactor.Animation; using Microsoft.UI.Reactor.Core; using Xunit; @@ -45,8 +46,8 @@ public void Configuration_Changes_DeclineSkip_While_Equal_Values_Skip(string pro [Fact] public void Rebuilt_Equal_Keyframes_And_ScrollLinked_Skip() { - static Element Render(int trigger, float opacity = 0.5f, float parallax = 0.5f) => Button("Go") - .Keyframes("pulse", trigger, k => k.Duration(400).At(0f, opacity: 1f).At(1f, opacity: opacity, easing: Easing.EaseOut)) + static Element Render(int trigger, float opacity = 0.5f, float parallax = 0.5f, int duration = 400, bool loop = false) => Button("Go") + .Keyframes("pulse", trigger, k => (loop ? k.Loop() : k).Duration(duration).At(0f, opacity: 1f).At(1f, opacity: opacity, easing: Easing.EaseOut)) .ScrollLinked(null!, s => s.Parallax(parallax).FadeOut(0, 100)); Assert.True(Element.ShallowEquals(Render(1), Render(1))); @@ -56,7 +57,8 @@ static Element Render(int trigger, float opacity = 0.5f, float parallax = 0.5f) Assert.Equal(Render(1).GetHashCode(), Render(1).GetHashCode()); foreach (var changed in new[] { Render(2), Render(1, opacity: 0.4f), Render(1, parallax: 0.6f), - Render(1) with { ScrollAnimation = null }, Render(1) with { KeyframeAnimations = null } }) + Render(1) with { ScrollAnimation = null }, Render(1) with { KeyframeAnimations = null }, + Render(1, duration: 500), Render(1, loop: true) }) { Assert.False(Element.ShallowEquals(Render(1), changed)); Assert.False(Element.CanSkipUpdate(changed, Render(1))); @@ -64,6 +66,25 @@ static Element Render(int trigger, float opacity = 0.5f, float parallax = 0.5f) } } + // Issue #1702: InteractionStateValues lists its fields by hand, so each one must decline the skip. + [Fact] + public void Each_Interaction_State_Value_Declines_The_Skip() + { + static Element Hover(InteractionStateValues values) => Button("Go") with { InteractionStates = new InteractionStatesConfig(PointerOver: values) }; + var first = new InteractionStateValues(Opacity: 0.5f, Scale: 1.1f, ScaleV: Vector3.One, Translation: Vector3.UnitX, Rotation: 5f); + + Assert.True(Element.CanSkipUpdate(Hover(first), Hover(first with { }))); + foreach (var changed in new[] + { + first with { Opacity = 0.6f }, first with { Scale = 1.2f }, first with { ScaleV = Vector3.UnitY }, + first with { Translation = Vector3.UnitY }, first with { Rotation = 6f }, + }) + { + Assert.False(Element.CanSkipUpdate(Hover(first), Hover(changed))); + Assert.NotEqual(first, changed); + } + } + [Fact] public void Clearing_One_Animation_Preserves_Other_Extras_And_The_Original_Record() { @@ -103,7 +124,7 @@ private static (object First, object Equal, object? Changed) Values(string prope // Native transition values are exercised in the WinUI selftest. Distinct // arrays with equal contents compare equal (issue #1702). return (new ThemeTransitions { Children = new XamlTransition[0] }, new ThemeTransitions { Children = new XamlTransition[0] }, - new ThemeTransitions { ItemContainer = new XamlTransition[0] }); + new ThemeTransitions { Children = new XamlTransition[0], ItemContainer = new XamlTransition[0] }); case nameof(Element.InteractionStates): return (new InteractionStatesConfig(PointerOver: new(Opacity: 0.5f)), new InteractionStatesConfig(PointerOver: new(Opacity: 0.5f)), diff --git a/tests/Reactor.Tests/Core/ReducedMotionSubscriptionTests.cs b/tests/Reactor.Tests/Core/ReducedMotionSubscriptionTests.cs index de5084837a..4e8cddd236 100644 --- a/tests/Reactor.Tests/Core/ReducedMotionSubscriptionTests.cs +++ b/tests/Reactor.Tests/Core/ReducedMotionSubscriptionTests.cs @@ -220,7 +220,8 @@ public void TheProbeGuardCheck_RejectsConditionsThatMerelyMentionTheProbe( /// on the UI thread every frame, so RequestRender is the whole propagation path. /// [Theory] - [InlineData("OnAnimationsEnabledChanged")] + // The animations handler forwards to ApplyAnimationsEnabled, which a selftest also drives. + [InlineData("ApplyAnimationsEnabled")] [InlineData("OnColorValuesChanged")] public void UiSettingsHandlers_LeaveTheChartingPushToTheRenderThread(string handler) { From 82b8624ef778e030f8204c42db4011425c49ed2c Mon Sep 17 00:00:00 2001 From: Alexandre Zollinger Chohfi Date: Wed, 25 Nov 2026 15:34:18 -0800 Subject: [PATCH 3/5] Address review round 1 Subscribe to the "Animation effects" notification once, process-wide, in TransitionEngine, and refresh every registered host through the theme resource listeners. Chart-free windows and embedded hosts now get the refresh too, and a palette notification arriving first can't suppress it. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 2 +- .../Core/Navigation/TransitionEngine.cs | 30 ++++++++++++++++++- src/Reactor/Hosting/ReactorHost.cs | 13 +------- .../SelfTest/Fixtures/AnimateModifierTests.cs | 10 +++---- .../Core/ReducedMotionSubscriptionTests.cs | 6 ++-- 5 files changed, 40 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 26b54ff444..5d92d5466f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -225,7 +225,7 @@ Conventions for contributors: The declarations now compare by value: keyframes, scroll expressions with the same `ScrollViewer`, transition durations and settings, and solid brushes by color and opacity. A changed or removed declaration still updates. Turning Windows' "Animation effects" setting on or off now refreshes - every element in a Reactor window, so implicit transitions on unchanged elements follow it too. + every element in every Reactor host, so implicit transitions on unchanged elements follow it too. - `.LayoutAnimation()` uses linear easing for position and optional size changes in non-spring mode (#1652). diff --git a/src/Reactor/Core/Navigation/TransitionEngine.cs b/src/Reactor/Core/Navigation/TransitionEngine.cs index a4a1509d95..6239edd551 100644 --- a/src/Reactor/Core/Navigation/TransitionEngine.cs +++ b/src/Reactor/Core/Navigation/TransitionEngine.cs @@ -251,7 +251,13 @@ internal static bool StillOwns(UIElement element, long generation) => { try { - return new global::Windows.UI.ViewManagement.UISettings(); + var settings = new global::Windows.UI.ViewManagement.UISettings(); + // Implicit transitions check the setting when they're applied, and an unchanged + // element skips its update, so a change refreshes every host (issue #1702). + // ColorValuesChanged doesn't fire for this setting. + if (Core.UiSettingsCapabilities.HasAnimationsEnabledChanged) + settings.AnimationsEnabledChanged += OnAnimationsEnabledChanged; + return settings; } catch (global::System.Runtime.InteropServices.COMException ex) { @@ -270,6 +276,28 @@ internal static bool StillOwns(UIElement element, long generation) => } } + private static void OnAnimationsEnabledChanged(global::Windows.UI.ViewManagement.UISettings sender, object args) + => RefreshHostsForAnimationsChange(); + + /// + /// Asks every live host for a pass that skips no element, so implicit transitions are + /// applied again under the current setting. Any thread. Internal so a selftest can drive + /// what the settings notification does. + /// + internal static void RefreshHostsForAnimationsChange() + { + try + { + Core.ThemeResourceListeners.NotifyAll(); + } + catch (Exception ex) when (ex is not OutOfMemoryException and not StackOverflowException) + { + // Raised on the WinRT notification thread, where nothing above would catch it. + Core.Diagnostics.DiagnosticLog.SwallowedError( + Core.Diagnostics.LogCategory.Navigation, "AnimationsEnabledChanged refresh", ex); + } + } + /// /// Whether the user has left animations on /// (Settings → Accessibility → Visual effects → Animation effects). diff --git a/src/Reactor/Hosting/ReactorHost.cs b/src/Reactor/Hosting/ReactorHost.cs index 3720beae00..87cbd35f82 100644 --- a/src/Reactor/Hosting/ReactorHost.cs +++ b/src/Reactor/Hosting/ReactorHost.cs @@ -1590,17 +1590,8 @@ private void OnColorValuesChanged( private void OnAnimationsEnabledChanged( global::Windows.UI.ViewManagement.UISettings sender, object args) - => ApplyAnimationsEnabled(sender.AnimationsEnabled); - - /// - /// Applies a change of the "Animation effects" setting. Implicit transitions check it when - /// they are applied, and an unchanged element skips its update, so this requests a - /// resource-refresh pass, which updates every element, rather than a plain render - /// (issue #1702). Internal so a selftest can drive it; any thread. - /// - internal void ApplyAnimationsEnabled(bool animationsEnabled) { - var value = !animationsEnabled; + var value = !sender.AnimationsEnabled; // A coincident palette change re-reads the same field through // OnColorValuesChanged, so bail out when nothing actually moved. if (value == _isReducedMotion) return; @@ -1609,8 +1600,6 @@ internal void ApplyAnimationsEnabled(bool animationsEnabled) // [ThreadStatic] and this runs on the WinRT notification thread, so a push here // would write a copy the render thread never reads. Render() pushes on the UI // thread every frame, so RequestRender is what actually propagates this. - if (_disposed) return; - _reconciler.RequestResourceRefresh(); RequestRender(); } diff --git a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs index fce8cc7477..b6c129456f 100644 --- a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs +++ b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs @@ -242,15 +242,15 @@ public override async Task RunAsync() } // Implicit transitions check the "Animation effects" setting when they're applied, and an - // equal render skips its update, so a change of the setting refreshes every element. + // equal render skips its update, so the settings notification refreshes every host. private async Task AnimationSettingChanges() { Microsoft.UI.Reactor.Navigation.TransitionEngine.OverrideAnimationsEnabled(true); var host = H.CreateHost(); + // Only this fixture's host sees the refresh, never hosts other fixtures left behind. + using var isolation = ThemeResourceListeners.IsolateForTest(host); host.Mount(_ => VStack(TextBlock("Motion").OpacityTransition(TimeSpan.FromMilliseconds(200)).AutomationId("motion-target"))); await Harness.Render(); - host.ApplyAnimationsEnabled(true); - await Harness.Render(); var target = H.FindControl(t => Microsoft.UI.Xaml.Automation.AutomationProperties.GetAutomationId(t) == "motion-target"); H.Check("RebuiltExtras_MotionMounted", target is not null); @@ -264,12 +264,12 @@ private async Task AnimationSettingChanges() await Harness.Render(); // Positive control: the equal render skips, so only the setting change can drop the key. H.Check("RebuiltExtras_MotionEqualRenderSkips", HasKey()); - host.ApplyAnimationsEnabled(false); + Microsoft.UI.Reactor.Navigation.TransitionEngine.RefreshHostsForAnimationsChange(); await Harness.Render(); H.Check("RebuiltExtras_MotionOffDropsKey", !HasKey()); Microsoft.UI.Reactor.Navigation.TransitionEngine.OverrideAnimationsEnabled(true); - host.ApplyAnimationsEnabled(true); + Microsoft.UI.Reactor.Navigation.TransitionEngine.RefreshHostsForAnimationsChange(); await Harness.Render(); H.Check("RebuiltExtras_MotionOnRestoresKey", HasKey()); } diff --git a/tests/Reactor.Tests/Core/ReducedMotionSubscriptionTests.cs b/tests/Reactor.Tests/Core/ReducedMotionSubscriptionTests.cs index 4e8cddd236..261c8a7bce 100644 --- a/tests/Reactor.Tests/Core/ReducedMotionSubscriptionTests.cs +++ b/tests/Reactor.Tests/Core/ReducedMotionSubscriptionTests.cs @@ -48,6 +48,7 @@ public sealed class ReducedMotionSubscriptionTests const string HookFile = "Core/RenderContext.cs"; const string HostFile = "Hosting/ReactorHost.cs"; + const string EngineFile = "Core/Navigation/TransitionEngine.cs"; static SyntaxNode Source(string file) { @@ -91,6 +92,7 @@ static string[] EventBindings(SyntaxNode scope, SyntaxKind op) => [Theory] [InlineData(HookFile, "UseReducedMotionState", "OnChanged")] [InlineData(HostFile, "InitChartingState", "OnAnimationsEnabledChanged")] + [InlineData(EngineFile, "CreateUiSettings", "OnAnimationsEnabledChanged")] public void ReducedMotionListeners_SubscribeToTheEventThatActuallyFires( string file, string name, string handler) { @@ -168,6 +170,7 @@ static bool GuardedByProbe(SyntaxNode binding) => [Theory] [InlineData(HookFile)] [InlineData(HostFile)] + [InlineData(EngineFile)] public void EveryAnimationsEventBinding_SitsUnderTheCapabilityProbe(string file) { var bindings = Source(file).DescendantNodes() @@ -220,8 +223,7 @@ public void TheProbeGuardCheck_RejectsConditionsThatMerelyMentionTheProbe( /// on the UI thread every frame, so RequestRender is the whole propagation path. /// [Theory] - // The animations handler forwards to ApplyAnimationsEnabled, which a selftest also drives. - [InlineData("ApplyAnimationsEnabled")] + [InlineData("OnAnimationsEnabledChanged")] [InlineData("OnColorValuesChanged")] public void UiSettingsHandlers_LeaveTheChartingPushToTheRenderThread(string handler) { From 2ffc65b2c8f8b87bc6712bf91e26f5635d8e0a4d Mon Sep 17 00:00:00 2001 From: Alexandre Zollinger Chohfi Date: Wed, 25 Nov 2026 17:07:07 -0800 Subject: [PATCH 4/5] Address review round 4 Before Windows 10 2004 "Animation effects" has no change notification, and equal elements now skip their updates, so each root pass polls the setting there and refreshes every host when it moved. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Core/Navigation/TransitionEngine.cs | 16 ++++++++++++++++ src/Reactor/Core/Reconciler.cs | 4 ++++ .../SelfTest/Fixtures/AnimateModifierTests.cs | 12 ++++++++++++ .../Core/ReducedMotionSubscriptionTests.cs | 18 ++++++++++++++++++ 4 files changed, 50 insertions(+) diff --git a/src/Reactor/Core/Navigation/TransitionEngine.cs b/src/Reactor/Core/Navigation/TransitionEngine.cs index 6239edd551..22be4475f8 100644 --- a/src/Reactor/Core/Navigation/TransitionEngine.cs +++ b/src/Reactor/Core/Navigation/TransitionEngine.cs @@ -279,6 +279,22 @@ internal static bool StillOwns(UIElement element, long generation) => private static void OnAnimationsEnabledChanged(global::Windows.UI.ViewManagement.UISettings sender, object args) => RefreshHostsForAnimationsChange(); + // The setting at the last poll: -1 before the first, then 0 or 1. + private static int _polledAnimationsEnabled = -1; + + /// + /// Where the change notification doesn't exist (before Windows 10 2004), each host's root + /// pass calls this, and a setting that moved since the last poll refreshes every host. The + /// first poll only records the value. UI thread. + /// + internal static void PollAnimationsEnabled() + { + int now = AnimationsEnabled ? 1 : 0; + int before = global::System.Threading.Interlocked.Exchange(ref _polledAnimationsEnabled, now); + if (before >= 0 && before != now) + RefreshHostsForAnimationsChange(); + } + /// /// Asks every live host for a pass that skips no element, so implicit transitions are /// applied again under the current setting. Any thread. Internal so a selftest can drive diff --git a/src/Reactor/Core/Reconciler.cs b/src/Reactor/Core/Reconciler.cs index 6285ff5d8e..495d98ffe0 100644 --- a/src/Reactor/Core/Reconciler.cs +++ b/src/Reactor/Core/Reconciler.cs @@ -451,6 +451,10 @@ private Element BuildInTreeFallback(Exception ex, bool inEffects, string? compon /// internal void BeginRootPass() { + // Before Windows 10 2004 (19041) "Animation effects" has no change notification, and an + // unchanged element skips its update, so each root pass polls the setting (issue #1702). + if (!UiSettingsCapabilities.HasAnimationsEnabledChanged) + global::Microsoft.UI.Reactor.Navigation.TransitionEngine.PollAnimationsEnabled(); var pending = Interlocked.Exchange(ref _resourceRefreshPending, 0) != 0; _resourceRefreshArmed |= pending || HostThemeChanged; } diff --git a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs index b6c129456f..8fdaa14295 100644 --- a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs +++ b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs @@ -272,6 +272,18 @@ private async Task AnimationSettingChanges() Microsoft.UI.Reactor.Navigation.TransitionEngine.RefreshHostsForAnimationsChange(); await Harness.Render(); H.Check("RebuiltExtras_MotionOnRestoresKey", HasKey()); + + // Before Windows 10 2004 there's no notification, so each root pass polls the setting + // instead. This machine has the notification, so the fixture drives the poll itself. + Microsoft.UI.Reactor.Navigation.TransitionEngine.PollAnimationsEnabled(); + Microsoft.UI.Reactor.Navigation.TransitionEngine.OverrideAnimationsEnabled(false); + Microsoft.UI.Reactor.Navigation.TransitionEngine.PollAnimationsEnabled(); + await Harness.Render(); + H.Check("RebuiltExtras_MotionPollOffDropsKey", !HasKey()); + Microsoft.UI.Reactor.Navigation.TransitionEngine.OverrideAnimationsEnabled(true); + Microsoft.UI.Reactor.Navigation.TransitionEngine.PollAnimationsEnabled(); + await Harness.Render(); + H.Check("RebuiltExtras_MotionPollOnRestoresKey", HasKey()); } private Element Wrap(Element element) => childSkip ? VStack(element) : element; diff --git a/tests/Reactor.Tests/Core/ReducedMotionSubscriptionTests.cs b/tests/Reactor.Tests/Core/ReducedMotionSubscriptionTests.cs index 261c8a7bce..376dda252b 100644 --- a/tests/Reactor.Tests/Core/ReducedMotionSubscriptionTests.cs +++ b/tests/Reactor.Tests/Core/ReducedMotionSubscriptionTests.cs @@ -200,6 +200,24 @@ static AssignmentExpressionSyntax ParseBinding(string statement) => .OfType() .Single(a => a.IsKind(SyntaxKind.AddAssignmentExpression)); + /// + /// Before 19041 the notification doesn't exist, and an unchanged element skips its update, + /// so the reconciler's root pass polls the setting instead (issue #1702). Structural for the + /// same reason as the rest of this class: this machine has the notification. + /// + [Fact] + public void RootPass_PollsTheSetting_WhenTheNotificationIsMissing() + { + var polls = Method("Core/Reconciler.cs", "BeginRootPass").DescendantNodes() + .OfType() + .Where(i => i.Expression.ToString().EndsWith("TransitionEngine.PollAnimationsEnabled", global::System.StringComparison.Ordinal)) + .ToArray(); + + var poll = Assert.Single(polls); + var guard = poll.Ancestors().OfType().First(); + Assert.Equal("!UiSettingsCapabilities.HasAnimationsEnabledChanged", guard.Condition.ToString()); + } + /// /// The polarity check above is the whole value of that test, so it needs a case it /// answers "no" to. A mention-only check (Condition.ToString().Contains(...)) From 460c392d9f407c70479080bd387b70e38b233a8c Mon Sep 17 00:00:00 2001 From: Alexandre Zollinger Chohfi Date: Wed, 25 Nov 2026 17:26:59 -0800 Subject: [PATCH 5/5] Address review round 5 Before Windows 10 2004 the root pass's own poll drops the key, so the fixture's equal-render positive control depends on that capability. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../SelfTest/Fixtures/AnimateModifierTests.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs index 8fdaa14295..75ac139843 100644 --- a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs +++ b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/AnimateModifierTests.cs @@ -262,8 +262,11 @@ private async Task AnimationSettingChanges() Microsoft.UI.Reactor.Navigation.TransitionEngine.OverrideAnimationsEnabled(false); host.RequestRender(); await Harness.Render(); - // Positive control: the equal render skips, so only the setting change can drop the key. - H.Check("RebuiltExtras_MotionEqualRenderSkips", HasKey()); + // Positive control: with the notification, the equal render skips, so only the setting + // change can drop the key. Without it (before Windows 10 2004), the root pass polls the + // setting and drops the key itself. + bool rootPassPolls = !UiSettingsCapabilities.HasAnimationsEnabledChanged; + H.Check("RebuiltExtras_MotionEqualRenderSkips", rootPassPolls ? !HasKey() : HasKey()); Microsoft.UI.Reactor.Navigation.TransitionEngine.RefreshHostsForAnimationsChange(); await Harness.Render(); H.Check("RebuiltExtras_MotionOffDropsKey", !HasKey()); @@ -274,7 +277,7 @@ private async Task AnimationSettingChanges() H.Check("RebuiltExtras_MotionOnRestoresKey", HasKey()); // Before Windows 10 2004 there's no notification, so each root pass polls the setting - // instead. This machine has the notification, so the fixture drives the poll itself. + // instead. Where the notification exists, root passes don't poll, so drive it here. Microsoft.UI.Reactor.Navigation.TransitionEngine.PollAnimationsEnabled(); Microsoft.UI.Reactor.Navigation.TransitionEngine.OverrideAnimationsEnabled(false); Microsoft.UI.Reactor.Navigation.TransitionEngine.PollAnimationsEnabled();