Skip to content

feat(scrollviewer): Implement CurrentAnchor and scroll anchoring - #23053

Merged
MartinZikmund merged 7 commits into
masterfrom
dev/mazi/scroll-anchor
Apr 21, 2026
Merged

MartinZikmund merged 7 commits into
masterfrom
dev/mazi/scroll-anchor

Conversation

@MartinZikmund

@MartinZikmund MartinZikmund commented Apr 15, 2026 •

Copy link
Copy Markdown
Member

Summary

Implements ScrollViewer.CurrentAnchor, RegisterAnchorCandidate / UnregisterAnchorCandidate, the AnchorRequested event, and honors HorizontalAnchorRatio / VerticalAnchorRatio — previously stubbed with [NotImplemented]. With this change, a ScrollViewer that has an anchor ratio set will preserve the visual position of its chosen anchor element when content above it grows or shrinks (the classic "chat window" / "log view" use case).

Ported line-for-line from microsoft-ui-xaml2/src/dxaml/xcp/dxaml/lib/ScrollViewer_Partial.cpp using /winui-port:

  • CurrentAnchor getter (get_CurrentAnchorImpl)
  • RegisterAnchorCandidateImpl / UnregisterAnchorCandidateImpl (preserves WinUI's allow-duplicate release-build semantics)
  • RaiseAnchorRequested + AnchorRequestedEventArgs (with Anchor and mutable AnchorCandidates)
  • IsAnchoring, ComputeAnchorPoint / ComputeViewportAnchorPoint / ComputeElementAnchorPoint
  • ComputeViewportToElementAnchorPointsDistance
  • EnsureAnchorElementSelection, ProcessAnchorCandidate
  • GetDescendantBounds, IsElementValidAnchor
  • PerformPositionAdjustment
  • ArrangeOverride orchestration (pre-distance → baseArrange → post-distance → offset correction, plus far-edge anchoring against the cached extent/viewport)

To match WinUI's behavior on Uno, ScrollContentPresenter.MeasureOverride now calls ScrollViewer.OnScrollContentPresenterMeasured (mirror of ScrollViewer_Partial.cpp:9440), which invalidates arrange when anchoring is active. Without this hook, Uno's layout short-circuit would skip ArrangeCore when the SV's own finalRect is unchanged, and the anchoring flow would not fire on grandchild extent changes.

Scope

  • Works for the managed ScrollContentPresenter pipeline (Skia + WASM).
  • CurrentAnchor / Register / Unregister / AnchorRequested surface is available on all platforms.
  • Out of scope: CanContentRenderOutsideBounds (still stubbed — separate feature), zoom-factor coupling during anchoring (managed SV's ZoomFactor is always 1), integration with native scroll containers on Android/iOS.

Test plan

  • 17 runtime tests added (Given_ScrollViewer_Anchoring) covering:
    • CurrentAnchor null cases (no ratios, no candidates)
    • Closest-candidate selection (vertical and horizontal)
    • CurrentAnchor updates on scroll
    • Register / Unregister roundtrip and duplicate-allow semantics
    • AnchorRequested firing, handler anchor override, handler candidate-list mutation
    • Position preservation on content grow/shrink above anchor
    • Collapsed and non-descendant candidate rejection
    • Far-edge anchoring (VerticalAnchorRatio == 1.0) and near-edge no-op (== 0.0)
    • IScrollAnchorProvider cast
  • All 17 pass on native WinUI via /winui-runtime-tests (validates tests encode correct reference behavior).
  • All 17 pass on Uno Skia via /runtime-tests.
  • Full Given_ScrollViewer regression suite: no new failures (four pre-existing flaky tests unchanged, confirmed via git stash baseline).
  • Manual smoke in SamplesApp.Skia.Generic via the new ScrollViewer_Anchoring sample (insert above / remove above / ratio picker, live CurrentAnchor and offset readout).
  • Runtime tests on WASM (not executed locally — shares the managed SCP code path but worth running in CI).

Closes #4548
Closes #23043

🤖 Generated with Claude Code

Copilot AI review requested due to automatic review settings April 15, 2026 08:47
@github-actions github-actions Bot added the area/automation Categorizes an issue or PR as relevant to project automation label Apr 15, 2026
@MartinZikmund
MartinZikmund enabled auto-merge April 15, 2026 08:48

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Implements classic Microsoft.UI.Xaml.Controls.ScrollViewer scroll anchoring on Uno by porting WinUI’s anchor-selection and offset-correction logic, enabling IScrollAnchorProvider scenarios (e.g., chat/log views and ItemsRepeater viewport stabilization).

Changes:

  • Add CurrentAnchor, anchor candidate registration APIs, and AnchorRequested event, plus arrange-time anchoring/offset correction logic.
  • Integrate anchoring with layout by forcing an arrange pass when ScrollContentPresenter is re-measured while anchoring is active.
  • Add runtime tests (Given_ScrollViewer_Anchoring) and a SamplesApp UI test page demonstrating anchoring behavior.

Reviewed changes

Copilot reviewed 8 out of 11 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
src/Uno.UI/UI/Xaml/Controls/ScrollViewer/ScrollViewer.cs Routes ArrangeOverride through anchoring orchestration and removes old CurrentAnchor stub.
src/Uno.UI/UI/Xaml/Controls/ScrollViewer/ScrollViewer.Anchoring.cs New anchoring implementation: candidate management, anchor selection, pre/post-arrange distance diff, and offset correction.
src/Uno.UI/UI/Xaml/Controls/ScrollViewer/AnchorRequestedEventArgs.cs Adds managed AnchorRequestedEventArgs with mutable AnchorCandidates.
src/Uno.UI/UI/Xaml/Controls/ScrollContentPresenter/ScrollContentPresenter.cs Calls back into ScrollViewer after measure to invalidate arrange when anchoring is active.
src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Controls/ScrollViewer.cs Removes generated stubs for Register/Unregister and AnchorRequested event (now implemented in partial).
src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Controls/IScrollAnchorProvider.cs Removes platform-guarded NotImplemented gating so the interface is always available.
src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Controls/AnchorRequestedEventArgs.cs Removes generated stub type (now provided by real implementation).
src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml_Controls/ScrollViewerTests/Given_ScrollViewer_Anchoring.cs Adds runtime tests covering selection, events, duplicate semantics, and position preservation.
src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/ScrollViewerTests/ScrollViewer_Anchoring.xaml.cs Adds a sample page to manually exercise anchoring behavior.
src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/ScrollViewerTests/ScrollViewer_Anchoring.xaml XAML UI for the anchoring demo (ratio picker, insert/remove above/below, top/bottom buttons).
src/SamplesApp/UITests.Shared/UITests.Shared.projitems Includes the new sample XAML + code-behind in the shared project items.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 207374 has failed on Uno.UI - CI.

@unodevops

Copy link
Copy Markdown
Contributor

Copilot AI review requested due to automatic review settings April 16, 2026 10:36

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 8 out of 11 changed files in this pull request and generated 1 comment.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@unodevops

Copy link
Copy Markdown
Contributor

@MartinZikmund

Copy link
Copy Markdown
Member Author

@copilot resolve the merge conflicts in this pull request

auto-merge was automatically disabled April 16, 2026 13:03

Head branch was pushed to by a user without write access

@CLAassistant

CLAassistant commented Apr 16, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Copilot AI commented Apr 16, 2026

Copy link
Copy Markdown
Contributor

@copilot resolve the merge conflicts in this pull request

Resolved in 7fd9f08. The branch is now merged with master — the 2 conflicts in the generated files (IScrollAnchorProvider.cs, ScrollViewer.cs) were resolved by keeping our implemented versions.

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 207557 has failed on Uno.UI - CI.

MartinZikmund and others added 3 commits April 20, 2026 13:41
Cover CurrentAnchor selection across ratios, register/unregister (including
WinUI's allow-duplicate semantics), AnchorRequested event and handler overrides,
position preservation on content grow/shrink, far-edge anchoring, collapsed and
non-descendant candidate exclusion, and the IScrollAnchorProvider cast path.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Port the scroll-anchoring flow from microsoft-ui-xaml2 ScrollViewer_Partial.cpp:
CurrentAnchor getter, Register/Unregister/ClearAnchorCandidates, AnchorRequested
event with AnchorRequestedEventArgs, IsAnchoring, ComputeAnchorPoint /
ComputeViewportAnchorPoint / ComputeElementAnchorPoint,
ComputeViewportToElementAnchorPointsDistance, EnsureAnchorElementSelection,
ProcessAnchorCandidate, GetDescendantBounds, IsElementValidAnchor,
PerformPositionAdjustment, and the ArrangeOverride orchestration.

ScrollContentPresenter.MeasureOverride now calls back to
ScrollViewer.OnScrollContentPresenterMeasured (mirror of
ScrollViewer_Partial.cpp:9440) which invalidates arrange when anchoring is
active, so ArrangeOverride re-fires on grandchild extent changes.

Fixes #4548, fixes #23043.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Interactive sample that exercises VerticalAnchorRatio and CurrentAnchor:
insert/remove items above and below the viewport anchor, switch between
NaN / 0.0 / 0.5 / 1.0 ratios, and watch the live CurrentAnchor / offset
readout.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings April 20, 2026 11:41
@MartinZikmund
MartinZikmund force-pushed the dev/mazi/scroll-anchor branch from 9494f35 to 58f8032 Compare April 20, 2026 11:41

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 8 out of 10 changed files in this pull request and generated 4 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Copilot AI review requested due to automatic review settings April 20, 2026 12:50

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 9 out of 12 changed files in this pull request and generated 5 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@MartinZikmund

Copy link
Copy Markdown
Member Author

Code review

Found 4 issues (focus: logic accuracy vs WinUI C++ ScrollViewer_Partial.cpp).

  1. HorizontalAnchorRatio / VerticalAnchorRatio default to 0.0 instead of double.NaN — anchoring is silently enabled by default. The generated DP registration uses default(double) (= 0.0), but IsAnchoring treats NaN as the "disabled" sentinel (!double.IsNaN(...)). With the default 0.0, as soon as the user scrolls past c_edgeDetectionTolerance, element-anchoring activates unintentionally on every ScrollViewer. The non-generated ScrollViewer.Anchoring.cs partial does not override the metadata. WinUI's IsAnchoring (ScrollViewer_Partial.cpp:16206/16235) expects NaN by default.

#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public static global::Microsoft.UI.Xaml.DependencyProperty HorizontalAnchorRatioProperty { get; } =
Microsoft.UI.Xaml.DependencyProperty.Register(
nameof(HorizontalAnchorRatio), typeof(double),
typeof(global::Microsoft.UI.Xaml.Controls.ScrollViewer),
new Microsoft.UI.Xaml.FrameworkPropertyMetadata(default(double)));
#endif

#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public static global::Microsoft.UI.Xaml.DependencyProperty VerticalAnchorRatioProperty { get; } =
Microsoft.UI.Xaml.DependencyProperty.Register(
nameof(VerticalAnchorRatio), typeof(double),
typeof(global::Microsoft.UI.Xaml.Controls.ScrollViewer),
new Microsoft.UI.Xaml.FrameworkPropertyMetadata(default(double)));
#endif

  1. RaiseAnchorRequested returns early when AnchorRequested is null but never resets m_anchorRequestedEventArgs. Once a handler has run and populated the args, detaching the handler leaves the stale Anchor / AnchorCandidates in place; EnsureAnchorElementSelection then unconditionally reads them and lets the previous override hijack subsequent selections. WinUI gates this with an m_useCandidatesFromArgs flag explicitly set to false in the no-handler branch (ScrollViewer_Partial.cpp:16169/16173/16520).

private void RaiseAnchorRequested()
{
if (AnchorRequested is null)
{
return;
}
m_anchorRequestedEventArgs ??= new AnchorRequestedEventArgs();
m_anchorRequestedEventArgs.Reset(m_anchorCandidates);
AnchorRequested.Invoke(this, m_anchorRequestedEventArgs);
}
// Raises AnchorRequested and selects an anchor based on either the handler's Anchor
// override, or the closest candidate to the viewport anchor point.
private void EnsureAnchorElementSelection(Rect zoomedViewport)
{
if (!m_isAnchorElementDirty)
{
return;
}
m_anchorElement = null;
m_anchorElementBounds = default;
m_isAnchorElementDirty = false;
var content = Content as UIElement;
if (content is null)
{
return;
}
ComputeViewportAnchorPoint(zoomedViewport,
out var viewportAnchorPointHorizontalOffset,
out var viewportAnchorPointVerticalOffset);
RaiseAnchorRequested();
UIElement? requestedAnchor = m_anchorRequestedEventArgs?.Anchor;
IList<UIElement>? candidateOverride = m_anchorRequestedEventArgs?.AnchorCandidates;
if (requestedAnchor is not null && IsElementValidAnchor(requestedAnchor, content))
{
m_anchorElement = requestedAnchor;
m_anchorElementBounds = GetDescendantBounds(content, requestedAnchor);
return;
}

  1. IsAnchoring is missing the infinite-viewport guard that the WinUI C++ source has. ScrollViewer_Partial.cpp:16213 and 16242 skip each dimension's anchoring activation with if (zoomedViewportWidth/Height != std::numeric_limits<double>::infinity()). The Uno port falls through and can spuriously activate anchoring when the ScrollViewer is hosted in an unconstrained-size container.

// Computes whether element / far-edge anchoring is active per dimension.
private void IsAnchoring(
out bool isAnchoringElementHorizontally,
out bool isAnchoringElementVertically,
out bool isAnchoringFarEdgeHorizontally,
out bool isAnchoringFarEdgeVertically)
{
isAnchoringElementHorizontally = false;
isAnchoringElementVertically = false;
isAnchoringFarEdgeHorizontally = false;
isAnchoringFarEdgeVertically = false;
var horizontalAnchorRatio = HorizontalAnchorRatio;
var verticalAnchorRatio = VerticalAnchorRatio;
if (!double.IsNaN(horizontalAnchorRatio))
{
if (horizontalAnchorRatio == 0.0 || horizontalAnchorRatio == 1.0)
{
if (horizontalAnchorRatio == 1.0 &&
HorizontalOffset + ViewportWidth - ExtentWidth > -c_edgeDetectionTolerance)
{
isAnchoringFarEdgeHorizontally = true;
}
else if (!(horizontalAnchorRatio == 0.0 && HorizontalOffset < c_edgeDetectionTolerance))
{
isAnchoringElementHorizontally = true;
}
}
else
{
isAnchoringElementHorizontally = true;
}
}
if (!double.IsNaN(verticalAnchorRatio))
{
if (verticalAnchorRatio == 0.0 || verticalAnchorRatio == 1.0)
{
if (verticalAnchorRatio == 1.0 &&
VerticalOffset + ViewportHeight - ExtentHeight > -c_edgeDetectionTolerance)
{
isAnchoringFarEdgeVertically = true;
}
else if (!(verticalAnchorRatio == 0.0 && VerticalOffset < c_edgeDetectionTolerance))
{
isAnchoringElementVertically = true;
}
}
else
{
isAnchoringElementVertically = true;
}
}
}

  1. UpdateDimensionProperties() is now called twice per arrange when anchoring is active on Skia — once eagerly in AnchoringArrangeOverride (so PerformPositionAdjustment sees post-arrange state), then again in AfterArrange. The eager call is correct, but the duplicate work in the unchanged AfterArrange path is redundant; consider skipping the second call (or guarding it) when the anchoring path already updated dimensions in this layout cycle.

var arrangeResult = baseArrange(finalSize);
// WinUI updates its extent/viewport members during the arrange pass; Uno delays the DP
// update until AfterArrange, which means PerformPositionAdjustment's clamping sees stale
// values. Eagerly sync now so the anchor offset correction uses post-arrange state.
UpdateDimensionProperties();
m_pendingViewportShiftX = 0;
m_pendingViewportShiftY = 0;

// TODO: Revisit if this can use SizeChanged += (_, _) => OnControlsBoundsChanged(); on all platforms.
#if UNO_HAS_ENHANCED_LIFECYCLE
internal override void AfterArrange()
{
base.AfterArrange();
#else
internal override void OnLayoutUpdated()
{
base.OnLayoutUpdated();
#endif
UpdateDimensionProperties();
UpdateZoomedContentAlignment();
}

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, react with 👎.

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 208106 has failed on Uno.UI - CI.

@MartinZikmund

Copy link
Copy Markdown
Member Author

🤖 Addressed PR comments up to this point

Code changes:

  • HorizontalAnchorRatio/VerticalAnchorRatio DPs moved into ScrollViewer.Anchoring.cs with double.NaN default (matches WinUI).
  • Added m_useCandidatesFromArgs flag so stale AnchorRequested args don't leak after handlers detach (ScrollViewer_Partial.cpp:16169/16173/16520 parity).
  • IsAnchoring now skips each dimension when ViewportWidth/ViewportHeight is infinite (WinUI :16213/:16242 parity).
  • AfterArrange skips the redundant UpdateDimensionProperties() call when anchoring already synced dimensions in this layout pass.
  • IScrollAnchorProvider.CurrentAnchor is now UIElement? under #nullable enable (matches WinUI _Outptr_result_maybenull_).
  • Register/UnregisterAnchorCandidate remarks clarified: Uno requires explicit calls (auto-registration via CanBeScrollAnchor is tracked as follow-up).
  • Runtime-test helpers ScrollTo{Vertical,Horizontal}Async now Assert.Fail on timeout with offset details, and short-circuit when the current offset already matches the target (ChangeView no-op).
  • Sample handler leak fixed: ScrollViewer_Anchoring.xaml.cs subscribes to ViewChanged once in the constructor via a named method.

Already resolved before this pass (by commit 1584f0c37c): generated-file stubs for IScrollAnchorProvider, AnchorRequested, and Register/UnregisterAnchorCandidate.

All 17 Given_ScrollViewer_Anchoring runtime tests pass on Skia Desktop.

WinUI never calls ClearAnchorCandidates internally either; matching that keeps the Uno port faithful and resolves IDE0051.
@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 208186 has failed on Uno.UI - CI.

@MartinZikmund
MartinZikmund merged commit aeee700 into master Apr 21, 2026
43 checks passed
@MartinZikmund
MartinZikmund deleted the dev/mazi/scroll-anchor branch April 21, 2026 16:19
@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Apr 30, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area/automation Categorizes an issue or PR as relevant to project automation

Projects

None yet

6 participants