Repository navigation
[iOS] ScrollView: Complete element scroll requests inside collapsed branches #37409
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 12 commits
a8e8d6d
d79d09c
9f439ed
7306000
7f625b3
7e4f1bf
a3323ee
567c5a1
74e9c16
f02311a
6ec1c5a
c56e736
fa03bc0
386214e
efdf0d9
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -43,27 +43,65 @@ public Rect LayoutAreaOverride | |
| ScrollToRequestedEventArgs _pendingScrollToRequested; | ||
| bool _replayPendingScrollToRequestedEvent; | ||
|
|
||
| // A parked element request lives exactly as long as the task the caller is awaiting. | ||
| // It leaves the park in one of two ways, and no other: the arrange arrives and the | ||
| // request is replayed against real geometry (the task completes with the scroll), | ||
| // or the view's lifecycle ends — its handler goes away or it is removed from the | ||
| // tree — and the request is dropped (the task completes without a scroll). Nothing | ||
| // releases the task while the request is still parked, so a completed await never | ||
| // scrolls later; and nothing but a lifecycle end drops the request, so a view that is | ||
| // merely hidden (a collapsed branch, an unselected tab) still scrolls to the element | ||
| // when it is eventually arranged. A view that stays attached and is never arranged | ||
| // keeps the task pending — that is the contract, not a leak: the task completes when | ||
| // the scroll happens or the view is torn down. | ||
| private protected override void OnHandlerChangedCore() | ||
| { | ||
| base.OnHandlerChangedCore(); | ||
|
|
||
| if (Handler is null) | ||
| { | ||
| // The handler went away with a request still queued, so nothing will ever | ||
| // dispatch it. Release the caller rather than leaving its task pending | ||
| // forever; Core does the same for its own pending request on disconnect. | ||
| if (_pendingScrollToRequested is not null) | ||
| { | ||
| _pendingScrollToRequested = null; | ||
| SendScrollFinished(); | ||
| } | ||
|
|
||
| // dispatch it; Core does the same for its own pending request on disconnect | ||
| DropPendingScrollToRequest(); | ||
| return; | ||
| } | ||
|
|
||
| DispatchPendingScrollToRequest(); | ||
| } | ||
|
|
||
| private protected override void OnParentChangedCore() | ||
| { | ||
| base.OnParentChangedCore(); | ||
|
|
||
| // Removed from the tree: no arrange will come from a parent that no longer | ||
| // exists, and the handler is not necessarily disconnected by the removal, so | ||
| // this is the other lifecycle end that drops a parked request | ||
| if (RealParent is null) | ||
| { | ||
| DropPendingScrollToRequest(); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
[moderate] Async and Threading Safety — |
||
| } | ||
| } | ||
|
|
||
| void DropPendingScrollToRequest() | ||
| { | ||
| if (_pendingScrollToRequested is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| _pendingScrollToRequested = null; | ||
| // A stale replay flag from a pre-handler park must not carry over to a later request | ||
| _replayPendingScrollToRequestedEvent = false; | ||
|
|
||
| // This runs from inside a lifecycle mutation (a handler change, the view leaving | ||
| // the tree), and the caller's await continuation must not resume in the middle of | ||
| // it — it could re-enter a half-finished parenting or property change. Post the | ||
| // completion instead of raising it inline. Only this path defers: the platform | ||
| // scroll callbacks complete the task exactly as before, so ordinary | ||
| // `await ScrollToAsync(...)` continuations keep their existing timing. | ||
| Dispatcher.Dispatch(SendScrollFinished); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
[major] Logic and Correctness — The deferred completion is posted as a bare method group, so it completes whatever Concrete failing sequence, all inside one dispatcher turn:
Two consequences, both of which are exactly what this change set out to prevent:
Bind the completion to the source captured at drop time so a superseding request cannot be released by an older drop, e.g. capture
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Confirmed and fixed in fa03bc0 — reproduced your exact sequence on the previous head ( |
||
| } | ||
|
|
||
| void DispatchPendingScrollToRequest() | ||
| { | ||
| if (Handler is null || _pendingScrollToRequested is not { } pending) | ||
|
|
@@ -79,11 +117,11 @@ void DispatchPendingScrollToRequest() | |
| return; | ||
| } | ||
|
|
||
| // Those callbacks run while the pass that produced the sizes is still arranging | ||
| // children, so resolve on the next tick, once positions are final. Posting on | ||
| // every retry is deliberate: SendPendingScrollToRequest is a no-op once the | ||
| // request has been sent or superseded, so a dropped callback cannot wedge the | ||
| // request the way an "already queued" flag would. | ||
| // Those callbacks run while the pass that produced the sizes is still | ||
| // arranging children, so resolve on the next tick, once positions are final. | ||
| // Posting on every retry is deliberate: SendPendingScrollToRequest is a no-op | ||
| // once the request has been sent or superseded, so a dropped callback cannot | ||
| // wedge the request the way an "already queued" flag would. | ||
| Dispatcher.Dispatch(SendPendingScrollToRequest); | ||
| return; | ||
| } | ||
|
|
@@ -533,6 +571,8 @@ void OnScrollToRequested(ScrollToRequestedEventArgs e) | |
| // OnAppearing): resolving the element target now would compute against the -1 | ||
| // never-arranged sentinels. Park it for the layout callbacks instead — the | ||
| // subscribers were already notified above, so the replay must not re-raise. | ||
| // It stays parked until the arrange arrives or the view's lifecycle ends | ||
| // (see OnHandlerChangedCore); a hidden view scrolls once it is shown. | ||
| _pendingScrollToRequested = e; | ||
| _replayPendingScrollToRequestedEvent = false; | ||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| using System; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Maui.UnitTests; | ||
| using NSubstitute; | ||
| using Xunit; | ||
|
|
||
|
|
@@ -487,6 +488,109 @@ public void ElementRequestWithHandlerAttachedWaitsForArrange() | |
| Assert.True(task.IsCompleted); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void ElementRequestOnHiddenScrollViewWaitsAndScrollsOnceShown() | ||
| { | ||
| var item = new View(); | ||
| var layout = new StackLayout { Children = { item } }; | ||
| var scrollView = new ScrollView { Content = layout, IsVisible = false }; | ||
|
|
||
| var handler = new ViewportProviderHandlerStub(); | ||
| scrollView.Handler = handler; | ||
|
|
||
| // A hidden view is skipped by layout, so no arrange is coming yet. The request | ||
| // stays parked and the task stays pending: completing it here would either | ||
| // scroll to a target computed from unarranged geometry or leave a request alive | ||
| // after its await returned — the task means "the scroll happened or the view is | ||
| // gone", nothing in between. | ||
| var task = scrollView.ScrollToAsync(item, ScrollToPosition.Center, false); | ||
| Assert.False(task.IsCompleted); | ||
| Assert.Empty(handler.ScrollToRequests); | ||
|
|
||
| // Showing the view arranges it; the first arrange replays the request against | ||
| // real geometry so the scroll lands on the element: Center = 450 - 100/2 + 50/2 | ||
| scrollView.IsVisible = true; | ||
| item.Layout(new Graphics.Rect(0, 450, 100, 50)); | ||
| layout.Layout(new Graphics.Rect(0, 0, 100, 1000)); | ||
| scrollView.Layout(new Graphics.Rect(0, 0, 100, 100)); | ||
|
|
||
| var request = Assert.Single(handler.ScrollToRequests); | ||
| Assert.Equal(425, request.VerticalOffset); | ||
|
|
||
| scrollView.SendScrollFinished(); | ||
| Assert.True(task.IsCompleted); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task ElementRequestIsDroppedAndCompletedWhenTheViewLeavesTheTree() | ||
| { | ||
| var item = new View(); | ||
| var layout = new StackLayout { Children = { item } }; | ||
| var scrollView = new ScrollView { Content = layout }; | ||
| var parent = new StackLayout { Children = { scrollView } }; | ||
|
|
||
| var handler = new ViewportProviderHandlerStub(); | ||
| scrollView.Handler = handler; | ||
|
|
||
| // Parked with the handler attached, waiting for the arrange | ||
| var task = scrollView.ScrollToAsync(item, ScrollToPosition.End, false); | ||
| Assert.False(task.IsCompleted); | ||
|
|
||
| // Removing the view from the tree ends its lifecycle for layout purposes: no | ||
| // arrange will ever come from a parent it no longer has, and the removal does | ||
| // not disconnect its handler — so the request must be dropped and the caller | ||
| // released here rather than left pending forever | ||
| parent.Children.Remove(scrollView); | ||
|
|
||
| await task.WaitAsync(TimeSpan.FromSeconds(5)); | ||
| Assert.True(task.IsCompleted); | ||
| Assert.Empty(handler.ScrollToRequests); | ||
|
|
||
| // And dropped means dropped: re-attaching and arranging later must not resurrect | ||
| // the stale request into a scroll the caller no longer expects | ||
| parent.Children.Add(scrollView); | ||
| item.Layout(new Graphics.Rect(0, 450, 100, 50)); | ||
| layout.Layout(new Graphics.Rect(0, 0, 100, 1000)); | ||
| scrollView.Layout(new Graphics.Rect(0, 0, 100, 100)); | ||
| Assert.Empty(handler.ScrollToRequests); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void DroppedRequestCompletesThroughTheDispatcherNotInlineOnTheMutationStack() | ||
| { | ||
| // Capture dispatcher posts instead of running them, so the test can observe | ||
| // exactly when the completion is raised relative to the mutation. The option is | ||
| // thread-static and this capture swallows posts, so it must be restored. | ||
| var posted = new System.Collections.Generic.List<Action>(); | ||
| DispatcherProviderStubOptions.InvokeOnMainThread = posted.Add; | ||
| try | ||
| { | ||
| var item = new View(); | ||
| var scrollView = new ScrollView { Content = new StackLayout { Children = { item } } }; | ||
| var parent = new StackLayout { Children = { scrollView } }; | ||
| scrollView.Handler = new ViewportProviderHandlerStub(); | ||
|
|
||
| var task = scrollView.ScrollToAsync(item, ScrollToPosition.Start, false); | ||
| Assert.False(task.IsCompleted); | ||
|
|
||
| // The drop runs from inside a lifecycle mutation (child removal). Completing | ||
| // the task inline there would resume the caller's continuation in the middle | ||
| // of a half-finished parenting operation, so the completion must be posted: | ||
| // after Remove returns the task is still pending and exactly one post is queued | ||
| parent.Children.Remove(scrollView); | ||
| Assert.False(task.IsCompleted); | ||
| var completion = Assert.Single(posted); | ||
|
|
||
| // Running the post — what the real dispatcher does on its next turn — completes it | ||
| completion(); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
[moderate] Regression Prevention and Test Coverage — This test only exercises the benign ordering: drop → post → nothing else happens → run the post. Because That is the one interleaving where deferring the completion changes which task gets released (see the finding on Add a case that, between
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Adopted in fa03bc0 and taken further. The interleaving you asked for is pinned ( |
||
| Assert.True(task.IsCompleted); | ||
| } | ||
| finally | ||
| { | ||
| DispatcherProviderStubOptions.InvokeOnMainThread = null; | ||
| } | ||
| } | ||
|
|
||
| [Fact] | ||
| public void DeferredRequestReplaysEventForSubscribersAttachedWithTheHandler() | ||
| { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -415,7 +415,7 @@ bool ValidateSafeArea() | |
| // it can push ContentSize over the Bounds, causing AdjustedContentInset to become non-zero and SafeAreaInsets on the child to reset to zero. | ||
| // This can result in a loop of invalidations as the layout toggles between these states. | ||
| // To prevent this, we ignore safe area calculations on child views when they are inside a scroll view. | ||
| if (SystemAdjustedContentInset == UIEdgeInsets.Zero || ContentInsetAdjustmentBehavior == UIScrollViewContentInsetAdjustmentBehavior.Never) | ||
| if (!UIKitCompensatesForSafeArea) | ||
| _safeArea = GetInset(SafeAreaInsets).ToSafeAreaInsets(); | ||
| else | ||
| _safeArea = GetInset(SystemAdjustedContentInset).ToSafeAreaInsets(); | ||
|
|
@@ -510,25 +510,44 @@ internal CGSize ScrollableContentSize | |
| CGRect? _arrangedContentRect; | ||
|
|
||
| /// <summary> | ||
| /// The safe area <see cref="CrossPlatformArrange"/> baked into the content's coordinate | ||
| /// space: when it applies the safe area while UIKit is not compensating through | ||
| /// <see cref="UIScrollView.AdjustedContentInset"/>, the content is arranged inside | ||
| /// safe-area-inset bounds, so element positions carry the padding and the trailing | ||
| /// padding still obscures the viewport without ever appearing in the adjusted inset. | ||
| /// Whether UIKit is compensating for the safe area through | ||
| /// <see cref="UIScrollView.AdjustedContentInset"/>. When it is not | ||
| /// (<see cref="UIScrollViewContentInsetAdjustmentBehavior.Never"/>, or a zero system | ||
| /// inset), <see cref="CrossPlatformArrange"/> bakes the safe area into the content's | ||
| /// coordinate space instead. Shared by the arrange branch and the <c>_safeArea</c> | ||
| /// source selection in <see cref="ValidateSafeArea"/> so the two cannot desynchronize; | ||
| /// the arrange records the outcome in <see cref="SafeAreaBakedIntoContent"/> for | ||
| /// readers between arranges. | ||
| /// </summary> | ||
| bool UIKitCompensatesForSafeArea => | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
[minor] Complexity Reduction — the new property's summary states it is "shared by the arrange branch and
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Adopted in 9f439ed — the
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
[minor] Safe Area and Window Insets — The extracted predicate is behavior-preserving (
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Adopted in 7e4f1bf — you're right that sharing a live expression only removes textual divergence, and the |
||
| SystemAdjustedContentInset != UIEdgeInsets.Zero | ||
| && ContentInsetAdjustmentBehavior != UIScrollViewContentInsetAdjustmentBehavior.Never; | ||
|
|
||
| /// <summary> | ||
| /// The safe area the last <see cref="CrossPlatformArrange"/> baked into the content's | ||
| /// coordinate space: when it applies the safe area while UIKit is not compensating | ||
| /// through <see cref="UIScrollView.AdjustedContentInset"/>, the content is arranged | ||
| /// inside safe-area-inset bounds, so element positions carry the padding and the | ||
| /// trailing padding still obscures the viewport without ever appearing in the | ||
| /// adjusted inset. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Mirrors the arrange-side branch exactly: bounds are inset only while | ||
| /// <c>_appliesSafeAreaAdjustments</c>, and the inset origin is kept only when UIKit | ||
| /// contributes nothing (<see cref="UIScrollViewContentInsetAdjustmentBehavior.Never"/>, | ||
| /// or a zero system inset). In the remaining case (<see cref="UIScrollViewContentInsetAdjustmentBehavior.Always"/>) | ||
| /// the content is re-based at the origin and UIKit's inset owns the compensation, so the | ||
| /// arranged rect <see cref="ScrollableContentSize"/> measures naturally excludes it (issue #36801). | ||
| /// Captured at arrange time rather than derived live from UIKit state, because the | ||
| /// two can legitimately disagree between arranges: under | ||
| /// <see cref="UIScrollViewContentInsetAdjustmentBehavior.Automatic"/> the arrange | ||
| /// that bakes the padding can push the content size past the bounds, at which point | ||
| /// UIKit turns the adjusted inset non-zero — the content still carries the padding | ||
| /// until the next arrange re-bases it, and this must keep saying so. Recorded | ||
| /// alongside <see cref="_arrangedContentRect"/>, which does the same for the rect | ||
| /// (issue #36801). | ||
| /// </remarks> | ||
| internal SafeAreaPadding SafeAreaBakedIntoContent => | ||
| _appliesSafeAreaAdjustments && | ||
| (SystemAdjustedContentInset == UIEdgeInsets.Zero || ContentInsetAdjustmentBehavior == UIScrollViewContentInsetAdjustmentBehavior.Never) | ||
| ? _safeArea | ||
| : SafeAreaPadding.Empty; | ||
| internal SafeAreaPadding SafeAreaBakedIntoContent => _bakedSafeArea; | ||
|
|
||
| /// <summary> | ||
| /// The value <see cref="SafeAreaBakedIntoContent"/> reports, set by | ||
| /// <see cref="CrossPlatformArrange"/> from the branch it actually took. | ||
| /// </summary> | ||
| SafeAreaPadding _bakedSafeArea = SafeAreaPadding.Empty; | ||
|
|
||
| UIEdgeInsets SystemAdjustedContentInset | ||
| { | ||
|
|
@@ -564,12 +583,15 @@ Size CrossPlatformArrange(CGRect bounds) | |
| Size contentSize; | ||
|
|
||
| CGPoint contentOrigin; | ||
| SafeAreaPadding bakedSafeArea; | ||
| double width; | ||
| double height; | ||
| if (SystemAdjustedContentInset == UIEdgeInsets.Zero || ContentInsetAdjustmentBehavior == UIScrollViewContentInsetAdjustmentBehavior.Never) | ||
| if (!UIKitCompensatesForSafeArea) | ||
| { | ||
| contentSize = CrossPlatformLayout?.CrossPlatformArrange(bounds.ToRectangle()) ?? Size.Zero; | ||
| contentOrigin = bounds.Location; | ||
| // The inset bounds put the safe area into the content's coordinate space | ||
| bakedSafeArea = _appliesSafeAreaAdjustments ? _safeArea : SafeAreaPadding.Empty; | ||
|
|
||
| width = contentSize.Width; | ||
| height = contentSize.Height; | ||
|
|
@@ -578,14 +600,20 @@ Size CrossPlatformArrange(CGRect bounds) | |
| { | ||
| contentSize = CrossPlatformLayout?.CrossPlatformArrange(new Rect(new Point(), bounds.Size.ToSize())) ?? Size.Zero; | ||
| contentOrigin = CGPoint.Empty; | ||
| // Re-based at the origin: UIKit's adjusted inset owns the compensation | ||
| bakedSafeArea = SafeAreaPadding.Empty; | ||
|
|
||
| width = contentSize.Width; | ||
| height = contentSize.Height; | ||
| } | ||
|
|
||
| // Record where the content was actually arranged, before the ContentSize adjustments | ||
| // below: ScrollableContentSize measures the scrollable extent from this rect | ||
| // Record what this arrange actually did, before the ContentSize adjustments below: | ||
| // ScrollableContentSize measures the scrollable extent from the rect, and | ||
| // SafeAreaBakedIntoContent reports the padding the content now carries. Both are | ||
| // captured rather than re-derived later, since UIKit's inset state can move | ||
| // between arranges (see SafeAreaBakedIntoContent). | ||
| _arrangedContentRect = new CGRect(contentOrigin, contentSize.ToCGSize()); | ||
| _bakedSafeArea = bakedSafeArea; | ||
|
|
||
|
|
||
| // When using ContentInsetAdjustmentBehavior.Automatic, UIKit dynamically decides whether to apply | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[moderate] Logic and Correctness / Regression Prevention —
RealParent is nullfires on every transition to a null parent, including the transient null in a reparent, not just a permanent removal.Element.OnParentChangedCoreis raised from both theParentsetter (Element.cs:330) andSetParent(Element.cs:445), soparent1.Children.Remove(sv); parent2.Children.Add(sv);(or any layout that rebuilds its children, e.g. a template/item re-realization that moves the ScrollView) raises this hook withRealParent == nullin between.Concrete scenario:
var t = scrollView.ScrollToAsync(label, ScrollToPosition.Center, false);while the branch is not yet arranged, then the ScrollView is moved between containers. The parked request is dropped andSendScrollFinished()completestsuccessfully even though no scroll occurred; the arrange that arrives moments later from the new parent does not replay it — the added testElementRequestIsDroppedAndCompletedWhenTheViewLeavesTheTreeasserts exactly this non-resurrection. The caller'sawaitreturns as if the scroll had happened, and the element is never scrolled into view.This is a deliberate contract choice, but the comment justifies it with "no arrange will come from a parent that no longer exists", which does not hold for a reparent. Either defer the drop (e.g. re-check on the next tick / on the following parent change) so a re-attach within the same update keeps the request parked, or document that a reparent cancels a pending element scroll and add a unit test pinning the remove-then-re-add sequence.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Adopted the second option in 386214e: reparent cancels a pending element scroll, stated as the contract and pinned by
ReparentingCancelsAPendingElementScroll(remove → task completes at the removal → re-add → arrange replays nothing). You're right that my comment's justification ("no arrange will come from a parent that no longer exists") did not hold for a reparent — it's rewritten to say what actually happens and why. I deliberately did not take the deferred-drop option: putting a window between the drop and the completion to watch for a re-add is exactly the mechanism that produced the task-identity bug fixed in the previous commit (a newer request released in the old one's place), and a request made against a tree position that no longer exists is coherently "over" — a caller that moves a ScrollView with a pending scroll re-requests it in the new location.