Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
1b2a0b5
Introduce a programmatic API to scroll a Virtualize<TItem> component …
ilonatommy May 4, 2026
7b3ac1f
Rename: Item -> Index.
ilonatommy May 4, 2026
93ffce6
Simplify.
ilonatommy May 20, 2026
746238b
Cleanup.
ilonatommy May 20, 2026
244e4ed
Nullable state duplicated 0-th state. Remove nullable.
ilonatommy May 20, 2026
fde7794
Use the pattern from NavigationManager or MAUI's CollectionView.Scrol…
ilonatommy May 20, 2026
d98775d
Apply feedback.
ilonatommy May 20, 2026
29006c2
Empty list: nothing will ever render, so unblock the awaiter.
ilonatommy May 20, 2026
f1d72f8
Fix InitialIndex re-applying when changed from 0 to a non-zero value …
ilonatommy May 21, 2026
5191c02
Cancel in-flight refresh on user scroll during ScrollToIndexAsync and…
ilonatommy May 21, 2026
2850ba9
Feedback: Surface the exception.
ilonatommy May 21, 2026
da829fc
Fix AnchorMode interfering with InitialIndex/ScrollToIndex scrolling,…
ilonatommy May 26, 2026
5e5aa4b
Tmp: logging.
ilonatommy May 27, 2026
39c389d
Wait for async provider in ScrollDoesNotFlash test to fix CI.
ilonatommy May 27, 2026
e413015
Fix: values over the range should be capped same as negative.
ilonatommy May 27, 2026
0331e71
Revert the tmp logging - test is passing now.
ilonatommy May 27, 2026
ae06b29
Stabilize test on CI.
ilonatommy May 28, 2026
99a7d6b
Add 1 px tolerance to test.
ilonatommy May 28, 2026
5f0186d
Merge branch 'main' into scroll-to-index
ilonatommy May 28, 2026
8269b8f
Merge branch 'main' into scroll-to-index
ilonatommy Jun 1, 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/Components/Web.JS/src/Virtualize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export const Virtualize = {
refreshObservers,
setAnchorMode,
restoreAnchor,
alignToItem,
};

const dispatcherObserversByDotNetIdPropname = Symbol();
Expand Down Expand Up @@ -300,19 +301,10 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac
return;
}

let current = spacerBefore.nextElementSibling;
for (let i = 0; i < snapshot.anchorItemIndex && current && current !== spacerAfter; i++) {
current = current.nextElementSibling;
}

if (!current || current === spacerAfter) {
const newOffset = measureLocalChildOffset(snapshot.anchorItemIndex);
if (Number.isNaN(newOffset)) {
return;
}

const containerTop = scrollContainer
? scrollContainer.getBoundingClientRect().top
: 0;
const newOffset = current.getBoundingClientRect().top - containerTop;
const delta = newOffset - snapshot.anchorOffset;

// Suppress spacer IO until next user scroll. Save anchor for drift correction.
Expand All @@ -335,8 +327,10 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac

// Save anchor offset AFTER scrollTop adjustment for drift correction.
if (pendingScrollCorrection) {
const containerTop = scrollContainer ? scrollContainer.getBoundingClientRect().top : 0;
scrollCorrectionOffset = current.getBoundingClientRect().top - containerTop;
const correctedOffset = measureLocalChildOffset(snapshot.anchorItemIndex);
if (!Number.isNaN(correctedOffset)) {
scrollCorrectionOffset = correctedOffset;
}
}

if (preserveWasAtBottom) {
Expand Down Expand Up @@ -427,6 +421,46 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac
let pendingCallbacks: Map<Element, IntersectionObserverEntry> = new Map();
let callbackTimeout: ReturnType<typeof setTimeout> | null = null;

// Walks `localIndex` siblings forward from spacerBefore to find the rendered child,
// returning its viewport-relative top measured against the scroll container (or 0 for
// the window-scroll case). Returns NaN when the slot is missing — e.g., the row hasn't
// rendered yet, or the local index falls outside the currently rendered window.
function measureLocalChildOffset(localIndex: number): number {
let el: Element | null = spacerBefore.nextElementSibling;
for (let i = 0; i < localIndex && el && el !== spacerAfter; i++) {
el = el.nextElementSibling;
}
if (!el || el === spacerAfter) {
return Number.NaN;
}
const containerTop = scrollElement === document.documentElement
? 0
: scrollElement.getBoundingClientRect().top;
return el.getBoundingClientRect().top - containerTop;
}

// Measures the target's viewport-relative top and aligns it to containerTop.
function alignToItemAt(localIndex: number): void {
const delta = measureLocalChildOffset(localIndex);
if (Number.isNaN(delta)) {
return;
}
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;
if (convergingToTop || convergingToBottom) {
convergingToTop = false;
convergingToBottom = false;
stopConvergenceObserving();
}
pendingJumpToStart = false;
pendingJumpToEnd = false;
scrollElement.scrollTo({ top: scrollElement.scrollTop + delta, behavior: 'instant' });
Comment thread
ilonatommy marked this conversation as resolved.
Resolved
}
}

observersByDotNetObjectId[id] = {
intersectionObserver,
resizeObserver,
Expand All @@ -436,6 +470,7 @@ function init(dotNetHelper: DotNet.DotNetObject, spacerBefore: HTMLElement, spac
setConvergingToBottom: () => { convergingToBottom = true; },
setAnchorMode: (mode: number) => { anchorMode = mode; },
restoreAnchor: restoreAnchorForShift,
alignToItem: alignToItemAt,
anchorSnapshot: null as { anchorItemIndex: number; anchorOffset: number; scrollTop: number } | null,
onDispose: () => {
stopConvergenceObserving();
Expand Down Expand Up @@ -659,6 +694,11 @@ function restoreAnchor(dotNetHelper: DotNet.DotNetObject): void {
entry?.restoreAnchor?.();
}

function alignToItem(dotNetHelper: DotNet.DotNetObject, localIndex: number): void {
const { observersByDotNetObjectId, id } = getObserversMapEntry(dotNetHelper);
observersByDotNetObjectId[id]?.alignToItem?.(localIndex);
}

function getObserversMapEntry(dotNetHelper: DotNet.DotNetObject): { observersByDotNetObjectId: {[id: number]: any }, id: number } {
const dotNetHelperDispatcher = dotNetHelper['_callDispatcher'];
const dotNetHelperId = dotNetHelper['_id'];
Expand Down
3 changes: 3 additions & 0 deletions src/Components/Web/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,11 @@ Microsoft.AspNetCore.Components.Web.Media.MediaSource.MimeType.get -> string!
Microsoft.AspNetCore.Components.Web.Media.MediaSource.Stream.get -> System.IO.Stream!
Microsoft.AspNetCore.Components.Web.Virtualization.Virtualize<TItem>.AnchorMode.get -> Microsoft.AspNetCore.Components.Web.Virtualization.VirtualizeAnchorMode
Microsoft.AspNetCore.Components.Web.Virtualization.Virtualize<TItem>.AnchorMode.set -> void
Microsoft.AspNetCore.Components.Web.Virtualization.Virtualize<TItem>.InitialIndex.get -> int
Microsoft.AspNetCore.Components.Web.Virtualization.Virtualize<TItem>.InitialIndex.set -> void
Microsoft.AspNetCore.Components.Web.Virtualization.Virtualize<TItem>.ItemComparer.get -> System.Collections.Generic.IEqualityComparer<TItem>!
Microsoft.AspNetCore.Components.Web.Virtualization.Virtualize<TItem>.ItemComparer.set -> void
Microsoft.AspNetCore.Components.Web.Virtualization.Virtualize<TItem>.ScrollToIndexAsync(int itemIndex, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!
Microsoft.AspNetCore.Components.Web.Virtualization.VirtualizeAnchorMode
Microsoft.AspNetCore.Components.Web.Virtualization.VirtualizeAnchorMode.Beginning = 1 -> Microsoft.AspNetCore.Components.Web.Virtualization.VirtualizeAnchorMode
Microsoft.AspNetCore.Components.Web.Virtualization.VirtualizeAnchorMode.End = 2 -> Microsoft.AspNetCore.Components.Web.Virtualization.VirtualizeAnchorMode
Expand Down
183 changes: 178 additions & 5 deletions src/Components/Web/src/Virtualization/Virtualize.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ public sealed class Virtualize<TItem> : ComponentBase, IVirtualizeJsCallbacks, I

private CancellationTokenSource? _refreshCts;

private CancellationTokenSource? _currentScrollCts;

private TaskCompletionSource? _nextRenderTcs;

private bool _initialScrollApplied;

private bool _skipNextDistributionRefresh;

private Exception? _refreshException;
Expand Down Expand Up @@ -193,6 +199,15 @@ public IEqualityComparer<TItem> ItemComparer
}
}

/// <summary>
/// Gets or sets the zero-based index of the item to scroll to on first interactive render.
/// Applied once when the component first knows its item count and ignored on subsequent re-renders;
/// to scroll programmatically at any later point, call <see cref="ScrollToIndexAsync(int, CancellationToken)"/>.
/// Out-of-range values are clamped. The default value, <c>0</c>, means no initial scroll.
/// </summary>
[Parameter]
public int InitialIndex { get; set; }

private IEqualityComparer<TItem> _itemComparer = EqualityComparer<TItem>.Default;

/// <summary>
Expand All @@ -211,6 +226,145 @@ public async Task RefreshDataAsync()
await RefreshDataCoreAsync(renderOnSuccess: false);
}

/// <summary>
/// Scrolls the viewport so the item at <paramref name="itemIndex"/> is aligned to the start of the visible area.
/// </summary>
/// <remarks>
/// Each call cancels any previously-running <see cref="ScrollToIndexAsync(int, CancellationToken)"/> (last call wins).
/// Must be called on the renderer's synchronization context; background-thread callers should wrap with
/// <see cref="ComponentBase.InvokeAsync(Func{Task})"/> to await completion.
/// </remarks>
/// <param name="itemIndex">The zero-based index of the item to scroll to.</param>
/// <param name="cancellationToken">A token that lets the caller request cancellation.</param>
/// <returns>A <see cref="Task"/> that completes when the target is aligned or superseded by another call,
/// or faults with <see cref="OperationCanceledException"/> if <paramref name="cancellationToken"/> is cancelled.</returns>
public Task ScrollToIndexAsync(int itemIndex, CancellationToken cancellationToken = default)
{
if (_jsInterop is null)
{
// Throw synchronously so misuse is reported on the call site, not on the Task.
throw new InvalidOperationException(
$"{nameof(ScrollToIndexAsync)} cannot be called before the {nameof(Virtualize<TItem>)} has been initialized for interactive rendering. " +
$"Use the {nameof(InitialIndex)} parameter to set the initial scroll position.");
}

return ScrollToIndexAsyncCore(itemIndex, cancellationToken);
}

private async Task ScrollToIndexAsyncCore(int itemIndex, CancellationToken cancellationToken)
{
// Cancel-and-switch (last call wins); finally block guards cleanup by ref-equality.
_currentScrollCts?.Cancel();

var ourCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_currentScrollCts = ourCts;
var token = ourCts.Token;

try
{
token.ThrowIfCancellationRequested();
var refetchRequired = MoveWindowToContain(itemIndex);
await EnsureRenderCommittedAsync(refetchRequired, token);
Comment thread
ilonatommy marked this conversation as resolved.
Resolved
await AlignToTargetAsync(itemIndex, token);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
// Ignore exceptions caused by cancellations.
}
finally
{
// Only the current owner clears shared state; orphaned operations leave it alone.
if (ReferenceEquals(_currentScrollCts, ourCts))
{
_currentScrollCts = null;
}
ourCts.Dispose();
}
}

private bool MoveWindowToContain(int itemIndex)
{
var clamped = ClampToItemRange(itemIndex);
var capacity = _visibleItemCapacity > 0 ? _visibleItemCapacity : OverscanCount * 2 + 1;
var desiredItemsBefore = Math.Max(0, clamped - OverscanCount);
if (_itemCount > 0 && desiredItemsBefore + capacity > _itemCount)
{
desiredItemsBefore = Math.Max(0, _itemCount - capacity);
}

var windowChanged = desiredItemsBefore != _itemsBefore;
if (_visibleItemCapacity <= 0)
{
// Seed capacity when called before any spacer-observer feedback so RefreshDataCoreAsync asks for a meaningful slice.
_visibleItemCapacity = capacity;
}
if (windowChanged)
{
_itemsBefore = desiredItemsBefore;
_skipNextDistributionRefresh = false;
}

var alreadyLoadedForWindow = _loadedItems is not null && _loadedItemsStartIndex == _itemsBefore;
return windowChanged || !alreadyLoadedForWindow;
}

private async Task EnsureRenderCommittedAsync(bool refetchRequired, CancellationToken token)
{
// Set up the signal BEFORE any render: on WASM, OnAfterRenderAsync runs synchronously inside RefreshDataCoreAsync.
var renderCommitTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_nextRenderTcs = renderCommitTcs;
using var renderReg = token.Register(static state => ((TaskCompletionSource)state!).TrySetCanceled(), renderCommitTcs);

if (refetchRequired)
{
await RefreshDataCoreAsync(renderOnSuccess: true);
token.ThrowIfCancellationRequested();
}
else
{
// Window already loaded — trigger one render so we can wait for the DOM to reflect it.
StateHasChanged();
}

// OnAfterRenderAsync signals once the rendered slice matches our window, so one await is enough.
await renderCommitTcs.Task;
token.ThrowIfCancellationRequested();
}

private async ValueTask AlignToTargetAsync(int itemIndex, CancellationToken token)
{
// Re-clamp in case _itemCount shifted during the fetch.
var localIndex = ClampToItemRange(itemIndex) - _itemsBefore;
if (localIndex < 0 || localIndex >= _visibleItemCapacity || _lastRenderedItemCount == 0)
{
// Window doesn't contain the target (e.g., empty provider result) — bail cleanly.
return;
}

// Pixel-exact one-shot scroll: JS reads getBoundingClientRect() and sets scrollTop.
if (_jsInterop is not null)
{
await _jsInterop.AlignToItemAsync(localIndex, token);
}
}

private int ClampToItemRange(int requested)
{
if (_itemCount <= 0)
{
return Math.Max(0, requested);
}
if (requested < 0)
{
return 0;
}
if (requested >= _itemCount)
{
return _itemCount - 1;
}
return requested;
}

/// <inheritdoc />
protected override void OnParametersSet()
{
Expand Down Expand Up @@ -272,6 +426,14 @@ protected override void OnParametersSet()
/// <inheritdoc />
protected override async Task OnAfterRenderAsync(bool firstRender)
{
// Wait until the loaded slice matches the window; earlier renders measure stale DOM.
var pendingRenderTcs = _nextRenderTcs;
if (pendingRenderTcs is not null && _loadedItemsStartIndex == _itemsBefore && (_lastRenderedItemCount > 0 || _itemCount == 0))
{
_nextRenderTcs = null;
pendingRenderTcs.TrySetResult();
}
Comment thread
ilonatommy marked this conversation as resolved.
Resolved

if (firstRender)
{
_jsInterop = new VirtualizeJsInterop(this, JSRuntime);
Expand All @@ -294,9 +456,10 @@ protected override async Task OnAfterRenderAsync(bool firstRender)
await _jsInterop.SetAnchorModeAsync((int)AnchorMode);
}

// If a mutation captured an anchor snapshot before render,
// restore it now to keep the same row at the same viewport offset.
var shouldRestore = _pendingAnchorRestore && !_pendingScrollToBottom;
// If a mutation captured an anchor snapshot, restore it to keep the same row at the
// same viewport offset. Skip while a ScrollToIndexAsync is in flight — we are
// intentionally moving the viewport.
var shouldRestore = _pendingAnchorRestore && !_pendingScrollToBottom && _currentScrollCts is null;
_pendingAnchorRestore = false;

if (shouldRestore)
Expand All @@ -306,6 +469,13 @@ protected override async Task OnAfterRenderAsync(bool firstRender)

await _jsInterop.RefreshObserversAsync();
}

// Apply InitialIndex once, when the count is known.
if (!_initialScrollApplied && _jsInterop is not null && InitialIndex > 0 && _itemCount > 0)
{
_initialScrollApplied = true;
Comment thread
ilonatommy marked this conversation as resolved.
Resolved
await ScrollToIndexAsync(InitialIndex);
}
}

/// <inheritdoc />
Expand Down Expand Up @@ -433,7 +603,7 @@ private bool ProcessMeasurements(float spacerSeparation)

void IVirtualizeJsCallbacks.OnBeforeSpacerVisible(float spacerSize, float spacerSeparation, float containerSize)
{
if (_pendingAnchorRestore)
if (_pendingAnchorRestore || _currentScrollCts is not null)
{
return;
}
Comment thread
ilonatommy marked this conversation as resolved.
Resolved
Expand All @@ -453,7 +623,7 @@ void IVirtualizeJsCallbacks.OnBeforeSpacerVisible(float spacerSize, float spacer

void IVirtualizeJsCallbacks.OnAfterSpacerVisible(float spacerSize, float spacerSeparation, float containerSize)
{
if (_pendingAnchorRestore)
if (_pendingAnchorRestore || _currentScrollCts is not null)
{
return;
}
Expand Down Expand Up @@ -730,6 +900,9 @@ public async ValueTask DisposeAsync()
{
_refreshCts?.Cancel();

_currentScrollCts?.Cancel();
_nextRenderTcs?.TrySetCanceled(CancellationToken.None);

if (_jsInterop != null)
{
await _jsInterop.DisposeAsync();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ public ValueTask RestoreAnchorAsync()
return _jsRuntime.InvokeVoidAsync($"{JsFunctionsPrefix}.restoreAnchor", _selfReference);
}

public ValueTask AlignToItemAsync(int localIndex, CancellationToken cancellationToken = default)
{
return _jsRuntime.InvokeVoidAsync($"{JsFunctionsPrefix}.alignToItem", cancellationToken, _selfReference, localIndex);
}

public async ValueTask DisposeAsync()
{
if (_selfReference != null)
Expand Down
Loading
Loading