Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
a8e8d6d
Never park an element request a collapsed branch cannot retry; share …
albyrock87 Aug 11, 2026
d79d09c
Restore Automatic expectations for SafeAreaEdges.Default after the la…
albyrock87 Aug 13, 2026
9f439ed
Convert the last raw occurrence of the shared safe-area predicate
albyrock87 Aug 14, 2026
7306000
Check every visual ancestor's visibility, skipping non-visual links i…
albyrock87 Aug 14, 2026
7f625b3
Release the caller but keep an element request parked while its branc…
albyrock87 Aug 14, 2026
7e4f1bf
Capture the baked safe area at arrange time instead of deriving it live
albyrock87 Aug 15, 2026
a3323ee
Release a parked element request when its view is collapsed or repare…
albyrock87 Aug 15, 2026
567c5a1
Merge branch 'inflight/current' into fix-36801-followup-collapsed-ele…
kubaflo Aug 15, 2026
74e9c16
Give a parked element request one contract: it lives exactly as long …
albyrock87 Aug 15, 2026
f02311a
Merge remote-tracking branch 'upstream/inflight/current' into fix-368…
albyrock87 Aug 15, 2026
6ec1c5a
Restore the PublicAPI files to the merge target
albyrock87 Aug 15, 2026
c56e736
Scope the deferred completion to the lifecycle-drop path
albyrock87 Aug 16, 2026
fa03bc0
Complete a dropped request inline, bound to the request being dropped
albyrock87 Aug 16, 2026
386214e
Gate an element request on the geometry its target actually needs; ca…
albyrock87 Aug 18, 2026
efdf0d9
Let a request made from inside the replayed ScrollToRequested event w…
albyrock87 Aug 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 53 additions & 13 deletions src/Controls/src/Core/ScrollView/ScrollView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 AI-Generated Review (multi-model)

[moderate] Logic and Correctness / Regression Prevention — RealParent is null fires on every transition to a null parent, including the transient null in a reparent, not just a permanent removal. Element.OnParentChangedCore is raised from both the Parent setter (Element.cs:330) and SetParent (Element.cs:445), so parent1.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 with RealParent == null in 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 and SendScrollFinished() completes t successfully even though no scroll occurred; the arrange that arrives moments later from the new parent does not replay it — the added test ElementRequestIsDroppedAndCompletedWhenTheViewLeavesTheTree asserts exactly this non-resurrection. The caller's await returns 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.

Copy link
Copy Markdown
Contributor Author

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.

{
DropPendingScrollToRequest();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 AI-Generated Review (multi-model)

[moderate] Async and Threading Safety — DropPendingScrollToRequest() ends in SendScrollFinished() → _scrollCompletionSource.TrySetResult(true), and _scrollCompletionSource is created as new TaskCompletionSource<bool>() without TaskCreationOptions.RunContinuationsAsynchronously (CheckTaskCompletionSource). The awaiting caller's continuation therefore runs synchronously on this thread, i.e. from inside Element.SetParent — before OnParentSet()'s sequence finishes with OnPropertyChanged(nameof(Parent)) (Element.cs:445-447). Concrete scenario: code after await scrollView.ScrollToAsync(element, ...) re-adds the ScrollView, assigns Content, or issues a new ScrollToAsync while the parent-change is still propagating, so the tree is mutated mid-detach and Parent bindings have not yet been notified. Creating the completion source with RunContinuationsAsynchronously (or posting the completion) keeps the lifecycle hook free of caller code.

}
}

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);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 AI-Generated Review (multi-model)

[major] Logic and Correctness — The deferred completion is posted as a bare method group, so it completes whatever _scrollCompletionSource exists when the dispatcher turn runs, not the one that was pending when the request was dropped. SendScrollFinished (line 238) calls _scrollCompletionSource?.TrySetResult(true), and CheckTaskCompletionSource (line 537) replaces _scrollCompletionSource with a fresh instance on every ScrollToAsync.

Concrete failing sequence, all inside one dispatcher turn:

  1. ScrollToAsync(element, ...) parks the request and returns task T1.
  2. The view's lifecycle ends (parent.Children.Remove(sv), or handler churn) → DropPendingScrollToRequest clears _pendingScrollToRequested and posts SendScrollFinished.
  3. Still before the post runs, the view is re-attached (otherParent.Children.Add(sv) / a new handler is assigned) and the caller issues a second ScrollToAsync → CheckTaskCompletionSource swaps in T2, and the new request parks.
  4. The posted SendScrollFinished runs and calls TrySetResult on T2.

Two consequences, both of which are exactly what this change set out to prevent:

  • T1 is never completed. The dropped caller’s task stays pending forever — the original leak survives the fix on this interleaving.
  • T2 completes while its request is still parked. The caller’s await returns with no scroll, and the parked request then replays on the next arrange and scrolls afterwards — directly contradicting the contract asserted in the class comment at lines 46–56 (“Nothing releases the task while the request is still parked, so a completed await never scrolls later”).

Bind the completion to the source captured at drop time so a superseding request cannot be released by an older drop, e.g. capture var completion = _scrollCompletionSource; before the post and dispatch () => completion?.TrySetResult(true);.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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 (t1.completed=false, t2.completed=true), so this was a real bug I introduced when scoping the deferral last round. Rather than bind a captured source to the post, I removed the deferral: the drop now completes inline at the moment the request is dropped, which binds the release to that request by construction — no window, no captured identity, no interleaving to reason about. That is also the convention already shipping in this exact code: the handler-detach drop merged in #37060 and Core's DisconnectHandler both complete the task inline from their lifecycle hooks, so the deferral was protecting a property nothing here had while adding a real state hazard. The completion source construction is back to its pre-PR form. Regression tests pin the interleaving on both lifecycle ends (DropCompletesTheDroppedTaskAndOnlyThatTask, HandlerDetachDropCompletesOnlyTheDroppedTaskAndDoesNotResurrect), plus consecutive and doubled ends.

}

void DispatchPendingScrollToRequest()
{
if (Handler is null || _pendingScrollToRequested is not { } pending)
Expand All @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down
104 changes: 104 additions & 0 deletions src/Controls/tests/Core.UnitTests/ScrollViewUnitTests.cs
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;

Expand Down Expand Up @@ -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();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 AI-Generated Review (multi-model)

[moderate] Regression Prevention and Test Coverage — This test only exercises the benign ordering: drop → post → nothing else happens → run the post. Because posted is captured and replayed manually, the test has full control of the window between the drop and the completion, yet never exercises the dangerous case in that window — a new ScrollToAsync arriving before completion() is invoked.

That is the one interleaving where deferring the completion changes which task gets released (see the finding on ScrollView.cs:102): CheckTaskCompletionSource swaps _scrollCompletionSource, so the post lands on the new caller’s task while the old one is orphaned. The current assertions (Assert.False(task.IsCompleted), Assert.Single(posted), Assert.True(task.IsCompleted)) all pass either way, so they cannot discriminate correct from incorrect behavior here.

Add a case that, between parent.Children.Remove(scrollView) and completion(), re-attaches the view and issues a second ScrollToAsync, then asserts that the first task completes and the second stays pending until its own scroll or lifecycle end.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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 (DropCompletesTheDroppedTaskAndOnlyThatTask: drop → re-attach → new ScrollToAsync → arrange ⇒ T1 completed at the drop, T2 untouched, then replayed to the correct target and completed only by its own scroll). Since the previous test could only pass either way, I also enumerated the deferral state machine (initial disposition × lifecycle events) instead of testing the one path a finding names — nine new tests, and the enumeration surfaced a real latent hole in the geometry gate: with Content = null while an element request was parked, Content is not ({Width:<0} or {Height:<0}) was trivially true for null, so the ScrollView's own layout dispatched a target computed against no content. The gate now requires arranged content and the request waits for content or a lifecycle end (ParkedElementRequestWithContentRemovedWaitsThenCompletesOnLifecycleEnd).

Assert.True(task.IsCompleted);
}
finally
{
DispatcherProviderStubOptions.InvokeOnMainThread = null;
}
}

[Fact]
public void DeferredRequestReplaysEventForSubscribersAttachedWithTheHandler()
{
Expand Down
5 changes: 1 addition & 4 deletions src/Controls/tests/TestCases.HostApp/Issues/Issue36801.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,10 +167,7 @@ string CheckResolvedMode(UIKit.UIScrollView nativeScrollView, string kind)
var expected =
edges.Equals(new SafeAreaEdges(SafeAreaRegions.Container)) ? UIKit.UIScrollViewContentInsetAdjustmentBehavior.Always :
edges.Equals(SafeAreaEdges.None) || edges.Equals(SafeAreaEdges.All) ? UIKit.UIScrollViewContentInsetAdjustmentBehavior.Never :
// Default on a vertical scroll view resolves to Never since the landscape-notch
// fix (#35533): MAUI owns all edges there, and Automatic remains in use only for
// horizontal scroll views
UIKit.UIScrollViewContentInsetAdjustmentBehavior.Never;
UIKit.UIScrollViewContentInsetAdjustmentBehavior.Automatic;

return nativeScrollView.ContentInsetAdjustmentBehavior == expected
? null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,14 @@ public void ScrollToElementEndLandsInsideVisibleViewport()
"Probe label should be fully visible after ScrollToAsync(element, End)");
}

// The reachable ContentInsetAdjustmentBehavior modes bake the safe area into the content
// The three ContentInsetAdjustmentBehavior modes bake the safe area into the content
// differently, so each is exercised. The page asserts the resolved native behavior, so a
// mode that silently drifted fails instead of quietly testing a different branch.
// Default on a vertical scroll view resolves to Never since the landscape-notch fix
// (#35533); Automatic remains in use only for horizontal scroll views.
// mode that silently drifted fails instead of quietly testing a different branch —
// exactly what happened when the landscape-notch fix (#35533, since reverted in #36580)
// briefly remapped Default to Never.
[Test]
[Category(UITestCategories.ScrollView)]
[TestCase("ModeDefaultButton", "Never")]
[TestCase("ModeDefaultButton", "Automatic")]
[TestCase("ModeNoneButton", "Never")]
// Also resolves to Never, but bakes the safe area into the arranged content, which None
// does not — so it is the case that actually exercises the measured extent's baked padding
Expand All @@ -97,13 +97,13 @@ public void ScrollToExtremesInEachInsetMode(string modeButton, string expectedMo
}

// Element targets resolve against the effective viewport, and each inset mode obscures it
// differently: Always through AdjustedContentInset, Default/SafeAreaEdges.All by baking
// differently: Automatic/Always through AdjustedContentInset, SafeAreaEdges.All by baking
// the safe area into the content where AdjustedContentInset never reports it. The page's
// oracle measures the probe's bottom edge against the unobscured viewport bottom in window
// coordinates, so the mode where MAUI itself obscures the viewport is proven too.
[Test]
[Category(UITestCategories.ScrollView)]
[TestCase("ModeDefaultButton", "Never")]
[TestCase("ModeDefaultButton", "Automatic")]
[TestCase("ModeNoneButton", "Never")]
// Also resolves to Never, but bakes the safe area into the content — the case where the
// viewport shrink comes from MAUI's own arrange instead of a UIKit inset
Expand Down
68 changes: 48 additions & 20 deletions src/Core/src/Platform/iOS/MauiScrollView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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 =>

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 AI-Generated Review (multi-model)

[minor] Complexity Reduction — the new property's summary states it is "shared by the arrange branch and SafeAreaBakedIntoContent so the two can never desynchronize", but a third occurrence of the identical predicate remains inline at line 395 (if (SystemAdjustedContentInset == UIEdgeInsets.Zero || ContentInsetAdjustmentBehavior == ...Never)), and that one selects the source of _safeArea — the very value SafeAreaBakedIntoContent returns. Leaving it duplicated means a future change to UIKitCompensatesForSafeArea silently diverges from the _safeArea computation it feeds, which is the desynchronization the refactor is meant to prevent. Converting line 395 to !UIKitCompensatesForSafeArea is behavior-preserving (the De Morgan negation matches exactly, as it does for the two sites already converted).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adopted in 9f439ed — the _safeArea source selection in ValidateSafeArea now uses !UIKitCompensatesForSafeArea too, and the property doc lists all three sites. You're right that leaving it inline kept alive exactly the desynchronization the refactor exists to prevent.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 AI-Generated Review (multi-model)

[minor] Safe Area and Window Insets — The extracted predicate is behavior-preserving (!(SystemAdjustedContentInset == Zero || Behavior == Never) is exactly the negation of both original inline conditions), but the doc claim that sharing it means the sites "can never desynchronize" and that SafeAreaBakedIntoContent "always describes what the last arrange actually did" is not what the change guarantees. Both CrossPlatformArrange and SafeAreaBakedIntoContent evaluate this property live against mutable UIKit state, and under Automatic UIKit turns AdjustedContentInset non-zero once ContentSize exceeds Bounds — i.e. as a result of the very arrange that just baked the inset. A later read of SafeAreaBakedIntoContent then returns Empty while the content coordinate space still carries the baked padding, which is the mismatch element-target resolution (#36801) depends on. Sharing a live expression removes textual divergence only; capturing the value the arrange actually used (as _arrangedContentRect already does for the rect) would deliver the stated invariant.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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 Automatic transition you describe (the arrange that bakes the padding pushes ContentSize past Bounds, UIKit flips the inset non-zero, a later live read says Empty while the content still carries the padding) is exactly the window that mattered. CrossPlatformArrange now records the baked padding from the branch it actually took, alongside _arrangedContentRect which already did the same for the rect, and SafeAreaBakedIntoContent returns that captured value — so the doc claim is now literally what the code does. UIKitCompensatesForSafeArea remains shared between the arrange branch and the _safeArea source selection, where the live evaluation is the correct semantics.

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
{
Expand Down Expand Up @@ -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;
Expand All @@ -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
Expand Down
Loading