refactor: paginator
This commit is contained in:
parent
6e54d95bbc
commit
0312547629
9 changed files with 88 additions and 56 deletions
|
@ -2,23 +2,34 @@ import type { Paginator } from 'masto'
|
|||
import type { PaginatorState } from '~/types'
|
||||
|
||||
export function usePaginator<T>(paginator: Paginator<any, T[]>) {
|
||||
let state = $ref('ready' as PaginatorState)
|
||||
const items = $ref<T[]>([])
|
||||
const state = ref<PaginatorState>('idle')
|
||||
const items = ref<T[]>([])
|
||||
|
||||
const endAnchor = ref<HTMLDivElement>()
|
||||
const bound = reactive(useElementBounding(endAnchor))
|
||||
const isInScreen = $computed(() => bound.top < window.innerHeight * 2)
|
||||
const error = ref<unknown | undefined>()
|
||||
|
||||
async function loadNext() {
|
||||
if (state === 'loading' || state === 'done')
|
||||
if (state.value !== 'idle')
|
||||
return
|
||||
|
||||
state = 'loading'
|
||||
const result = await paginator.next()
|
||||
state = result.done ? 'done' : 'ready'
|
||||
state.value = 'loading'
|
||||
try {
|
||||
const result = await paginator.next()
|
||||
|
||||
if (result.value?.length)
|
||||
items.push(...result.value)
|
||||
if (result.value?.length) {
|
||||
items.value.push(...result.value)
|
||||
state.value = 'idle'
|
||||
}
|
||||
else {
|
||||
state.value = 'done'
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
error.value = e
|
||||
state.value = 'error'
|
||||
}
|
||||
|
||||
await nextTick()
|
||||
bound.update()
|
||||
|
@ -31,11 +42,16 @@ export function usePaginator<T>(paginator: Paginator<any, T[]>) {
|
|||
watch(
|
||||
() => isInScreen,
|
||||
() => {
|
||||
if (isInScreen && state !== 'loading')
|
||||
if (isInScreen && state.value === 'idle')
|
||||
loadNext()
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
return { items, state, endAnchor }
|
||||
return {
|
||||
items,
|
||||
state,
|
||||
error,
|
||||
endAnchor,
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue