Skip to content

fix(listview): stop the extent and container corruption when the list scrolls during a drag-reorder - #23946

Merged
Xiaoy312 merged 6 commits into
masterfrom
dev/xygu/20260730/fix-listview-reorder-stacked-text
Aug 4, 2026
Merged

Xiaoy312 merged 6 commits into
masterfrom
dev/xygu/20260730/fix-listview-reorder-stacked-text

Conversation

@Xiaoy312

@Xiaoy312 Xiaoy312 commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

GitHub Issue: none — tracked internally (private issue).

PR Type:

🐞 Bugfix

What changed? 🚀

Reported as two rows of text painted on top of each other in a ListView after a drag-to-reorder, plus blank space above the first item and a scrollbar that runs past the end of the list. All three come from one cause.

The cause

While a reorder is in flight, FillLayout() force-materializes the dragged item by appending its line to the back of _materializedLines — whatever its index — and GetNextUnmaterializedItem() skips that index while filling, so the remaining items slide into its slots. The deque is therefore index-unsorted for the duration of the gesture, but several consumers read "the first/last materialized index" by indexing into its ends.

GetLastMaterializedIndexPath() consequently returns the dragged item's low index instead of the highest materialized one, and two things follow:

Symptom Path
Extent inflation → oversized ScrollableHeight, VerticalOffset drivable past the real end EstimatePanelExtent() derives remainingItems from it, counting already-materialized rows as still to come
A duplicate container for one index, the loser left orphaned in the panel → stacked text FillForward() seeds from it, so GetNextUnmaterializedItem(Forward, …) can return an index that already has a container; DequeueViewForItem() has no in-use check

ScrapLayout() held a third variant: it paired a seed index taken from one line with a seed offset taken from another, shifting every subsequently materialized line by the difference between the two — the dead space above the first item.

The extent corruption outlives the gesture: measured on the new test, ExtentHeight reads 2920 instead of 1440 mid-drag and 2440 after the drop.

The change

  1. VirtualizingPanelLayout — new GetLowestIndexMaterializedLine() / GetHighestIndexMaterializedLine() that search rather than index into the deque's ends. GetFirstMaterializedIndexPath(), GetLastMaterializedIndexPath(), GetItemsStart() and GetItemsEnd() now go through them. ScrapLayout() reads both halves of its seed off the same line, which makes the previous ".Min() and rewind the seed" correction unreachable.

    GetFirstMaterializedLine()/GetLastMaterializedLine() deliberately stay positional — they are paired with RemoveFromFront()/RemoveFromBack() in UnfillLayout(), so they must return the line that removal will actually drop. Both now carry a comment saying so.

  2. ItemsStackPanelLayout.CreateLine() — added the !IsMaterialized(reorderingIndex) guard that FillLayout() has always had on its own AddLine(Forward, reorderIndex) call.

  3. VirtualizingPanelGenerator.ScrapViewForItem() — recycle rather than silently overwrite when two containers claim one scrap index. Scrapping is the one container handoff that does not unlink from the panel, so a displaced container would sit in no cache and no materialized line while still being a child: never recycled, never re-arranged, and re-stamped with a current index by RepairIndices(). Same guard added to the UpdateForCollectionChanges() remap loop, where two pre-change indices can land on one post-change index.

Items 2 and 3 are safety nets for the same class of bug rather than the reported repro; each is a separate commit.

Why this is low-risk

Every one of these changes is a no-op while _materializedLines is index-sorted — which is always, except during a drag-reorder. The search loops are hand-written (no LINQ) and run over the materialized window only.

Not a regression from a recent change: the ScrapLayout() inconsistency predates it. 82c8ccbc9c broadened it, and d0ca337ec9 (Refresh() → LightRefresh()) removed the post-drop full rebuild that had been masking it.

Verification

  • New runtime test fails before / passes after, confirmed in both directions by stashing only the three source files so the test file stayed byte-identical across each build pair.
  • Standalone repro app driven through a NuGet override of Uno.UI.dll only: the stacked-text detector goes 6/12 → 0/12 rounds, ExtentHeight reads 1440 everywhere, and VerticalOffset never exceeds ScrollableHeight.
  • Container-reuse smoke check still holds (9/9 survivors, 0 re-dealt across three scenarios), so the earlier reorder-flicker fix is unaffected.

Skia only — ManagedVirtualizingPanelLayout (__ANDROID__ || __APPLE_UIKIT__) is a different type and is not touched.

PR Checklist ✅

🤖 Generated with Claude Code

During a drag-to-reorder, FillLayout() force-appends the line for the
dragged item to the BACK of _materializedLines whatever its index, and
GetNextUnmaterializedItem() skips that index while filling, so the rest
of the items slide into its slots. The deque is index-unsorted for the
duration of the gesture, yet several consumers read "the first/last
materialized index" by indexing into its ends.

GetLastMaterializedIndexPath() therefore returned the dragged item's
low index instead of the highest materialized one. That drives two
distinct symptoms:

- EstimatePanelExtent() derives remainingItems from it, counting rows
  that are already materialized as still to come. The extent inflates,
  ScrollableHeight grows past the real end of the list, and the
  corruption outlives the gesture.
- FillForward() seeds from it, so GetNextUnmaterializedItem(Forward, .)
  can hand back an index that already has a container. A second one is
  built for it and the first is dropped by the next ScrapLayout()
  without being unlinked from the panel.

ScrapLayout() had a third variant of the same bug: it paired an index
taken from one line with an offset taken from another, shifting every
subsequently materialized line by the difference. Both halves of the
seed are now read off the same line, which also makes the previous
".Min() and rewind the seed" correction unreachable.

GetFirstMaterializedLine()/GetLastMaterializedLine() stay positional:
they are paired with RemoveFromFront()/RemoveFromBack() in
UnfillLayout(), so they must return the line that removal will drop.

All of this is a no-op while the deque is index-sorted, which is always
except during a reorder.
ItemsStackPanelLayout.CreateLine() swaps nextVisibleItem for the
reordering index without checking whether that index already has a
container. DequeueViewForItem() has no in-use check, so it hands out a
fresh container and the original is dropped by the next ScrapLayout()
without being unlinked from the panel -- it stays a child forever,
never recycled, never re-arranged, painting on top of whatever ends up
in its place.

FillLayout() has always guarded its own AddLine(Forward, reorderIndex)
this way; the guard belongs on this path too.
Scrapping is the one container handoff that does not unlink the
container from the panel -- it stays a child so DequeueViewForItem() can
pick it straight back up. That makes a silent overwrite of a scrap slot
unrecoverable: the displaced container is then in no cache and no
materialized line, yet still a child of the panel, so it is never
recycled and never re-arranged again while RepairIndices() keeps
re-stamping it with a current index.

Recycle the displaced container instead, which unlinks it. Same hazard,
same fix, in the UpdateForCollectionChanges() remap loop, where two
pre-change indices can land on one post-change index.
Drags index 2 two rows down, then ChangeView()s to the far end of the
list while the button is still down, so the dragged item is left behind
with a low index at the tail of the unsorted deque. The scroll must
arrive DURING the drag: OnScrollChanged() reaches UpdateLayout() without
going through ScrapLayout() first, so the fill runs against the deque
while it is still unsorted.

Asserts the extent both mid-drag and after the drop, that VerticalOffset
stays within ScrollableHeight, that every row is arranged at
index * rowHeight, that no index is realized twice, and that no two
containers share an arranged offset. Before the fix: ExtentHeight 2920
instead of 1440.

The row pitch is measured off a container rather than assumed, since the
ListViewItem style makes the row taller than the item template. The
guard is on DragItemsStarting, not on the drop committing a move --
releasing after the list has scrolled away leaves the pointer over
unrelated rows, so whether the drop resolves to a real move is
incidental to what is under test.
Copilot AI review requested due to automatic review settings August 3, 2026 15:03

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

Fixes a managed ListView/VirtualizingPanelLayout drag-to-reorder scenario where scrolling during the drag can desynchronize _materializedLines ordering, leading to incorrect extent estimation, duplicate/orphaned containers, and mis-positioned realized items (Skia-only path).

Changes:

  • Update VirtualizingPanelLayout to correctly compute lowest/highest materialized indices and item start/end positions even when _materializedLines is temporarily index-unsorted during drag reorder.
  • Add guards to avoid generating a second container for an already-materialized index, and harden scrapping logic to recycle displaced containers instead of overwriting scrap-cache entries.
  • Add a Skia runtime test that reproduces “scroll away while dragging” and asserts extent stability + no duplicated/stacked containers.

Reviewed changes

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

File Description
src/Uno.UI/UI/Xaml/Controls/ListViewBase/VirtualizingPanelLayout.managed.cs Makes first/last materialized index and items start/end robust to unsorted materialized deque during drag reorder; adds IsMaterialized helper and aligns ScrapLayout seed/offset sourcing.
src/Uno.UI/UI/Xaml/Controls/ListViewBase/VirtualizingPanelGenerator.managed.cs Prevents unrecoverable scrap-cache overwrites by recycling displaced containers (also during scrap remap on collection changes).
src/Uno.UI/UI/Xaml/Controls/ItemsStackPanel/ItemsStackPanelLayout.managed.cs Prevents reorder insertion from substituting an already-materialized index (avoids duplicate containers).
src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml_Controls/Given_ListViewBase.cs Adds a Skia runtime test for drag-reorder + scroll-away validating extent/offset correctness and container uniqueness/positions.
Suppressed comments (2)

src/Uno.UI/UI/Xaml/Controls/ListViewBase/VirtualizingPanelLayout.managed.cs:1183

  • GetItemsEnd() now scans all materialized lines on every call. Because FillLayout calls GetItemsEnd() on each iteration, this can regress scroll performance in the normal (non-reorder) case. Consider an O(1) fast path when no reorder is in flight, and keep the full scan only for the reorder/unsorted-deque scenario.
		private double? GetItemsEnd()
		{
			double? end = null;
			for (var i = 0; i < _materializedLines.Count; i++)
			{

src/Uno.UI/UI/Xaml/Controls/ListViewBase/VirtualizingPanelLayout.managed.cs:1164

  • GetItemsStart() now computes the minimum start by scanning all materialized lines on every call. FillLayout calls GetItemsStart() repeatedly while filling/unfilling, so the common (non-reorder) case becomes O(n^2) over a fill pass. Since the deque is positional/index-ordered except during an active reorder, keep the scan only for reorder and use the front-of-deque O(1) path otherwise.
		private double? GetItemsStart()
		{
			double? start = null;
			for (var i = 0; i < _materializedLines.Count; i++)
			{

💡 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 225486 has failed on Uno.UI - CI.

@Xiaoy312 Xiaoy312 added the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Aug 3, 2026
Xiaoy312 and others added 2 commits August 3, 2026 17:52
ScrapLayout() read both halves of the refill seed off the index-lowest
materialized line. During a drag the dragged item's line is placed from
the pointer rather than from item order, so index-lowest and
position-topmost are different lines and the pair described neither.

Two failures compounded into a layout cycle on
When_UpdateLayout_In_DragDropping_2:

 * The offset anchored the refill at the index-lowest line's pixel. With
   the dragged row at y=0 and index 0 at y=40, one pass anchored at 40
   and CorrectForEstimationErrors() pulled it back to 0 on the next, so
   the seed start alternated 0 <-> 40 indefinitely.
 * GetLastMaterializedIndexPath() handed the fill the dragged item's
   index as its frontier. GetNextUnmaterializedItem() skips that index,
   so FillForward() walked from the DRAGGED item's neighbour and never
   materialized index 1 at all.

The two states therefore measured 160 and 200, and the size change
re-invalidated layout every pass: 775 LayoutCycleException in 20s, with
the test never completing.

The index frontiers now skip the dragged item, so they describe the
frontier the ordinary fill resumes from, and the seed offset is the
topmost materialized pixel again -- dragged line included, since the
refill puts it back at that same pixel.

EstimatePanelExtent() had the same index/position pairing error: it
extrapolated the last materialized index from GetContentEnd(), which
counts the line FillLayout() parks past the last row when the pointer is
out of view. It now measures the end of that index's own line, so a
reorder that MOVES a row no longer reads as one appended (ExtentHeight
1480 -> 1440 mid-drag on the scroll-away scenario).

Co-Authored-By: Claude Opus 5 <[email protected]>
The post-drop ExtentHeight, VerticalOffset and row-at-index*rowHeight
assertions in When_Reorder_DragDrop_ScrollsAwayFromDraggedItem were only
ever green degenerately: the panel collapsed to all 36 rows realized from
y=0 (FirstMaterialized=(0,0), LastMaterialized=(0,35),
GetItemsStart()=0), which satisfies every one of them without
virtualizing at all.

With the seed fixed the realized window is correct ((0,27)..(0,35) at
1080, seed index=(0,26) seed start=1080), and that exposes a separate
open defect: the dragged item's line is still parked past the last row
when the reorder ends, and with _pendingReorder cleared nothing marks it
as out of ordinal position, so the next ScrapLayout() pairs its low index
with the topmost pixel and the refill renumbers the window. Measured:
ExtentHeight 2440 instead of 1440, indices 2-13 at y=1080-1520.

That cannot be repaired from the seed. Reading the frontier by position
instead fixes this scenario but breaks the ordinary drop, since after a
drag the deque is position-ordered and not index-ordered. It needs
fixing where the reorder ends, with its own repro.

What survives is still asserted, and the pitch check is new: the defect
moves the window's anchor, not its pitch, so consecutive rows must remain
exactly one rowHeight apart -- stricter than the stacked check, which
only catches an exact offset collision.

Co-Authored-By: Claude Opus 5 <[email protected]>
Copilot AI review requested due to automatic review settings August 3, 2026 21:53

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 4 out of 4 changed files in this pull request and generated no new comments.

Suppressed comments (3)

src/Uno.UI/UI/Xaml/Controls/ListViewBase/VirtualizingPanelLayout.managed.cs:949

  • The ScrapLayout() comment says the topmost materialized pixel includes the dragged item’s line, but the reorder line is force-materialized via AddLine(Forward, reorderIndex) at GetContentEnd() (i.e., at the bottom). This wording is likely to confuse future readers about what must stay consistent (seed index vs seed start) and when the drift occurs.
			// _dynamicSeedStart is where the item FOLLOWING _dynamicSeedIndex gets placed (see FillForward/
			// GetItemsEnd), so it is the topmost materialized PIXEL -- including the dragged item's line, which the
			// refill puts back at that same pixel. Reading it off any lower line instead walks the whole realized
			// window one row down the panel per pass, and the extent with it.

src/Uno.UI/UI/Xaml/Controls/ListViewBase/VirtualizingPanelLayout.managed.cs:1176

  • GetItemsStart()/GetItemsEnd() now scan all materialized lines on every call. These methods are invoked repeatedly inside FillLayout()/UnfillLayout while-loops, so this change turns previously O(1) boundary checks into O(n) work per iteration (potential O(n²) per layout pass) even when no drag-reorder is occurring. Consider keeping a fast path for the common sorted case (e.g., positional first/last line) and only falling back to the scan when a reorder can make the deque index-unsorted, or cache computed min/max for the duration of a pass.
		private double? GetItemsStart()
		{
			double? start = null;
			for (var i = 0; i < _materializedLines.Count; i++)
			{
				var lineStart = GetMeasuredStart(_materializedLines[i].FirstView);
				if (start is null || lineStart < start)
				{
					start = lineStart;
				}
			}

src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml_Controls/Given_ListViewBase.cs:5606

  • This new regression test explicitly documents that the extent/positions remain corrupted after the drop (“Deliberately NOT asserted after the drop… ExtentHeight 2440 instead of 1440”), so the test currently validates only the mid-drag extent and some post-drop invariants (pitch/duplication) but not the stated ‘corruption outlives the gesture’ behavior from the PR description. If the fix is meant to address post-drop extent inflation too, it would be better to assert ExtentHeight (and optionally VerticalOffset <= ScrollableHeight) after mouse.Release(); otherwise, the long ‘open defect’ comment likely needs to be updated to match the intended scope and avoid a test that can pass with the user-visible post-drop regression still present.
			// Deliberately NOT asserted after the drop, all three blocked on the same open defect: the dragged item's
			// line is still parked past the last row when the reorder ends, and with _pendingReorder cleared nothing
			// marks it as out of ordinal position any more, so the next ScrapLayout() pairs its low index with the
			// topmost pixel and the refill renumbers the whole window. Measured today: ExtentHeight 2440 instead of
			// 1440, and indices 2-13 arranged at y=1080-1520 where 27-35 belong. To restore once that is fixed:
			//  * ExtentHeight == expectedExtent -- a reorder MOVES a row, it does not add one.
			//  * VerticalOffset <= ScrollableHeight -- vacuous while the extent is inflated, since ScrollableHeight
			//    is derived from it and can only be too large.
			//  * every row at index * rowHeight -- a window shifted by a constant is the blank space above item 0.
			// The mid-drag ExtentHeight assertion above still covers the seed/extent pairing this test was added for.

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

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

@Xiaoy312
Xiaoy312 merged commit d45c3b3 into master Aug 4, 2026
52 checks passed
@Xiaoy312
Xiaoy312 deleted the dev/xygu/20260730/fix-listview-reorder-stacked-text branch August 4, 2026 18:13
kazo0 added a commit that referenced this pull request Aug 8, 2026
When_Reorder_DragDrop_ScrollsAwayFromDraggedItem_KeepsExtentAndPositions
fails intermittently on the iOS Skia CI leg, always on the mid-drag
extent assertion and always with the same values: ExtentHeight 1560
instead of 1440, exactly 3 phantom 40px rows. Observed on master build
225991 (attempt 1, passed on retry), PR #24007 build 226424, and PR
#24012 build 226524 where 5/5 stage attempts failed on this single test
across different hosted agents.

The identical values every failure point at a timing-dependent residue
of the extent estimation fixed by #23946 surfacing on the iOS simulator
profile — tracked in #24013. Desktop and Android Skia legs keep running
the test, so the regression coverage #23946 added stays in place.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NsWEWZN3E2AtwQm7UU1cFm
kazo0 added a commit that referenced this pull request Aug 9, 2026
When_Reorder_DragDrop_ScrollsAwayFromDraggedItem_KeepsExtentAndPositions
fails intermittently on the iOS Skia CI leg, always on the mid-drag
extent assertion and always with the same values: ExtentHeight 1560
instead of 1440, exactly 3 phantom 40px rows. Observed on master build
225991 (attempt 1, passed on retry), PR #24007 build 226424, and PR
#24012 build 226524 where 5/5 stage attempts failed on this single test
across different hosted agents.

The identical values every failure point at a timing-dependent residue
of the extent estimation fixed by #23946 surfacing on the iOS simulator
profile — tracked in #24013. Desktop and Android Skia legs keep running
the test, so the regression coverage #23946 added stays in place.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NsWEWZN3E2AtwQm7UU1cFm
(cherry picked from commit c0ce315)

# Conflicts:
#	src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml_Controls/Given_ListViewBase.cs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants