Skip to content
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

feat(useInfiniteScroll): new options #1354

Merged
merged 4 commits into from May 31, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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,
})
})
}
}
},
)
}