-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
320 lines (256 loc) · 8.91 KB
/
index.ts
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import type { MaybeRef } from '@vueuse/shared'
import type { ComputedRef, Ref, ShallowRef, StyleValue } from 'vue-demi'
import { computed, ref, shallowRef, watch } from 'vue-demi'
import { useElementSize } from '../useElementSize'
type UseVirtualListItemSize = number | ((index: number) => number)
export interface UseHorizontalVirtualListOptions extends UseVirtualListOptionsBase {
/**
* item width, accept a pixel value or a function that returns the height
*
* @default 0
*/
itemWidth: UseVirtualListItemSize
}
export interface UseVerticalVirtualListOptions extends UseVirtualListOptionsBase {
/**
* item height, accept a pixel value or a function that returns the height
*
* @default 0
*/
itemHeight: UseVirtualListItemSize
}
export interface UseVirtualListOptionsBase {
/**
* the extra buffer items outside of the view area
*
* @default 5
*/
overscan?: number
}
export type UseVirtualListOptions = UseHorizontalVirtualListOptions | UseVerticalVirtualListOptions
export interface UseVirtualListItem<T> {
data: T
index: number
}
export interface UseVirtualListReturn<T> {
list: Ref<UseVirtualListItem<T>[]>
scrollTo: (index: number) => void
containerProps: {
ref: Ref<HTMLElement | null>
onScroll: () => void
style: StyleValue
}
wrapperProps: ComputedRef<{
style: {
width: string
height: string
marginTop: string
} | {
width: string
height: string
marginLeft: string
display: string
}
}>
}
export function useVirtualList<T = any>(list: MaybeRef<T[]>, options: UseVirtualListOptions): UseVirtualListReturn<T> {
const { containerStyle, wrapperProps, scrollTo, calculateRange, currentList, containerRef } = 'itemHeight' in options
? useVerticalVirtualList(options, list)
: useHorizontalVirtualList(options, list)
return {
list: currentList,
scrollTo,
containerProps: {
ref: containerRef,
onScroll: () => {
calculateRange()
},
style: containerStyle,
},
wrapperProps,
}
}
type UseVirtualListContainerRef = Ref<HTMLElement | null>
interface UseVirtualElementSizes {
width: Ref<number>
height: Ref<number>
}
type UseVirtualListArray<T> = UseVirtualListItem<T>[]
type UseVirtualListRefArray<T> = Ref<UseVirtualListArray<T>>
type UseVirtualListSource<T> = Ref<T[]> | ShallowRef<T[]>
interface UseVirtualListState { start: number; end: number }
type RefState = Ref<UseVirtualListState>
interface UseVirtualListResources<T> {
state: RefState
source: UseVirtualListSource<T>
currentList: UseVirtualListRefArray<T>
size: UseVirtualElementSizes
containerRef: UseVirtualListContainerRef
}
function useVirtualListResources<T>(list: MaybeRef<T[]>): UseVirtualListResources<T> {
const containerRef = ref<HTMLElement | null>(null)
const size = useElementSize(containerRef)
const currentList: Ref<UseVirtualListItem<T>[]> = ref([])
const source = shallowRef(list)
const state: Ref<{ start: number; end: number }> = ref({ start: 0, end: 10 })
return { state, source, currentList, size, containerRef }
}
function createGetViewCapacity<T>(state: UseVirtualListResources<T>['state'], source: UseVirtualListResources<T>['source'], itemSize: UseVirtualListItemSize) {
return (containerHeight: number) => {
if (typeof itemSize === 'number')
return Math.ceil(containerHeight / itemSize)
const { start = 0 } = state.value
let sum = 0
let capacity = 0
for (let i = start; i < source.value.length; i++) {
const height = itemSize(i)
sum += height
if (sum >= containerHeight) {
capacity = i
break
}
}
return capacity - start
}
}
function createGetOffset<T>(source: UseVirtualListResources<T>['source'], itemSize: UseVirtualListItemSize) {
return (scrollDirection: number) => {
if (typeof itemSize === 'number')
return Math.floor(scrollDirection / itemSize) + 1
let sum = 0
let offset = 0
for (let i = 0; i < source.value.length; i++) {
const size = itemSize(i)
sum += size
if (sum >= scrollDirection) {
offset = i
break
}
}
return offset + 1
}
}
function createCalculateRange<T>(type: 'horizontal' | 'vertical', overscan: number, getOffset: ReturnType<typeof createGetOffset>,
getViewCapacity: ReturnType<typeof createGetViewCapacity>,
{ containerRef, state, currentList, source }: UseVirtualListResources<T>) {
return () => {
const element = containerRef.value
if (element) {
const offset = getOffset(type === 'vertical' ? element.scrollTop : element.scrollLeft)
const viewCapacity = getViewCapacity(type === 'vertical' ? element.clientHeight : element.clientWidth)
const from = offset - overscan
const to = offset + viewCapacity + overscan
state.value = {
start: from < 0 ? 0 : from,
end: to > source.value.length
? source.value.length
: to,
}
currentList.value = source.value
.slice(state.value.start, state.value.end)
.map((ele, index) => ({
data: ele,
index: index + state.value.start,
}))
}
}
}
function createGetDistance<T>(itemSize: UseVirtualListItemSize, source: UseVirtualListResources<T>['source']) {
return (index: number) => {
if (typeof itemSize === 'number') {
const size = index * itemSize
return size
}
const size = source.value
.slice(0, index)
.reduce((sum, _, i) => sum + itemSize(i), 0)
return size
}
}
function useWatchForSizes<T>(size: UseVirtualElementSizes, list: MaybeRef<T[]>, calculateRange: () => void) {
watch([size.width, size.height, list], () => {
calculateRange()
})
}
function createComputedTotalSize<T>(itemSize: UseVirtualListItemSize, source: UseVirtualListResources<T>['source']) {
return computed(() => {
if (typeof itemSize === 'number')
return source.value.length * itemSize
return source.value.reduce((sum, _, index) => sum + itemSize(index), 0)
})
}
const scrollToDictionaryForElementScrollKey = {
horizontal: 'scrollLeft',
vertical: 'scrollTop',
} as const
function createScrollTo<T>(type: 'horizontal' | 'vertical', calculateRange: () => void, getDistance: ReturnType<typeof createGetDistance>, containerRef: UseVirtualListResources<T>['containerRef']) {
return (index: number) => {
if (containerRef.value) {
containerRef.value[scrollToDictionaryForElementScrollKey[type]] = getDistance(index)
calculateRange()
}
}
}
function useHorizontalVirtualList<T>(options: UseHorizontalVirtualListOptions, list: MaybeRef<T[]>) {
const resources = useVirtualListResources(list)
const { state, source, currentList, size, containerRef } = resources
const containerStyle: StyleValue = { overflowX: 'auto' }
const { itemWidth, overscan = 5 } = options
const getViewCapacity = createGetViewCapacity(state, source, itemWidth)
const getOffset = createGetOffset(source, itemWidth)
const calculateRange = createCalculateRange('horizontal', overscan, getOffset, getViewCapacity, resources)
const getDistanceLeft = createGetDistance(itemWidth, source)
const offsetLeft = computed(() => getDistanceLeft(state.value.start))
const totalWidth = createComputedTotalSize(itemWidth, source)
useWatchForSizes(size, list, calculateRange)
const scrollTo = createScrollTo('horizontal', calculateRange, getDistanceLeft, containerRef)
const wrapperProps = computed(() => {
return {
style: {
height: '100%',
width: `${totalWidth.value - offsetLeft.value}px`,
marginLeft: `${offsetLeft.value}px`,
display: 'flex',
},
}
})
return {
scrollTo,
calculateRange,
wrapperProps,
containerStyle,
currentList,
containerRef,
}
}
function useVerticalVirtualList<T>(options: UseVerticalVirtualListOptions, list: MaybeRef<T[]>) {
const resources = useVirtualListResources(list)
const { state, source, currentList, size, containerRef } = resources
const containerStyle: StyleValue = { overflowY: 'auto' }
const { itemHeight, overscan = 5 } = options
const getViewCapacity = createGetViewCapacity(state, source, itemHeight)
const getOffset = createGetOffset(source, itemHeight)
const calculateRange = createCalculateRange('vertical', overscan, getOffset, getViewCapacity, resources)
const getDistanceTop = createGetDistance(itemHeight, source)
const offsetTop = computed(() => getDistanceTop(state.value.start))
const totalHeight = createComputedTotalSize(itemHeight, source)
useWatchForSizes(size, list, calculateRange)
const scrollTo = createScrollTo('vertical', calculateRange, getDistanceTop, containerRef)
const wrapperProps = computed(() => {
return {
style: {
width: '100%',
height: `${totalHeight.value - offsetTop.value}px`,
marginTop: `${offsetTop.value}px`,
},
}
})
return {
calculateRange,
scrollTo,
containerStyle,
wrapperProps,
currentList,
containerRef,
}
}