Skip to content

Commit c5dc846

Browse files
fix(Listbox): prevent virtualized list from scrolling page on mount (#2675)
Follow-up to #2666, which fixed the non-virtual path only. A virtualized Listbox still pulled the whole page to itself on mount: `highlightSelected` dropped the `scroll` flag whenever `isVirtual` was true, so a list with no checked item fell through to `highlightFirstItem` (synthetic PageUp → `changeHighlight` with focus + `scrollIntoView`), yanking a below-the-fold listbox into view on load. Thread the mount intent through the `virtualFocusHook` payload (`{ event, scroll }`) so the virtualizer can set its roving-tabindex target without focusing/scrolling on mount, mirroring the non-virtual path. The checked-item branch keeps `scrollToIndex`, which only scrolls the internal listbox container, never the page. Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent ed7531b commit c5dc846

3 files changed

Lines changed: 126 additions & 9 deletions

File tree

‎packages/core/src/Listbox/Listbox.test.ts‎

Lines changed: 100 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import type { DOMWrapper, VueWrapper } from '@vue/test-utils'
22
import { mount } from '@vue/test-utils'
3-
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
3+
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
44
import { axe } from 'vitest-axe'
55
import { defineComponent, h, nextTick, ref } from 'vue'
66
import { useKbd } from '@/shared'
77
import { handleSubmit } from '@/test'
8-
import { ListboxItem, ListboxRoot } from '.'
8+
import { ListboxContent, ListboxItem, ListboxRoot, ListboxVirtualizer } from '.'
99
import Listbox from './story/_Listbox.vue'
1010

1111
describe('given default Listbox', () => {
@@ -167,6 +167,104 @@ describe('given a Listbox on initial mount', () => {
167167
})
168168
})
169169

170+
describe('given a virtualized Listbox on initial mount', () => {
171+
let scrollSpy: ReturnType<typeof vi.fn>
172+
173+
window.HTMLElement.prototype.releasePointerCapture = vi.fn()
174+
window.HTMLElement.prototype.hasPointerCapture = vi.fn()
175+
window.HTMLElement.prototype.scrollTo = vi.fn()
176+
globalThis.ResizeObserver = class ResizeObserver {
177+
observe() {}
178+
unobserve() {}
179+
disconnect() {}
180+
}
181+
182+
// jsdom reports zero-sized rects, so `@tanstack/virtual-core` would render no
183+
// items. Give the virtualizer a non-zero viewport so items actually mount.
184+
const originalGetBoundingClientRect = window.HTMLElement.prototype.getBoundingClientRect
185+
beforeAll(() => {
186+
window.HTMLElement.prototype.getBoundingClientRect = function () {
187+
return { width: 200, height: 200, top: 0, left: 0, right: 200, bottom: 200, x: 0, y: 0, toJSON() {} }
188+
}
189+
})
190+
afterAll(() => {
191+
window.HTMLElement.prototype.getBoundingClientRect = originalGetBoundingClientRect
192+
})
193+
194+
const VirtualListbox = defineComponent({
195+
props: { multiple: Boolean, modelValue: { type: null, default: undefined } },
196+
setup(props) {
197+
const options = Array.from({ length: 100 }, (_, i) => ({ label: `Item ${i}`, value: i }))
198+
return () => h(ListboxRoot, { multiple: props.multiple, modelValue: props.modelValue }, () =>
199+
h(ListboxContent, { style: 'height: 200px; overflow: auto' }, () =>
200+
h(ListboxVirtualizer, { options, textContent: (o: any) => o.label }, {
201+
default: ({ option }: any) => h(ListboxItem, { value: option }, () => option.label),
202+
})))
203+
},
204+
})
205+
206+
async function flush() {
207+
// watcher → nextTick → highlightSelected (await nextTick) → virtualFocusHook → rAF
208+
await nextTick()
209+
await nextTick()
210+
await new Promise(resolve => requestAnimationFrame(() => resolve(null)))
211+
await nextTick()
212+
}
213+
214+
beforeEach(() => {
215+
scrollSpy = vi.fn()
216+
window.HTMLElement.prototype.scrollIntoView = scrollSpy
217+
document.body.innerHTML = ''
218+
})
219+
220+
it('should highlight the first item without scrolling the page or stealing focus', async () => {
221+
const wrapper = mount(VirtualListbox, { props: { multiple: true }, attachTo: document.body })
222+
await flush()
223+
224+
const items = wrapper.findAll('[role=option]')
225+
expect(items.length).toBeGreaterThan(0)
226+
// the first item is highlighted for keyboard entry...
227+
expect(items[0].attributes('data-highlighted')).toBe('')
228+
// ...but the mount highlight must not focus it or scroll, otherwise a
229+
// virtualized Listbox below the fold scrolls the whole page on load.
230+
expect(scrollSpy).not.toHaveBeenCalled()
231+
expect(document.activeElement).not.toBe(items[0].element)
232+
})
233+
234+
it('should highlight a pre-selected item on mount without scrolling the page or stealing focus', async () => {
235+
// A selected value below the fold must not pull the page to the listbox on
236+
// mount. The checked item is brought into the internal scroll container
237+
// (`scrollToIndex`) and made the roving-tabindex target, but it is neither
238+
// focused nor scrolled into view at the document level.
239+
// `modelValue` is the option object (items hold the whole option as value);
240+
// it matches option #3 structurally via the default `isEqual` comparison.
241+
const wrapper = mount(VirtualListbox, { props: { modelValue: { label: 'Item 3', value: 3 } }, attachTo: document.body })
242+
await flush()
243+
244+
const checked = wrapper.find('[data-index="3"]')
245+
expect(checked.exists()).toBe(true)
246+
// the checked item (not the first item) becomes the highlight target...
247+
expect(checked.attributes('data-highlighted')).toBe('')
248+
expect(wrapper.find('[data-index="0"]').attributes('data-highlighted')).toBeUndefined()
249+
// ...without focusing it or scrolling the page.
250+
expect(scrollSpy).not.toHaveBeenCalled()
251+
expect(document.activeElement).not.toBe(checked.element)
252+
})
253+
254+
it('should focus and scroll the first item when the user enters the listbox', async () => {
255+
// Entry focus (`onEnter`) is user-driven, so focusing and scrolling the
256+
// first item into view is expected here — unlike the mount highlight above.
257+
const wrapper = mount(VirtualListbox, { props: { multiple: true }, attachTo: document.body })
258+
await flush()
259+
scrollSpy.mockClear()
260+
261+
await wrapper.find('[role=listbox]').trigger('focus')
262+
const items = wrapper.findAll('[role=option]')
263+
expect(document.activeElement).toBe(items[0].element)
264+
expect(scrollSpy).toHaveBeenCalled()
265+
})
266+
})
267+
170268
describe('given multiple `true` Listbox', () => {
171269
const kbd = useKbd()
172270
let wrapper: VueWrapper<InstanceType<typeof Listbox>>

‎packages/core/src/Listbox/ListboxRoot.vue‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ type ListboxRootContext<T> = {
1616
highlightOnHover: Ref<boolean>
1717
highlightedElement: Ref<HTMLElement | null>
1818
isVirtual: Ref<boolean>
19-
virtualFocusHook: EventHook<Event | null | undefined>
19+
virtualFocusHook: EventHook<{ event?: Event, scroll: boolean }>
2020
virtualKeydownHook: EventHook<KeyboardEvent>
2121
virtualHighlightHook: EventHook<any>
2222
by?: string | ((a: T, b: T) => boolean)
@@ -150,7 +150,7 @@ const highlightedElement = ref<HTMLElement | null>(null)
150150
const previousElement = ref<HTMLElement | null>(null)
151151
const isVirtual = ref(false)
152152
const isComposing = ref(false)
153-
const virtualFocusHook = createEventHook<Event | null | undefined>()
153+
const virtualFocusHook = createEventHook<{ event?: Event, scroll: boolean }>()
154154
const virtualKeydownHook = createEventHook<KeyboardEvent>()
155155
const virtualHighlightHook = createEventHook<T>()
156156
@@ -333,8 +333,11 @@ async function highlightSelected(event?: Event, scroll = true) {
333333
return
334334
await nextTick()
335335
if (isVirtual.value) {
336-
// Trigger on nextTick for Virtualizer to be mounted
337-
virtualFocusHook.trigger(event)
336+
// Trigger on nextTick for Virtualizer to be mounted.
337+
// `scroll` is `false` on the initial mount highlight, so the virtualizer sets
338+
// its roving-tabindex target without focusing/scrolling — otherwise a
339+
// virtualized Listbox below the fold would pull the page to it on load.
340+
virtualFocusHook.trigger({ event, scroll })
338341
}
339342
else {
340343
const collection = getCollectionItem()

‎packages/core/src/Listbox/ListboxVirtualizer.vue‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,11 @@ const virtualizedItems = computed(() => virtualizer.value.getVirtualItems().map(
104104
}
105105
}))
106106
107-
rootContext.virtualFocusHook.on((event) => {
107+
rootContext.virtualFocusHook.on(({ event, scroll }) => {
108+
// `scroll` is `false` only for the initial mount highlight. There we set the
109+
// roving-tabindex target without focusing or scrolling, so a virtualized
110+
// Listbox below the fold doesn't pull the page to it on load. User-driven
111+
// highlights (keyboard, typeahead, select) keep scrolling as before.
108112
const index = props.options.findIndex((option) => {
109113
if (Array.isArray(rootContext.modelValue.value))
110114
return compare(option, rootContext.modelValue.value[0], rootContext.by)
@@ -114,19 +118,31 @@ rootContext.virtualFocusHook.on((event) => {
114118
if (index !== -1) {
115119
event?.preventDefault()
116120
121+
// Bringing the checked item into the (internal) scroll viewport is safe — it
122+
// only scrolls the listbox container, never the page.
117123
virtualizer.value.scrollToIndex(index, { align: 'start' })
118124
requestAnimationFrame(() => {
119125
const item = queryCheckedElement(parentEl.value)
120126
if (item) {
121-
rootContext.changeHighlight(item)
127+
rootContext.changeHighlight(item, scroll, scroll ? undefined : false)
122128
if (event)
123129
item?.focus()
124130
}
125131
})
126132
}
127-
else {
133+
else if (scroll) {
128134
rootContext.highlightFirstItem()
129135
}
136+
else {
137+
// Mount highlight with no checked item: highlight the first enabled item only,
138+
// mirroring the non-virtual path. `highlightFirstItem` is reserved for
139+
// user-driven PageUp/Home navigation, which focuses and scrolls.
140+
requestAnimationFrame(() => {
141+
const item = getItems().find(i => i.ref.dataset.disabled !== '')?.ref
142+
if (item)
143+
rootContext.changeHighlight(item, false, false)
144+
})
145+
}
130146
})
131147
132148
rootContext.virtualHighlightHook.on((value) => {

0 commit comments

Comments
 (0)