Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
c278450
Fix the spacer callback and item-alignment call race on initial trans…
ilonatommy Jul 30, 2026
e60afe5
Align tolerance with the most commonly used in tests.
ilonatommy Jul 30, 2026
0af1bd2
JS hook that assures test fails on regression.
ilonatommy Jul 31, 2026
92a340e
Feedback: JS can inform C# about the reason why spacer is visible.
ilonatommy Aug 6, 2026
8b8fc77
Merge branch 'main' into fix-68099
ilonatommy Aug 6, 2026
ba746b7
Limit the docs for internal class.
ilonatommy Aug 6, 2026
211f8b4
Remove orphaned suppressSpacerCallbacks write left by #68064 merge
ilonatommy Aug 6, 2026
6750257
Feedback: Add info about the cause when callback doesn't fire.
ilonatommy Aug 6, 2026
dbf91e9
Initialindex and ScrollToItem should test in-memory items as well.
ilonatommy Aug 7, 2026
0f9bb04
Update src/Components/Web.JS/src/Virtualize.ts
ilonatommy Aug 7, 2026
c688c09
Fix in memory tests: move the data window after refreshing data.
ilonatommy Aug 7, 2026
aa751ae
Test further actions after the initial load.
ilonatommy Aug 7, 2026
0332c35
Tighten test for https://github.com/dotnet/aspnetcore/issues/64029.
ilonatommy Aug 10, 2026
f898550
Fix both spacers visible case tested by `InitialRender_DispatchesSing…
ilonatommy Aug 10, 2026
11d988d
Fix jumps. Leave the viewport fill for the follow up PR.
ilonatommy Aug 10, 2026
22c3059
Clean tests: id=1 and id=5 are the same case. Move jumping and expans…
ilonatommy Aug 10, 2026
c239d69
Fix InitialItemIndex jump landing at wrong item on first scroll.
ilonatommy Aug 10, 2026
b172f57
Fix Virtualize programmatic scroll-to-bottom convergence and make sur…
ilonatommy Aug 10, 2026
5480a17
Tighten the test.
ilonatommy Aug 10, 2026
0dc8dc8
Fix `ScrollToItems` after `IntiailItemIndex!=0`: Pending state for In…
ilonatommy Aug 11, 2026
847a030
`ScrollToItemAsync` respects cancellation token.
ilonatommy Aug 11, 2026
6039b1e
Tests use real scrolling, not JS symulation of scrolling.
ilonatommy Aug 13, 2026
1f618c8
`scroll` even is triggered by both user scoll and self scroll. Listen…
ilonatommy Aug 13, 2026
6c67d88
Feedback: Avoid repeated programmatic scroll events being treated as …
ilonatommy Aug 13, 2026
01cac72
More tests need real wheel srolling.
ilonatommy Aug 13, 2026
89f4c00
More tests need correcting the scroll action.
ilonatommy Aug 13, 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
184 changes: 108 additions & 76 deletions src/Components/Web.JS/src/Virtualize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,19 @@ export const Virtualize = {

const dispatcherObserversByDotNetIdPropname = Symbol();
const THROTTLE_MS = 50;
const SpacerVisibilityReason = {
UserScroll: 0,
ProgrammaticScroll: 1,
ViewportFill: 2,
} as const;

const ScrollSource = {
None: 0,
UserScroll: 1,
AlignToItem: 2,
RestoreSnapshot: 3,
} as const;
type ScrollSource = typeof ScrollSource[keyof typeof ScrollSource];

function findClosestScrollContainer(element: HTMLElement | null): HTMLElement | null {
// If we recurse up as far as body or the document root, return null so that the
Expand Down Expand Up @@ -176,9 +189,27 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac
const anchoredItems: Map<Element, number> = new Map();
let scrollTriggeredRender = false;

// After anchor restore, suppress spacer IO callbacks until the next user scroll.
let suppressSpacerCallbacks = false;
let ignoreAnchorScroll = false;
const scrollActivity = {
source: ScrollSource.None as ScrollSource,
_ignoreNextScroll: false,
ignoreNextScroll(): void {
this._ignoreNextScroll = true;
},
consumeIgnoreScroll(): boolean {
if (!this._ignoreNextScroll) {
return false;
}
this._ignoreNextScroll = false;
return true;
},
consumeScroll(): void {
this.source = ScrollSource.None;
},
clear(): void {
this.consumeScroll();
reobserveSpacers();
},
};
const isViewportAtBottom = (): boolean =>
scrollElement.scrollHeight <= scrollElement.clientHeight
|| Math.abs(scrollElement.scrollTop + scrollElement.clientHeight - scrollElement.scrollHeight) < 2;
Expand Down Expand Up @@ -213,11 +244,9 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac
intersectionObserver.observe(spacerAfter);
}

// Called by C# at the start of a programmatic ScrollToIndex. Suppresses spacer-IO
// callbacks (which would otherwise be misinterpreted as a "user scroll") until
// either alignToItemAt completes or a real user scroll fires.
function beginProgrammaticScrollSuppression(): void {
suppressSpacerCallbacks = true;
// Called by C# at the start of a programmatic ScrollToItem, before the align scroll itself.
function beginProgrammaticScroll(): void {
scrollActivity.source = ScrollSource.AlignToItem;
pendingCallbacks.delete(spacerBefore);
pendingCallbacks.delete(spacerAfter);
}
Expand Down Expand Up @@ -356,12 +385,11 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac
// End mode: pin new items into view if we're at the bottom now, or were and are still following.
if ((anchorModeIs.end || bottomTracking.following) && (bottomTracking.wasAtBottomLastRender || bottomTracking.reached)) {
scrollElement.scrollTop = scrollElement.scrollHeight;
ignoreAnchorScroll = true;
scrollActivity.ignoreNextScroll();
// Start convergence only when there are more items to load (spacerAfter > 0).
// When all items fit in DOM, the single scrollTop assignment above is sufficient.
if (!convergence.bottom && !convergence.top && spacerAfter.offsetHeight > 0) {
suppressSpacerCallbacks = false;
reobserveSpacers();
scrollActivity.clear();
startConvergenceObserving('bottom');
}
}
Expand All @@ -378,7 +406,7 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac
const delta = (el.getBoundingClientRect().top - containerTop) - scrollCorrectionOffset;
if (Math.abs(delta) > 1) {
scrollElement.scrollTop += delta;
ignoreAnchorScroll = true;
scrollActivity.ignoreNextScroll();
}
}
}
Expand Down Expand Up @@ -426,9 +454,9 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac
}
const delta = newOffset - snapshot.anchorOffset;

// Suppress spacer IO until next user scroll. Save anchor for drift correction.
suppressSpacerCallbacks = true;
ignoreAnchorScroll = true;
// Save anchor for drift correction.
scrollActivity.source = ScrollSource.RestoreSnapshot;
scrollActivity.ignoreNextScroll();
if (Math.abs(delta) > 1) {
scrollCorrectionItemIndex = snapshot.anchorItemIndex;
pendingScrollCorrection = true;
Expand Down Expand Up @@ -487,8 +515,7 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac
function handleJumpKeys(e: Event): void {
const ke = e as KeyboardEvent;
if (ke.key === 'End') {
suppressSpacerCallbacks = false;
reobserveSpacers();
scrollActivity.clear();
Comment thread
ilonatommy marked this conversation as resolved.
Outdated
pendingJumpToEnd = true;
pendingJumpToStart = false;
if (!anchorModeIs.end) {
Expand All @@ -499,8 +526,7 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac
startConvergenceObserving('bottom');
}
} else if (ke.key === 'Home') {
suppressSpacerCallbacks = false;
reobserveSpacers();
scrollActivity.clear();
pendingJumpToStart = true;
pendingJumpToEnd = false;
clearBottomFollow();
Expand All @@ -512,23 +538,21 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac
keydownTarget.addEventListener('keydown', handleJumpKeys);

const scrollEventTarget: EventTarget = scrollContainer ?? window;
function handleScroll(): void {
if (convergence.isConverging()) {
function handleUserScroll(): void {
if (convergence.isConverging() || scrollActivity.consumeIgnoreScroll()) {
return;
}

if (ignoreAnchorScroll) {
ignoreAnchorScroll = false;
return;
}

// Clear suppression and re-observe on user scroll.
if (suppressSpacerCallbacks) {
suppressSpacerCallbacks = false;
const selfScrollInProgress = scrollActivity.source === ScrollSource.AlignToItem
|| scrollActivity.source === ScrollSource.RestoreSnapshot;
if (selfScrollInProgress) {
// IntersectionObserver only fires on change, so spacers suppressed during a self-scroll would stay silent
// once the user takes over. Re-observe to force them to re-fire and be processed under the user scroll.
reobserveSpacers();
}
scrollActivity.source = ScrollSource.UserScroll;
Comment thread
ilonatommy marked this conversation as resolved.

// A user scroll is the only thing that (re)sets follow state (programmatic scrolls early-return above).
// A user scroll is the only thing that (re)sets follow state (self-scrolls early-return above).
if (anchorModeIs.end || bottomTracking.following) {
const atBottom = isViewportAtBottom();
bottomTracking.following = atBottom;
Expand All @@ -537,7 +561,7 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac

updateAnchorSnapshot();
}
scrollEventTarget.addEventListener('scroll', handleScroll, { passive: true });
scrollEventTarget.addEventListener('scroll', handleUserScroll, { passive: true });

const { observersByDotNetObjectId, id } = getObserversMapEntry(dotNetHelper);
let pendingCallbacks: Map<Element, IntersectionObserverEntry> = new Map();
Expand All @@ -564,25 +588,25 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac

// Measures the target's viewport-relative top and aligns it to containerTop.
function alignToItemAt(localIndex: number): void {
function beginAlign(): void {
scrollActivity.ignoreNextScroll();
scrollActivity.source = ScrollSource.AlignToItem;
observersByDotNetObjectId[id].anchorSnapshot = null;
stopConvergenceObserving();
}

// Target row should be measured against the committed window, not a stale spacer height.
flushPendingStyleMutations();
const delta = measureLocalChildOffset(localIndex);
if (Number.isNaN(delta)) {
// Items aren't in DOM yet. Retry after the next render commit.
// Target item isn't in DOM yet. Retry after the next render.
pendingAlignLocalIndex = localIndex;
ignoreAnchorScroll = true;
suppressSpacerCallbacks = true;
observersByDotNetObjectId[id].anchorSnapshot = null;
stopConvergenceObserving();
beginAlign();
return;
}
pendingAlignLocalIndex = null;
if (Math.abs(delta) > 0.5) {
ignoreAnchorScroll = true;
suppressSpacerCallbacks = true;
// Programmatic scroll establishes a new explicit position — invalidate any pending anchor snapshot and cancel in-progress convergence.
observersByDotNetObjectId[id].anchorSnapshot = null;
stopConvergenceObserving();
beginAlign();
pendingJumpToStart = false;
pendingJumpToEnd = false;
scrollElement.scrollTo({ top: scrollElement.scrollTop + delta, behavior: 'instant' });
Expand All @@ -599,15 +623,15 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac
setAnchorMode: (mode: number) => { anchorMode = mode; bottomTracking.following = (mode & 2) !== 0; bottomTracking.reached = isViewportAtBottom(); },
restoreAnchor: restoreAnchorForShift,
alignToItem: alignToItemAt,
beginProgrammaticScroll: beginProgrammaticScrollSuppression,
beginProgrammaticScroll: beginProgrammaticScroll,
anchorSnapshot: null as { anchorItemIndex: number; anchorOffset: number; scrollTop: number } | null,
onDispose: () => {
mutationObserver.disconnect();
stopConvergenceObserving();
anchoredItems.clear();
resizeObserver.disconnect();
keydownTarget.removeEventListener('keydown', handleJumpKeys);
scrollEventTarget.removeEventListener('scroll', handleScroll);
scrollEventTarget.removeEventListener('scroll', handleUserScroll);
if (callbackTimeout) {
clearTimeout(callbackTimeout);
callbackTimeout = null;
Expand Down Expand Up @@ -636,7 +660,7 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac
}
}

function onSpacerAfterVisible(): void {
function updateBottomConvergence(): void {
if (spacerAfter.offsetHeight === 0) {
if (convergence.bottom) {
stopConvergenceObserving();
Expand All @@ -662,7 +686,7 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac
startConvergenceObserving('bottom');
}

function onSpacerBeforeVisible(): void {
Comment thread
ilonatommy marked this conversation as resolved.
function updateTopConvergence(): void {
if (spacerBefore.offsetHeight === 0) {
if (convergence.top) {
stopConvergenceObserving();
Expand Down Expand Up @@ -709,9 +733,6 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac
const modePinsTopItem = !anchorModeIs.beginning || !convergence.top;
const itemAlreadyShifted = rect.top - containerTop > rect.height;
if (nativeAnchoringUnavailable && modePinsTopItem && existing && itemAlreadyShifted) {
if (existing.scrollTop < 1 && anchorModeIs.end) {
suppressSpacerCallbacks = true;
}
return;
}
observersByDotNetObjectId[id].anchorSnapshot = {
Expand All @@ -732,25 +753,28 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac
return;
}

// Keep the anchor snapshot fresh on every IO callback so it reflects
// the current scroll position, not just the last render. Skip when
// suppression is active — those callbacks have pre-restore stale data.
if (!suppressSpacerCallbacks) {
const source = scrollActivity.source;
if (source === ScrollSource.UserScroll) {
// An ongoing scroll re-arms UserScroll every tick (handleUserScroll). Consuming prevents stale activity status.
scrollActivity.consumeScroll();
}

// Keep the anchor snapshot fresh on every IO callback so it reflects the current scroll position,
// not just the last render. Skip while a self-scroll is settling — those callbacks have stale data.
const isSelfScroll = source === ScrollSource.AlignToItem || source === ScrollSource.RestoreSnapshot;
if (!isSelfScroll) {
Comment thread
ilonatommy marked this conversation as resolved.
updateAnchorSnapshot();
}

const intersectingEntries = entries.filter(entry => {
// After an anchor restore, skip ALL spacer callbacks until the user
// scrolls. Re-observation is handled in handleScroll.
if (suppressSpacerCallbacks && (entry.target === spacerBefore || entry.target === spacerAfter)) {
return false;
}

if (entry.isIntersecting) {
if (entry.target === spacerAfter) {
onSpacerAfterVisible();
} else if (entry.target === spacerBefore) {
onSpacerBeforeVisible();
if (!isSelfScroll) {
// Convergence to the top/bottom edge should not fight with self scroll.
if (entry.target === spacerAfter) {
updateBottomConvergence();
} else if (entry.target === spacerBefore) {
updateTopConvergence();
}
}
return true;
}
Expand All @@ -774,24 +798,34 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac

intersectingEntries.forEach((entry): void => {
const containerSize = (entry.rootBounds?.height ?? 0) / scaleFactor;
const reason = source === ScrollSource.UserScroll
? SpacerVisibilityReason.UserScroll
: (isSelfScroll && (entry.target === spacerBefore || source === ScrollSource.RestoreSnapshot))
? SpacerVisibilityReason.ProgrammaticScroll
: SpacerVisibilityReason.ViewportFill;

const isBefore = entry.target === spacerBefore;
const spacer = isBefore ? spacerBefore : spacerAfter;

// At startup both spacers are visible, but we choose only one to report events to avoid duplicated callbacks.
if (!isBefore && spacer.offsetHeight === 0) {
return;
}

if (entry.target === spacerBefore) {
// ProgrammaticScroll callbacks are ignored by C#, so no item redistribution and no re-render happens.
if (reason !== SpacerVisibilityReason.ProgrammaticScroll) {
// So that RefreshObservedElements can skip item observation (avoids layout interference drift).
scrollTriggeredRender = true;
if (spacerBefore.offsetHeight > 0) {
if (spacer.offsetHeight > 0) {
nativeAnchoring.suspend('slide');
}
const spacerSize = (entry.intersectionRect.top - entry.boundingClientRect.top) / scaleFactor;
dotNetHelper.invokeMethodAsync('OnSpacerBeforeVisible', spacerSize, spacerSeparation, containerSize);
} else if (entry.target === spacerAfter && spacerAfter.offsetHeight > 0) {
// When we first start up, both the "before" and "after" spacers will be visible, but it's only relevant to raise a
// single event to load the initial data. To avoid raising two events, skip the one for the "after" spacer if we know
// it's meaningless to talk about any overlap into it.
scrollTriggeredRender = true;
nativeAnchoring.suspend('slide');
const spacerSize = (entry.boundingClientRect.bottom - entry.intersectionRect.bottom) / scaleFactor;
dotNetHelper.invokeMethodAsync('OnSpacerAfterVisible', spacerSize, spacerSeparation, containerSize);
}

const spacerSize = isBefore
? (entry.intersectionRect.top - entry.boundingClientRect.top) / scaleFactor
: (entry.boundingClientRect.bottom - entry.intersectionRect.bottom) / scaleFactor;
const methodName = isBefore ? 'OnSpacerBeforeVisible' : 'OnSpacerAfterVisible';
dotNetHelper.invokeMethodAsync(methodName, spacerSize, spacerSeparation, containerSize, reason);
});
}

Expand Down Expand Up @@ -874,5 +908,3 @@ function dispose(dotNetHelper: DotNet.DotNetObject): void {
// even if init() returned early and no observers were created.
dotNetHelper.dispose();
}


Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ namespace Microsoft.AspNetCore.Components.Web.Virtualization;

internal interface IVirtualizeJsCallbacks
{
void OnBeforeSpacerVisible(float spacerSize, float spacerSeparation, float containerSize);
void OnAfterSpacerVisible(float spacerSize, float spacerSeparation, float containerSize);
void OnBeforeSpacerVisible(float spacerSize, float spacerSeparation, float containerSize, SpacerVisibilityReason reason);
void OnAfterSpacerVisible(float spacerSize, float spacerSeparation, float containerSize, SpacerVisibilityReason reason);
}
26 changes: 26 additions & 0 deletions src/Components/Web/src/Virtualization/SpacerVisibilityReason.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.AspNetCore.Components.Web.Virtualization;

/// <remarks>
/// The numeric values must stay in sync with the <c>SpacerVisibilityReason</c> constant in
/// <c>Virtualize.ts</c>.
/// </remarks>
internal enum SpacerVisibilityReason
{
/// <summary>The user scrolled the spacer into view.</summary>
UserScroll = 0,

/// <summary>
/// A scroll the component itself performed (initial positioning, <c>ScrollToItemAsync</c>, or an
/// anchor restore) transiently exposed the spacer.
/// </summary>
ProgrammaticScroll = 1,

/// <summary>
/// The spacer is visible at rest because the rendered window does not cover the viewport, so the
/// window should grow toward the spacer to fill it.
/// </summary>
ViewportFill = 2,
}
Loading
Loading