Skip to content

feat(useVirtualList): Add options behavior, block and inline to exposed scrollTo method #4905

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
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
53 changes: 45 additions & 8 deletions packages/core/useVirtualList/demo.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import { useVirtualList } from '@vueuse/core'
import { computed, shallowRef } from 'vue'

const index = shallowRef<number>()
const search = shallowRef('')
const search = shallowRef<'' | 'small' | 'large'>('')
const smoothScroll = shallowRef(false)
const block = shallowRef<ScrollLogicalPosition>('start')

const allItems = Array.from(Array.from({ length: 99999 }).keys())
.map(i => ({
Expand All @@ -23,26 +25,61 @@ const { list, containerProps, wrapperProps, scrollTo } = useVirtualList(
},
)
function handleScrollTo() {
if (index.value)
scrollTo(index.value)
if (typeof index.value === 'number')
scrollTo(index.value, { behavior: smoothScroll.value ? 'smooth' : 'auto', block: block.value })
}
</script>

<template>
<div>
<div>
<form @submit.prevent="handleScrollTo">
<div class="inline-block mr-4">
Jump to index
<input v-model="index" placeholder="Index" type="number">
</div>
<button type="button" @click="handleScrollTo">
<label class="inline-block mr-4"><input v-model="smoothScroll" type="checkbox"> Smooth</label>
<div bg="$vp-c-bg" border="$vp-c-divider 1" inline-flex items-center relative rounded>
<i v-if="block === 'start'" i-carbon-align-vertical-top absolute left-2 opacity-80 pointer-events-none />
<i v-if="block === 'center'" i-carbon-align-vertical-center absolute left-2 opacity-80 pointer-events-none />
<i v-if="block === 'end'" i-carbon-align-vertical-bottom absolute left-2 opacity-80 pointer-events-none />
<i v-if="block === 'nearest'" i-carbon-arrows-vertical absolute left-2 opacity-80 pointer-events-none />
<select v-model="block" px-8 border-0 bg-transparent h-9 rounded appearance-none>
<option value="start">
Start
</option>
<option value="center">
Center
</option>
<option value="end">
End
</option>
<option value="nearest">
Nearest
</option>
</select>
<i i-carbon-chevron-down absolute right-2 opacity-80 pointer-events-none />
</div>
<button type="submit">
Go
</button>
</div>
</form>
<div>
<div class="inline-block mr-4">
Filter list by size
<input v-model="search" placeholder="e.g. small, medium, large" type="search">
<div>Filter list by size</div>
<div bg="$vp-c-bg" border="$vp-c-divider 1" inline-flex items-center relative rounded mb-2>
<select v-model="search" pl-4 pr-8 border-0 bg-transparent h-9 rounded appearance-none>
<option value="">
All
</option>
<option value="small">
Small
</option>
<option value="large">
Large
</option>
</select>
<i i-carbon-chevron-down absolute right-2 opacity-80 pointer-events-none />
</div>
</div>
</div>
<div v-bind="containerProps" class="h-300px overflow-auto p-2 bg-gray-500/5 rounded">
Expand Down
2 changes: 1 addition & 1 deletion packages/core/useVirtualList/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,4 @@ const { list, containerProps, wrapperProps } = useVirtualList(
</template>
```

To scroll to a specific element, the component exposes `scrollTo(index: number) => void`.
To scroll to a specific element, the component exposes `scrollTo(index: number, options?: { behavior?: ScrollBehavior, block?: ScrollLogicalPosition, inline?: ScrollLogicalPosition }) => void`.
89 changes: 84 additions & 5 deletions packages/core/useVirtualList/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,23 @@ import { describe, expect, it } from 'vitest'
import { ref as deepRef } from 'vue'
import { useVirtualList } from './index'

function createDiv(properties: Partial<HTMLElement>) {
return {
...document.createElement('div'),
...properties,
scrollTo(options?: ScrollToOptions | number) {
if (typeof options === 'object') {
if (options.top) {
this.scrollTop = options.top
}
if (options.left) {
this.scrollLeft = options.left
}
}
},
}
}

describe('useVirtualList', () => {
it('should be defined', () => {
expect(useVirtualList).toBeDefined()
Expand All @@ -13,7 +30,7 @@ describe('useVirtualList', () => {
containerProps: { ref: containerRef },
scrollTo,
} = useVirtualList(['a', 'b', 'c', 'd', 'e', 'f'], { itemHeight: () => 50 })
const div = { ...document.createElement('div'), clientHeight: 100 }
const div = createDiv({ clientHeight: 100 })

containerRef.value = div
scrollTo(0)
Expand All @@ -28,7 +45,7 @@ describe('useVirtualList, vertical', () => {
containerProps: { ref: containerRef },
scrollTo,
} = useVirtualList(deepRef(['a', 'b', 'c', 'd', 'e', 'f']), { itemHeight: () => 50, overscan: 1 })
const div = { ...document.createElement('div'), clientHeight: 50 }
const div = createDiv({ clientHeight: 50 })

containerRef.value = div

Expand All @@ -47,7 +64,7 @@ describe('useVirtualList, vertical', () => {
containerProps: { ref: containerRef },
scrollTo,
} = useVirtualList(deepRef(['a', 'b', 'c', 'd', 'e', 'f', 'g']), { itemHeight: () => 50, overscan: 1 })
const div = { ...document.createElement('div'), clientHeight: 50 }
const div = createDiv({ clientHeight: 50 })

containerRef.value = div

Expand All @@ -72,6 +89,37 @@ describe('useVirtualList, vertical', () => {
scrollTo(6)
expect(list.value.map(i => i.data)).toEqual(['f', 'g'])
})

it('correctly uses the scrollTo block option to align inside the container', () => {
const {
list,
containerProps: { ref: containerRef },
scrollTo,
} = useVirtualList(deepRef(['a', 'b', 'c', 'd', 'e', 'f', 'g']), { itemHeight: () => 50, overscan: 1 })
const div = createDiv({ clientHeight: 140 })

containerRef.value = div

scrollTo(0, { block: 'start' })
expect(list.value.map(i => i.data)).toEqual(['a', 'b', 'c', 'd'])

scrollTo(3, { block: 'start' })
expect(list.value.map(i => i.data)).toEqual(['c', 'd', 'e', 'f'])

scrollTo(3, { block: 'center' })
expect(list.value.map(i => i.data)).toEqual(['c', 'd', 'e', 'f'])

scrollTo(3, { block: 'end' })
expect(list.value.map(i => i.data)).toEqual(['b', 'c', 'd', 'e'])

containerRef.value.scrollTop = 1500
scrollTo(3, { block: 'nearest' })
expect(list.value.map(i => i.data)).toEqual(['c', 'd', 'e', 'f'])

containerRef.value.scrollTop = 0
scrollTo(3, { block: 'nearest' })
expect(list.value.map(i => i.data)).toEqual(['b', 'c', 'd', 'e'])
})
})

describe('useVirtualList, horizontal', () => {
Expand All @@ -81,7 +129,7 @@ describe('useVirtualList, horizontal', () => {
containerProps: { ref: containerRef },
scrollTo,
} = useVirtualList(deepRef(['a', 'b', 'c', 'd', 'e', 'f']), { itemWidth: () => 50, overscan: 1 })
const div = { ...document.createElement('div'), clientWidth: 50 }
const div = createDiv({ clientWidth: 50 })

containerRef.value = div

Expand All @@ -100,7 +148,7 @@ describe('useVirtualList, horizontal', () => {
containerProps: { ref: containerRef },
scrollTo,
} = useVirtualList(deepRef(['a', 'b', 'c', 'd', 'e', 'f', 'g']), { itemWidth: () => 50, overscan: 1 })
const div = { ...document.createElement('div'), clientWidth: 50 }
const div = createDiv({ clientWidth: 50 })

containerRef.value = div

Expand All @@ -126,6 +174,37 @@ describe('useVirtualList, horizontal', () => {
expect(list.value.map(i => i.data)).toEqual(['f', 'g'])
})

it('correctly uses the scrollTo inline option to align inside the container', () => {
const {
list,
containerProps: { ref: containerRef },
scrollTo,
} = useVirtualList(deepRef(['a', 'b', 'c', 'd', 'e', 'f', 'g']), { itemWidth: () => 50, overscan: 1 })
const div = createDiv({ clientWidth: 140 })

containerRef.value = div

scrollTo(0, { inline: 'start' })
expect(list.value.map(i => i.data)).toEqual(['a', 'b', 'c', 'd'])

scrollTo(3, { inline: 'start' })
expect(list.value.map(i => i.data)).toEqual(['c', 'd', 'e', 'f'])

scrollTo(3, { inline: 'center' })
expect(list.value.map(i => i.data)).toEqual(['c', 'd', 'e', 'f'])

scrollTo(3, { inline: 'end' })
expect(list.value.map(i => i.data)).toEqual(['b', 'c', 'd', 'e'])

containerRef.value.scrollLeft = 1500
scrollTo(3, { inline: 'nearest' })
expect(list.value.map(i => i.data)).toEqual(['c', 'd', 'e', 'f'])

containerRef.value.scrollLeft = 0
scrollTo(3, { inline: 'nearest' })
expect(list.value.map(i => i.data)).toEqual(['b', 'c', 'd', 'e'])
})

it('allows both readonly and mutable arrays as input', () => {
const mutableInput: string[] = ['a', 'b', 'c', 'd', 'e', 'f']
const readonlyInput: readonly string[] = ['a', 'b', 'c', 'd', 'e', 'f']
Expand Down
51 changes: 43 additions & 8 deletions packages/core/useVirtualList/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,11 @@ export interface UseVirtualListItem<T> {
index: number
}

export interface UseVirtualListScrollToOptions { behavior?: ScrollBehavior, block?: ScrollLogicalPosition, inline?: ScrollLogicalPosition }

export interface UseVirtualListReturn<T> {
list: Ref<UseVirtualListItem<T>[]>
scrollTo: (index: number) => void
scrollTo: (index: number, options?: UseVirtualListScrollToOptions) => void

containerProps: {
ref: Ref<HTMLElement | null>
Expand Down Expand Up @@ -220,12 +222,45 @@ const scrollToDictionaryForElementScrollKey = {
vertical: 'scrollTop',
} as const

function createScrollTo<T>(type: 'horizontal' | 'vertical', calculateRange: () => void, getDistance: ReturnType<typeof createGetDistance>, containerRef: UseVirtualListResources<T>['containerRef']) {
return (index: number) => {
if (containerRef.value) {
containerRef.value[scrollToDictionaryForElementScrollKey[type]] = getDistance(index)
calculateRange()
const scrollToDictionaryForElementScrollToKey = {
horizontal: 'left',
vertical: 'top',
} as const

const defaultScrollToOptions: UseVirtualListScrollToOptions = { behavior: 'auto', block: 'start', inline: 'nearest' }

function createScrollTo<T>(type: 'horizontal' | 'vertical', calculateRange: () => void, getDistance: ReturnType<typeof createGetDistance>, containerRef: UseVirtualListResources<T>['containerRef'], itemSize: UseVirtualListItemSize) {
return (index: number, options: UseVirtualListScrollToOptions = defaultScrollToOptions) => {
if (!containerRef.value)
return

options = Object.assign(defaultScrollToOptions, options)
let offset = 0
const axisToCheck = options[type === 'horizontal' ? 'inline' : 'block']
if (axisToCheck) {
const containerSize = type === 'horizontal' ? containerRef.value.clientWidth : containerRef.value.clientHeight
const fullItemSize = typeof itemSize === 'number' ? itemSize : itemSize(index)

if (axisToCheck === 'center') {
offset = (containerSize / 2) - (fullItemSize / 2)
}
else if (axisToCheck === 'end') {
offset = containerSize - fullItemSize
}
else if (axisToCheck === 'nearest') {
const containerScrollPosition = containerRef.value[scrollToDictionaryForElementScrollKey[type]]
if (getDistance(index) > containerScrollPosition + (containerSize / 2)) {
offset = containerSize - fullItemSize
}
}
}

containerRef.value.scrollTo({
[scrollToDictionaryForElementScrollToKey[type]]: getDistance(index) - offset,
behavior: options.behavior,
})

calculateRange()
}
}

Expand All @@ -250,7 +285,7 @@ function useHorizontalVirtualList<T>(options: UseHorizontalVirtualListOptions, l

useWatchForSizes(size, list, containerRef, calculateRange)

const scrollTo = createScrollTo('horizontal', calculateRange, getDistanceLeft, containerRef)
const scrollTo = createScrollTo('horizontal', calculateRange, getDistanceLeft, containerRef, itemWidth)

const wrapperProps = computed(() => {
return {
Expand Down Expand Up @@ -296,7 +331,7 @@ function useVerticalVirtualList<T>(options: UseVerticalVirtualListOptions, list:

useWatchForSizes(size, list, containerRef, calculateRange)

const scrollTo = createScrollTo('vertical', calculateRange, getDistanceTop, containerRef)
const scrollTo = createScrollTo('vertical', calculateRange, getDistanceTop, containerRef, itemHeight)

const wrapperProps = computed(() => {
return {
Expand Down
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy