Skip to content
Open
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/bound-rows-render.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/svelte-virtual': patch
---

Read the scroll element again after Svelte updates the DOM, so a virtualizer whose scroll element is assigned with `bind:this` after the store is subscribed renders its rows.
13 changes: 12 additions & 1 deletion packages/svelte-virtual/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
observeWindowRect,
windowScroll,
} from '@tanstack/virtual-core'
import { tick } from 'svelte'
import { derived, writable } from 'svelte/store'
import type { PartialKeys, VirtualizerOptions } from '@tanstack/virtual-core'
import type { Readable, Writable } from 'svelte/store'
Expand Down Expand Up @@ -64,7 +65,17 @@ function createVirtualizerBase<

virtualizerWritable = writable(virtualizer, () => {
setOptions({})
return virtualizer._didMount()
let subscribed = true
// The store is usually subscribed before `bind:this` assigns the scroll
// element, so read it again once Svelte has updated the DOM.
tick().then(() => {
if (subscribed) virtualizer._willUpdate()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
})
const cleanup = virtualizer._didMount()
return () => {
subscribed = false
cleanup()
}
})

return derived(virtualizerWritable, (instance) =>
Expand Down
31 changes: 31 additions & 0 deletions packages/svelte-virtual/tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { tick } from 'svelte'
import { get } from 'svelte/store'
import { describe, expect, test, vi } from 'vitest'
import { createVirtualizer, createWindowVirtualizer } from '../src'
Expand Down Expand Up @@ -149,3 +150,33 @@ describe.each([
}
})
})

test('createVirtualizer reads a scroll element bound after subscribing', async () => {
let scrollElement: Element | null = null
const subscriber = vi.fn()
const store = createVirtualizer<Element, Element>({
count: 100,
estimateSize: () => 40,
getScrollElement: () => scrollElement,
observeElementRect: (_instance, cb) => {
cb({ width: 400, height: 400 })
},
observeElementOffset: () => {},
scrollToFn: () => {},
})
const unsubscribe = store.subscribe(subscriber)
const virtualizer = get(store)

try {
expect(virtualizer.getVirtualItems()).toHaveLength(0)

scrollElement = {} as Element
subscriber.mockClear()
await tick()

expect(virtualizer.getVirtualItems()).toHaveLength(11)
expect(subscriber).toHaveBeenCalledWith(virtualizer)
} finally {
unsubscribe()
}
})