Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 5 additions & 0 deletions .changeset/quiet-detached-rows.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/virtual-core': patch
---

Fix the ResizeObserver loop error when a list shrinks in a framework that renders in a microtask, such as Vue: a row that the framework detaches right after it clears the row's ref is now unobserved before the browser delivers again.
1 change: 1 addition & 0 deletions packages/react-virtual/e2e/app/resize-delivery/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<style>
:root {
--scale: 1;
--viewport: 600px;
}
body {
margin: 0;
Expand Down
6 changes: 5 additions & 1 deletion packages/react-virtual/e2e/app/resize-delivery/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ function App() {
})

return (
<div id="scroll" ref={parentRef} style={{ height: 600, overflow: 'auto' }}>
<div
id="scroll"
ref={parentRef}
style={{ height: 'var(--viewport)', overflow: 'auto' }}
>
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
{virtualizer.getVirtualItems().map((item) => (
<div
Expand Down
60 changes: 50 additions & 10 deletions packages/react-virtual/e2e/app/test/resize-delivery.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,23 @@ const settleFrames = (page: Page) =>
}),
)

const trackResizeLoops = (page: Page) =>
page.addInitScript(() => {
window.addEventListener('error', (event) => {
if (event.message.includes('ResizeObserver loop')) {
const root = document.documentElement
root.dataset.resizeLoops = String(
Number(root.dataset.resizeLoops ?? 0) + 1,
)
}
})
})

for (const direction of ['grow', 'shrink'] as const) {
test(`resizing rows can ${direction} the rendered range without observer loop errors`, async ({
page,
}) => {
await page.addInitScript(() => {
window.addEventListener('error', (event) => {
if (event.message.includes('ResizeObserver loop')) {
const root = document.documentElement
root.dataset.resizeLoops = String(
Number(root.dataset.resizeLoops ?? 0) + 1,
)
}
})
})
await trackResizeLoops(page)
await page.goto('/resize-delivery/')
const scroll = page.locator('#scroll')
await expect(page.locator('.row').first()).toBeVisible()
Expand Down Expand Up @@ -95,3 +98,40 @@ for (const direction of ['grow', 'shrink'] as const) {
expect(errors).toEqual([])
})
}

test('shrinking the scroll element while scrolling can unmount rows without observer loop errors', async ({
page,
}) => {
await trackResizeLoops(page)
await page.goto('/resize-delivery/')
const scroll = page.locator('#scroll')
await expect(page.locator('.row').first()).toBeVisible()
await scroll.evaluate((element) => {
element.scrollTop = element.scrollHeight / 2
})
await expect
.poll(() => page.locator('.row').first().getAttribute('data-index'))
.not.toBe('0')
await settleFrames(page)

const errors: Array<string> = []
page.on('pageerror', (error) => errors.push(error.message))
await page.evaluate(() => {
document.documentElement.dataset.resizeLoops = '0'
})
const countBefore = await page.locator('.row').count()
// The frame runs the scroll event before it delivers the new size, so
// `isScrolling` is true there and the virtualizer notifies synchronously:
// React unmounts the rows that no longer fit inside the observer callback.
await scroll.evaluate((element) => {
element.scrollTop += 10
document.documentElement.style.setProperty('--viewport', '200px')
})
await expect
.poll(() => page.locator('.row').count())
.toBeLessThan(countBefore)
await settleFrames(page)

expect(await page.locator('html').getAttribute('data-resize-loops')).toBe('0')
expect(errors).toEqual([])
})
31 changes: 25 additions & 6 deletions packages/virtual-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,8 @@ export class Virtualizer<
// Set while a ResizeObserver callback measures its entries; `resizeItem`
// records the pending notify here instead of firing it per entry.
private _resizeBatch: { sync: boolean; notify?: boolean } | null = null
// Set while a microtask waits to run `dropDisconnected` again.
private _dropQueued = false
private now = () => this.targetWindow?.performance?.now?.() ?? Date.now()
private observer = (() => {
let _ro: ResizeObserver | null = null
Expand Down Expand Up @@ -2135,14 +2137,31 @@ export class Virtualizer<
return true
}

private dropDisconnected = () => {
this.elementsCache.forEach((cached, key) => {
if (!cached.isConnected) {
this.observer.unobserve(cached)
this.elementsCache.delete(key)
}
})
}

measureElement = (node: TItemElement | null) => {
if (!node) {
this.elementsCache.forEach((cached, key) => {
if (!cached.isConnected) {
this.observer.unobserve(cached)
this.elementsCache.delete(key)
}
})
this.dropDisconnected()
// A framework clears the ref before it detaches the element, so the row
// that is unmounting is still connected here. A render in a microtask of
// a ResizeObserver delivery (Vue does this) detaches it before the
// browser gathers the next observations, and a detached row that is
// still observed at that point makes the browser report a loop error.
// Check again once the render is done.
if (!this._dropQueued) {
this._dropQueued = true
queueMicrotask(() => {
this._dropQueued = false
this.dropDisconnected()
})
}
return
}

Expand Down
142 changes: 142 additions & 0 deletions packages/virtual-core/tests/measurement.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -999,6 +999,148 @@ test.each(['removed', 'replaced', 'disconnected'] as const)(
},
)

// ─── Rows that a render detaches in a microtask of a delivery ────────────────

// The microtasks of a delivery all run before the browser gathers the next
// observations, so `flushMicrotasks` stands for that moment.
const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve))

// A framework that renders in a microtask after `onChange`, as Vue does, and
// unmounts a row as React and Vue do: the ref gets null first, the element
// leaves the document after.
function setupMicrotaskRender() {
const observers: Array<{
callback: ResizeObserverCallback
targets: Set<any>
}> = []
const mockWindow = {
requestAnimationFrame: vi.fn(),
cancelAnimationFrame: vi.fn(),
performance: { now: () => Date.now() },
ResizeObserver: vi.fn(function (callback: ResizeObserverCallback) {
const targets = new Set<any>()
observers.push({ callback, targets })
return {
observe: (target: any) => targets.add(target),
unobserve: (target: any) => targets.delete(target),
disconnect: () => targets.clear(),
}
}),
}
const el = {
scrollTop: 0,
scrollLeft: 0,
scrollWidth: 400,
scrollHeight: 5000,
clientWidth: 400,
clientHeight: 500,
isConnected: true,
ownerDocument: { defaultView: mockWindow },
}
const nodes = new Map<number, any>()
const node = (i: number) => {
if (!nodes.has(i)) {
nodes.set(i, {
getAttribute: (name: string) =>
name === 'data-index' ? String(i) : null,
isConnected: true,
})
}
return nodes.get(i)
}
const mounted = new Set<number>()
const render = () => {
const wanted = virtualizer.getVirtualItems().map((item) => item.index)
for (const index of [...mounted]) {
if (wanted.includes(index)) continue
virtualizer.measureElement(null)
node(index).isConnected = false
mounted.delete(index)
}
for (const index of wanted) {
if (mounted.has(index)) continue
mounted.add(index)
virtualizer.measureElement(node(index))
}
}
const virtualizer = new Virtualizer({
count: 100,
estimateSize: () => 50,
overscan: 0,
getScrollElement: () => el as unknown as HTMLDivElement,
scrollToFn: vi.fn(),
measureElement: () => 50,
observeElementRect,
observeElementOffset: (_instance, cb) => {
cb(0, false)
return () => {}
},
onChange: () => queueMicrotask(render),
})
virtualizer._willUpdate()
render()

const observed = () => observers.flatMap(({ targets }) => [...targets])
const detachedObserved = () =>
observed().filter((target) => !target.isConnected)
return {
virtualizer,
el,
node,
mounted,
observers,
observed,
detachedObserved,
}
}

test('stops observing rows that a microtask render detaches in a scroll element delivery', async () => {
const { el, node, mounted, observers, observed, detachedObserved } =
setupMicrotaskRender()
expect([...mounted]).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

el.clientHeight = 200
observers.find(({ targets }) => targets.has(el))!.callback([], {} as any)
await flushMicrotasks()

expect([...mounted]).toEqual([0, 1, 2, 3])
expect(detachedObserved()).toEqual([])
expect(observed()).toContain(node(3))
})

test('stops observing rows that a microtask render detaches in a row delivery', async () => {
const { virtualizer, unobserve, node, sizes, deliver } = setupResizeBatch(
(instance, sync) => {
if (!sync) return
queueMicrotask(() => {
instance.measureElement(null)
node(5).isConnected = false
})
},
)
sizes.set(3, 200)
deliver([3])
await flushMicrotasks()

expect(unobserve).toHaveBeenCalledWith(node(5))
expect(virtualizer.elementsCache.has(5)).toBe(false)
})

test('queues one microtask for any number of null refs', async () => {
const { virtualizer } = setupMicrotaskRender()
await flushMicrotasks()
const queue = vi.spyOn(globalThis, 'queueMicrotask')
try {
for (let i = 0; i < 5; i++) virtualizer.measureElement(null)
expect(queue).toHaveBeenCalledTimes(1)
await flushMicrotasks()
virtualizer.measureElement(null)
expect(queue).toHaveBeenCalledTimes(2)
} finally {
queue.mockRestore()
}
})

// ─── useAnimationFrameWithResizeObserver: frames of the scroll element's window

// A window other than the global one, as for a list rendered into a
Expand Down
Loading