Skip to content

Commit

Permalink
feat(useInfiniteScroll): new options (#1354)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
innocenzi and antfu committed May 31, 2022
1 parent bbb8334 commit 5a1b932
Showing 1 changed file with 38 additions and 7 deletions.
45 changes: 38 additions & 7 deletions packages/core/useInfiniteScroll/index.ts
@@ -1,5 +1,5 @@
import type { UnwrapNestedRefs } from 'vue-demi'
import { reactive, watch } from 'vue-demi'
import { nextTick, reactive, unref, watch } from 'vue-demi'
import type { MaybeRef } from '@vueuse/shared'
import type { UseScrollOptions } from '../useScroll'
import { useScroll } from '../useScroll'
Expand All @@ -11,6 +11,20 @@ export interface UseInfiniteScrollOptions extends UseScrollOptions {
* @default 0
*/
distance?: number

/**
* The direction in which to listen the scroll.
*
* @default 'bottom'
*/
direction?: 'top' | 'bottom'

/**
* Whether to preserve the current scroll position when loading more items.
*
* @default false
*/
preserveScrollPosition?: boolean
}

/**
Expand All @@ -20,25 +34,42 @@ export interface UseInfiniteScrollOptions extends UseScrollOptions {
*/
export function useInfiniteScroll(
element: MaybeRef<HTMLElement | SVGElement | Window | Document | null | undefined>,
onLoadMore: (state: UnwrapNestedRefs<ReturnType<typeof useScroll>>) => void,
onLoadMore: (state: UnwrapNestedRefs<ReturnType<typeof useScroll>>) => void | Promise<void>,
options: UseInfiniteScrollOptions = {},
) {
const direction = options.direction ?? 'bottom'
const state = reactive(useScroll(
element,
{
...options,
offset: {
bottom: options.distance ?? 0,
[direction]: options.distance ?? 0,
...options.offset,
},
},
))

watch(
() => state.arrivedState.bottom,
(v) => {
if (v)
onLoadMore(state)
() => state.arrivedState[direction],
async(v) => {
if (v) {
const elem = unref(element) as Element
const previous = {
height: elem?.scrollHeight ?? 0,
width: elem?.scrollWidth ?? 0,
}

await onLoadMore(state)

if (options.preserveScrollPosition && elem) {
nextTick(() => {
elem.scrollTo({
top: elem.scrollHeight - previous.height,
left: elem.scrollWidth - previous.width,
})
})
}
}
},
)
}

0 comments on commit 5a1b932

Please sign in to comment.