diff --git a/packages/react-virtual/src/index.tsx b/packages/react-virtual/src/index.tsx index d835e7c4..fb245800 100644 --- a/packages/react-virtual/src/index.tsx +++ b/packages/react-virtual/src/index.tsx @@ -84,7 +84,6 @@ export function useWindowVirtualizer( observeElementRect: observeWindowRect, observeElementOffset: observeWindowOffset, scrollToFn: windowScroll, - initialOffset: () => (typeof document !== 'undefined' ? window.scrollY : 0), ...options, }) } diff --git a/packages/react-virtual/tests/index.test.tsx b/packages/react-virtual/tests/index.test.tsx index c7348dc2..8b520a6e 100644 --- a/packages/react-virtual/tests/index.test.tsx +++ b/packages/react-virtual/tests/index.test.tsx @@ -2,7 +2,7 @@ import { beforeEach, test, expect, vi } from 'vitest' import * as React from 'react' import { render, screen, fireEvent } from '@testing-library/react' -import { useVirtualizer, Range } from '../src/index' +import { useVirtualizer, useWindowVirtualizer, Range } from '../src/index' beforeEach(() => { Object.defineProperties(HTMLElement.prototype, { @@ -190,3 +190,111 @@ test('should handle handle height change', () => { rerender() expect(screen.queryByText('Row 0')).toBeInTheDocument() }) + +test('useWindowVirtualizer should not set initialOffset from window.scrollY by default', () => { + // Reset window.scrollY to 0 initially + Object.defineProperty(window, 'scrollY', { + configurable: true, + value: 0, + }) + + // Mock window.scrollTo to avoid jsdom error + window.scrollTo = vi.fn() + + let virtualizerInstance: any = null + + function WindowList() { + const virtualizer = useWindowVirtualizer({ + count: 100, + estimateSize: () => 50, + overscan: 5, + }) + + virtualizerInstance = virtualizer + + return ( +
+ {virtualizer.getVirtualItems().map((item) => ( +
+ Item {item.index} +
+ ))} +
+ ) + } + + render() + + // Verify that initialOffset option is not set (should be default 0) + expect(virtualizerInstance.options.initialOffset).toBe(0) + + // The scrollOffset will match window.scrollY (0 in this case) due to the observer + expect(virtualizerInstance.scrollOffset).toBe(0) +}) + +test('useWindowVirtualizer should allow explicit initialOffset', () => { + // Mock window.scrollY + Object.defineProperty(window, 'scrollY', { + configurable: true, + value: 500, + }) + + // Mock window.scrollTo to avoid jsdom error + window.scrollTo = vi.fn() + + let virtualizerInstance: any = null + + function WindowListWithOffset() { + const virtualizer = useWindowVirtualizer({ + count: 100, + estimateSize: () => 50, + overscan: 5, + initialOffset: () => window.scrollY, // Explicitly set to preserve scroll + }) + + virtualizerInstance = virtualizer + + return ( +
+ {virtualizer.getVirtualItems().map((item) => ( +
+ Item {item.index} +
+ ))} +
+ ) + } + + render() + + // The virtualizer should use the provided initialOffset + expect(virtualizerInstance.scrollOffset ?? 500).toBe(500) +})