Line data Source code
1 16 : <template>
2 514 : <div
3 : ref="container"
4 : class="h-full scrollbar-thin scrollbar-thumb-(--muted) scrollbar-track-transparent scrollbar-gutter-stable overflow-y-auto [overflow-anchor:none]"
5 : >
6 : <div :style="topSpacerStyle" />
7 : <div :style="mergedGridStyle">
8 1356 : <div
9 : v-for="(item, i) in renderedItems"
10 : :key="item.key ?? item.id"
11 : data-virtual-grid-item
12 : >
13 : <slot name="item" :item :index="state.start + i" />
14 : </div>
15 : </div>
16 : <div :style="bottomSpacerStyle" />
17 : </div>
18 : </template>
19 :
20 : <script setup lang="ts" generic="T">
21 : import {
22 : useElementSize,
23 : useInfiniteScroll,
24 : useScroll,
25 : whenever
26 : } from '@vueuse/core'
27 : import { clamp, debounce } from 'es-toolkit/compat'
28 : import { computed, onBeforeUnmount, ref, watch } from 'vue'
29 : import type { CSSProperties } from 'vue'
30 :
31 : type HasKeyOrId = { key: string; id?: string } | { key?: string; id: string }
32 :
33 : type GridState = {
34 : start: number
35 : end: number
36 : }
37 :
38 : const {
39 : items,
40 : gridStyle,
41 : bufferRows = 1,
42 : resizeDebounce = 64,
43 : defaultItemHeight = 200,
44 : defaultItemWidth = 200,
45 : maxColumns = Infinity,
46 : onLoadMore,
47 : canLoadMore = false
48 : } = defineProps<{
49 : items: readonly (T & HasKeyOrId)[]
50 : gridStyle: CSSProperties
51 : bufferRows?: number
52 : resizeDebounce?: number
53 : defaultItemHeight?: number
54 : defaultItemWidth?: number
55 : maxColumns?: number
56 : onLoadMore?: () => unknown
57 : canLoadMore?: boolean
58 : }>()
59 :
60 103 : const itemHeight = ref(defaultItemHeight)
61 103 : const itemWidth = ref(defaultItemWidth)
62 103 : const container = ref<HTMLElement | null>(null)
63 103 : const { width, height } = useElementSize(container)
64 103 : const { y: scrollY } = useScroll(container, {
65 : eventListenerOptions: { passive: true }
66 : })
67 :
68 103 : const cols = computed(() => {
69 423 : if (maxColumns !== Infinity) return maxColumns
70 423 : return Math.floor(width.value / itemWidth.value) || 1
71 : })
72 :
73 103 : const mergedGridStyle = computed<CSSProperties>(() => {
74 104 : if (maxColumns === Infinity) return gridStyle
75 10 : return {
76 : ...gridStyle,
77 : gridTemplateColumns: `repeat(${maxColumns}, minmax(0, 1fr))`
78 : }
79 : })
80 :
81 103 : const viewRows = computed(() => Math.ceil(height.value / itemHeight.value))
82 103 : const offsetRows = computed(() => Math.floor(scrollY.value / itemHeight.value))
83 103 : const isValidGrid = computed(() => height.value && width.value && items?.length)
84 :
85 103 : const state = computed<GridState>(() => {
86 415 : const fromRow = offsetRows.value - bufferRows
87 415 : const toRow = offsetRows.value + bufferRows + viewRows.value
88 :
89 415 : const fromCol = fromRow * cols.value
90 415 : const toCol = toRow * cols.value
91 :
92 415 : const total = items?.length ?? 0
93 415 : const windowSize = Math.max(toCol - fromCol, 0)
94 :
95 415 : const end = clamp(toCol, 0, total)
96 415 : let start = clamp(fromCol, 0, end)
97 :
98 415 : if (start === end && total > 0) {
99 0 : start = Math.max(0, end - windowSize)
100 : }
101 :
102 415 : return { start, end }
103 : })
104 103 : const renderedItems = computed(() =>
105 : isValidGrid.value ? items.slice(state.value.start, state.value.end) : []
106 : )
107 :
108 840 : function rowsToHeight(itemsCount: number): string {
109 : const rows = Math.ceil(itemsCount / cols.value)
110 840 : return `${rows * itemHeight.value}px`
111 : }
112 103 : const topSpacerStyle = computed<CSSProperties>(() => ({
113 : height: rowsToHeight(state.value.start)
114 : }))
115 103 : const bottomSpacerStyle = computed<CSSProperties>(() => ({
116 : height: rowsToHeight(items.length - state.value.end)
117 : }))
118 :
119 103 : const distance = 2 * defaultItemHeight * (1 + bufferRows)
120 103 : useInfiniteScroll(
121 : container,
122 : async () => {
123 6 : await onLoadMore?.()
124 : },
125 : { canLoadMore: () => canLoadMore, distance }
126 : )
127 :
128 200 : function updateItemSize(): void {
129 200 : if (container.value) {
130 200 : const firstItem = container.value.querySelector('[data-virtual-grid-item]')
131 :
132 200 : if (!firstItem?.clientHeight || !firstItem?.clientWidth) return
133 :
134 192 : if (itemHeight.value !== firstItem.clientHeight) {
135 99 : itemHeight.value = firstItem.clientHeight
136 : }
137 193 : if (itemWidth.value !== firstItem.clientWidth) {
138 98 : itemWidth.value = firstItem.clientWidth
139 : }
140 : }
141 : }
142 103 : const onResize = debounce(updateItemSize, resizeDebounce)
143 103 : watch([width, height], onResize, { flush: 'post' })
144 103 : watch(() => gridStyle, updateItemSize, { flush: 'post' })
145 103 : whenever(() => items, updateItemSize, { flush: 'post' })
146 103 : onBeforeUnmount(() => {
147 22 : onResize.cancel()
148 : })
149 : </script>
|