-
-
Notifications
You must be signed in to change notification settings - Fork 425
Expand file tree
/
Copy pathuseVisibleItems.ts
More file actions
59 lines (52 loc) · 1.62 KB
/
useVisibleItems.ts
File metadata and controls
59 lines (52 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { computed, shallowRef, toValue } from 'vue'
import type { MaybeRefOrGetter } from 'vue'
export interface UseVisibleItemsOptions {
/**
* Called when expanding. Useful for loading remaining data on demand.
* If it returns a promise, `isExpanding` will be `true` until it resolves.
* Return `false` to signal a partial load — `showAll` stays false so
* `hasMore` remains true and the user can retry.
*/
onExpand?: () => void | boolean | Promise<void | boolean>
}
export function useVisibleItems<T>(
items: MaybeRefOrGetter<T[]>,
limit: number,
options?: UseVisibleItemsOptions,
) {
const showAll = shallowRef(false)
const isExpanding = shallowRef(false)
const visibleItems = computed(() => {
const list = toValue(items)
return showAll.value ? list : list.slice(0, limit)
})
const hiddenCount = computed(() =>
showAll.value ? 0 : Math.max(0, toValue(items).length - limit),
)
const hasMore = computed(() => !showAll.value && toValue(items).length > limit)
const expand = async () => {
if (showAll.value) return
let fullyLoaded = true
if (options?.onExpand) {
isExpanding.value = true
try {
const result = await options.onExpand()
if (result === false) fullyLoaded = false
} finally {
isExpanding.value = false
}
}
if (fullyLoaded) showAll.value = true
}
const collapse = () => {
showAll.value = false
}
const toggle = async () => {
if (showAll.value) {
collapse()
} else {
await expand()
}
}
return { visibleItems, hiddenCount, hasMore, isExpanding, showAll, expand, collapse, toggle }
}