Skip to content

Commit cc5d11e

Browse files
petyosiHawkForge
andauthored
Honor initialTopMostItemIndex and scrollToIndex inside VirtuosoMockContext (#1553)
* fix: honor initialTopMostItemIndex inside VirtuosoMockContext The scroller drops scrollTo requests when the scroll element has no layout (offsetHeight 0), which is always the case in jsdom. With initialTopMostItemIndex set, the list waits for the scroll to land before rendering items, so it stayed empty. Under VirtuosoMockContext the scroller now reports the requested position as the new scroll container state. Fixes #1001 * Keep mock scrollTo from re-rendering the scroller and cover more scroll paths The mock scrollTo handler read totalListHeight through useEmitterValue, which made the Scroller re-render on every list height change in production too, where the mock path is never used. Read it through a ref fed by useEmitter instead. Add tests for clamping near the end, align: 'end', imperative and smooth scrollToIndex, GroupedVirtuoso and TableVirtuoso under VirtuosoMockContext. * Regenerate skill references for the item remount troubleshooting docs The troubleshooting section added in #1540 was not propagated to the generated skill references, so the Validate Skills drift check failed. --------- Co-authored-by: HawkForge <[email protected]>
1 parent 636edb2 commit cc5d11e

6 files changed

Lines changed: 244 additions & 3 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'react-virtuoso': patch
3+
---
4+
5+
Fixed `initialTopMostItemIndex` and `scrollToIndex` having no effect inside `VirtuosoMockContext`. The scroller now reports the requested scroll position directly, so the list renders the target items in tests instead of staying empty or starting from the first item.

‎packages/react-virtuoso/src/Virtuoso.tsx‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,30 @@ export function buildScroller({ useEmitter, useEmitterValue, usePublisher }: Hoo
327327
horizontalDirection
328328
)
329329

330-
useEmitter('scrollTo', scrollToCallback)
330+
const ctx = React.useContext(VirtuosoMockContext)
331+
// a ref instead of useEmitterValue, so that the scroller does not re-render on every list height change outside of tests
332+
const totalListHeightRef = React.useRef(0)
333+
const setTotalListHeight = React.useCallback((value: number) => {
334+
totalListHeightRef.current = value
335+
}, [])
336+
useEmitter('totalListHeight', setTotalListHeight)
337+
// there is no layout to scroll in a mocked environment, so report the requested position as the new scroll state
338+
const mockScrollToCallback = React.useCallback(
339+
(location: ScrollToOptions) => {
340+
if (!ctx || location.top === undefined) {
341+
return
342+
}
343+
const scrollHeight = Math.max(totalListHeightRef.current, ctx.viewportHeight)
344+
const scrollTop = Math.ceil(Math.max(Math.min(scrollHeight - ctx.viewportHeight, location.top), 0))
345+
scrollContainerStateCallback({ scrollHeight, scrollTop, viewportHeight: ctx.viewportHeight })
346+
if (location.behavior === 'smooth') {
347+
smoothScrollTargetReached(true)
348+
}
349+
},
350+
[ctx, scrollContainerStateCallback, smoothScrollTargetReached]
351+
)
352+
353+
useEmitter('scrollTo', ctx ? mockScrollToCallback : scrollToCallback)
331354
useEmitter('scrollBy', scrollByCallback)
332355
const defaultStyle = horizontalDirection ? horizontalScrollerStyle : scrollerStyle
333356
return (

‎packages/react-virtuoso/test/VirtuosoMockContext.test.tsx‎

Lines changed: 119 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,15 @@
1-
import { render } from '@testing-library/react'
1+
import React from 'react'
2+
3+
import { act, render, waitFor } from '@testing-library/react'
24
import { describe, expect, it } from 'vitest'
35

4-
import { TableVirtuoso, Virtuoso, VirtuosoGrid, VirtuosoGridMockContext, VirtuosoMockContext } from '../src'
6+
import { GroupedVirtuoso, TableVirtuoso, Virtuoso, VirtuosoGrid, VirtuosoGridMockContext, VirtuosoMockContext } from '../src'
7+
8+
import type { VirtuosoHandle } from '../src'
9+
10+
function renderedIndices(container: HTMLElement) {
11+
return Array.from(container.querySelectorAll<HTMLElement>('[data-index]')).map((el) => el.dataset.index)
12+
}
513

614
describe('VirtuosoMockContext', () => {
715
interface Item {
@@ -49,6 +57,100 @@ describe('VirtuosoMockContext', () => {
4957

5058
expect(container).toMatchSnapshot()
5159
})
60+
61+
it('starts at the initialTopMostItemIndex', async () => {
62+
const { container } = render(<Virtuoso initialTopMostItemIndex={50} itemContent={(index) => `Item ${index}`} totalCount={100} />, {
63+
wrapper: ({ children }) => (
64+
<VirtuosoMockContext.Provider value={{ itemHeight: 100, viewportHeight: 300 }}>{children}</VirtuosoMockContext.Provider>
65+
),
66+
})
67+
68+
await waitFor(() => {
69+
expect(Array.from(container.querySelectorAll('[data-index]')).map((el) => el.textContent)).toEqual([
70+
'Item 50',
71+
'Item 51',
72+
'Item 52',
73+
])
74+
})
75+
})
76+
77+
it('clamps the initialTopMostItemIndex to the end of the list', async () => {
78+
const { container } = render(<Virtuoso initialTopMostItemIndex={99} itemContent={(index) => `Item ${index}`} totalCount={100} />, {
79+
wrapper: ({ children }) => (
80+
<VirtuosoMockContext.Provider value={{ itemHeight: 100, viewportHeight: 300 }}>{children}</VirtuosoMockContext.Provider>
81+
),
82+
})
83+
84+
await waitFor(() => {
85+
expect(renderedIndices(container)).toEqual(['97', '98', '99'])
86+
})
87+
})
88+
89+
it('aligns the initialTopMostItemIndex to the end', async () => {
90+
const { container } = render(
91+
<Virtuoso initialTopMostItemIndex={{ align: 'end', index: 50 }} itemContent={(index) => `Item ${index}`} totalCount={100} />,
92+
{
93+
wrapper: ({ children }) => (
94+
<VirtuosoMockContext.Provider value={{ itemHeight: 100, viewportHeight: 300 }}>{children}</VirtuosoMockContext.Provider>
95+
),
96+
}
97+
)
98+
99+
await waitFor(() => {
100+
expect(renderedIndices(container)).toEqual(['48', '49', '50'])
101+
})
102+
})
103+
104+
it('scrolls to an index imperatively', async () => {
105+
const ref = React.createRef<VirtuosoHandle>()
106+
const { container } = render(<Virtuoso itemContent={(index) => `Item ${index}`} ref={ref} totalCount={100} />, {
107+
wrapper: ({ children }) => (
108+
<VirtuosoMockContext.Provider value={{ itemHeight: 100, viewportHeight: 300 }}>{children}</VirtuosoMockContext.Provider>
109+
),
110+
})
111+
112+
act(() => {
113+
ref.current!.scrollToIndex(30)
114+
})
115+
await waitFor(() => {
116+
expect(renderedIndices(container)).toEqual(['30', '31', '32'])
117+
})
118+
119+
act(() => {
120+
ref.current!.scrollToIndex({ behavior: 'smooth', index: 60 })
121+
})
122+
await waitFor(() => {
123+
expect(renderedIndices(container)).toEqual(['60', '61', '62'])
124+
})
125+
})
126+
})
127+
128+
describe('GroupedList', () => {
129+
it('starts at the initialTopMostItemIndex', async () => {
130+
const { container } = render(
131+
<GroupedVirtuoso
132+
groupContent={(index) => `Group ${index}`}
133+
groupCounts={[50, 50]}
134+
initialTopMostItemIndex={20}
135+
itemContent={(index) => `Item ${index}`}
136+
/>,
137+
{
138+
wrapper: ({ children }) => (
139+
<VirtuosoMockContext.Provider value={{ itemHeight: 100, viewportHeight: 300 }}>{children}</VirtuosoMockContext.Provider>
140+
),
141+
}
142+
)
143+
144+
// the scroll position is offset by the sticky group header, so item 19 is rendered underneath it
145+
await waitFor(() => {
146+
expect(Array.from(container.querySelectorAll('[data-index]')).map((el) => el.textContent)).toEqual([
147+
'Group 0',
148+
'Item 19',
149+
'Item 20',
150+
'Item 21',
151+
])
152+
})
153+
})
52154
})
53155

54156
describe('Table', () => {
@@ -71,6 +173,21 @@ describe('VirtuosoMockContext', () => {
71173

72174
expect(container).toMatchSnapshot()
73175
})
176+
177+
it('starts at the initialTopMostItemIndex', async () => {
178+
const { container } = render(
179+
<TableVirtuoso initialTopMostItemIndex={50} itemContent={(index) => <td>Item {index}</td>} totalCount={100} />,
180+
{
181+
wrapper: ({ children }) => (
182+
<VirtuosoMockContext.Provider value={{ itemHeight: 100, viewportHeight: 300 }}>{children}</VirtuosoMockContext.Provider>
183+
),
184+
}
185+
)
186+
187+
await waitFor(() => {
188+
expect(renderedIndices(container)).toEqual(['50', '51', '52'])
189+
})
190+
})
74191
})
75192

76193
describe('Grid', () => {

‎packages/virtuoso-skills/skills/react-virtuoso/references/6.troubleshooting.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,38 @@ function App() {
122122

123123
See the [custom rendering documentation](/customize-rendering) for more details on component customization patterns.
124124

125+
## Items change height when they scroll back into view
126+
127+
Unlike the inline component case above, some remounts are expected. The list unmounts items that leave the rendered area and mounts them again when they come back. A remounted item is a new component instance, so its local state starts over. If that state affects the item's height, the new measurement differs from the size the list remembered, and the layout shifts.
128+
129+
### Why this happens
130+
131+
These patterns change an item's height on every mount:
132+
133+
- An entry animation that animates `height` or `max-height` replays each time the item mounts.
134+
- An image without a fixed size takes little or no space until it loads, then grows.
135+
- Content that appears after a delay, such as action buttons, is hidden again until the delay passes.
136+
137+
### Fix
138+
139+
Make the item render at its final height on every mount:
140+
141+
- Reserve space for images and other async content with explicit `width`/`height` or `aspect-ratio`.
142+
- Animate entries with `transform` and `opacity` only, so the animation doesn't change the layout.
143+
- Keep state that should apply only once, such as "the entry animation has played", outside the item component and key it by the item id, so it survives remounts:
144+
145+
```jsx
146+
const playedIds = new Set()
147+
148+
function Message({ message }) {
149+
const [animate] = React.useState(() => !playedIds.has(message.id))
150+
React.useEffect(() => {
151+
playedIds.add(message.id)
152+
}, [message.id])
153+
return <div className={animate ? 'fade-in' : undefined}>{message.text}</div>
154+
}
155+
```
156+
125157
## Webpack dev server shows an error `Uncaught Error: ResizeObserver loop completed with undelivered notifications`
126158

127159
This is a known issue with the Webpack dev server and the `ResizeObserver` API used by Virtuoso. To silence this error, apply the following configuration to your server:

‎plugins/virtuoso-skills/skills/react-virtuoso/references/6.troubleshooting.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,38 @@ function App() {
122122

123123
See the [custom rendering documentation](/customize-rendering) for more details on component customization patterns.
124124

125+
## Items change height when they scroll back into view
126+
127+
Unlike the inline component case above, some remounts are expected. The list unmounts items that leave the rendered area and mounts them again when they come back. A remounted item is a new component instance, so its local state starts over. If that state affects the item's height, the new measurement differs from the size the list remembered, and the layout shifts.
128+
129+
### Why this happens
130+
131+
These patterns change an item's height on every mount:
132+
133+
- An entry animation that animates `height` or `max-height` replays each time the item mounts.
134+
- An image without a fixed size takes little or no space until it loads, then grows.
135+
- Content that appears after a delay, such as action buttons, is hidden again until the delay passes.
136+
137+
### Fix
138+
139+
Make the item render at its final height on every mount:
140+
141+
- Reserve space for images and other async content with explicit `width`/`height` or `aspect-ratio`.
142+
- Animate entries with `transform` and `opacity` only, so the animation doesn't change the layout.
143+
- Keep state that should apply only once, such as "the entry animation has played", outside the item component and key it by the item id, so it survives remounts:
144+
145+
```jsx
146+
const playedIds = new Set()
147+
148+
function Message({ message }) {
149+
const [animate] = React.useState(() => !playedIds.has(message.id))
150+
React.useEffect(() => {
151+
playedIds.add(message.id)
152+
}, [message.id])
153+
return <div className={animate ? 'fade-in' : undefined}>{message.text}</div>
154+
}
155+
```
156+
125157
## Webpack dev server shows an error `Uncaught Error: ResizeObserver loop completed with undelivered notifications`
126158

127159
This is a known issue with the Webpack dev server and the `ResizeObserver` API used by Virtuoso. To silence this error, apply the following configuration to your server:

‎skills/react-virtuoso/references/6.troubleshooting.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,38 @@ function App() {
122122

123123
See the [custom rendering documentation](/customize-rendering) for more details on component customization patterns.
124124

125+
## Items change height when they scroll back into view
126+
127+
Unlike the inline component case above, some remounts are expected. The list unmounts items that leave the rendered area and mounts them again when they come back. A remounted item is a new component instance, so its local state starts over. If that state affects the item's height, the new measurement differs from the size the list remembered, and the layout shifts.
128+
129+
### Why this happens
130+
131+
These patterns change an item's height on every mount:
132+
133+
- An entry animation that animates `height` or `max-height` replays each time the item mounts.
134+
- An image without a fixed size takes little or no space until it loads, then grows.
135+
- Content that appears after a delay, such as action buttons, is hidden again until the delay passes.
136+
137+
### Fix
138+
139+
Make the item render at its final height on every mount:
140+
141+
- Reserve space for images and other async content with explicit `width`/`height` or `aspect-ratio`.
142+
- Animate entries with `transform` and `opacity` only, so the animation doesn't change the layout.
143+
- Keep state that should apply only once, such as "the entry animation has played", outside the item component and key it by the item id, so it survives remounts:
144+
145+
```jsx
146+
const playedIds = new Set()
147+
148+
function Message({ message }) {
149+
const [animate] = React.useState(() => !playedIds.has(message.id))
150+
React.useEffect(() => {
151+
playedIds.add(message.id)
152+
}, [message.id])
153+
return <div className={animate ? 'fade-in' : undefined}>{message.text}</div>
154+
}
155+
```
156+
125157
## Webpack dev server shows an error `Uncaught Error: ResizeObserver loop completed with undelivered notifications`
126158

127159
This is a known issue with the Webpack dev server and the `ResizeObserver` API used by Virtuoso. To silence this error, apply the following configuration to your server:

0 commit comments

Comments
 (0)