/
index.tsx
964 lines (862 loc) · 27.4 KB
/
index.tsx
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
import React, {
useCallback,
useEffect,
useState,
useMemo,
useRef,
useImperativeHandle,
} from 'react'
import {unstable_batchedUpdates} from 'react-dom'
import ResizeObserver from 'resize-observer-polyfill'
import trieMemoize from 'trie-memoize'
import OneKeyMap from '@essentials/one-key-map'
import memoizeOne from '@essentials/memoize-one'
import useLayoutEffect from '@react-hook/passive-layout-effect'
import useWindowScroll from '@react-hook/window-scroll'
import useWindowSize from '@react-hook/window-size'
import createIntervalTree from './IntervalTree'
const emptyObj = {}
const emptyArr = []
const binarySearch = (a: number[], y: number): number => {
let l = 0
let h = a.length - 1
while (l <= h) {
const m = (l + h) >>> 1
const x = a[m]
if (x === y) return m
else if (x <= y) l = m + 1
else h = m - 1
}
return -1
}
interface IUpdatedItem {
top: number
left: number
height: number
}
interface ItemPositioner {
set: (index: number, height: number) => any
get: (index: number | undefined) => any
update: (updates: number[]) => (number | IUpdatedItem)[]
columnCount: number
columnWidth: number
columnGutter: number
}
const createItemPositioner = (
columnCount: number,
columnWidth: number,
columnGutter = 0
): ItemPositioner => {
// Track the height of each column.
// Layout algorithm below always inserts into the shortest column.
const columnHeights = new Array(columnCount),
items: Record<number, any> = {},
columnItems: number[][] = new Array(columnCount)
for (let i = 0; i < columnCount; i++) {
columnHeights[i] = 0
columnItems[i] = []
}
const set = (index: number, height = 0): any => {
let column = 0
// finds the shortest column and uses it
for (let i = 1; i < columnHeights.length; i++) {
if (columnHeights[i] < columnHeights[column]) column = i
}
const left = column * (columnWidth + columnGutter),
top = columnHeights[column] || 0,
item = {left, top, height, column}
columnHeights[column] = top + height + columnGutter
items[index] = item
columnItems[column].push(index)
return item
}
// this only updates items in the specific columns that have changed, on and after the
// specific items that have changed
const update = (updates: number[]): (number | IUpdatedItem)[] => {
const columns: number[] = new Array(columnCount),
updatedItems: (number | IUpdatedItem)[] = []
let i = 0,
j = 0
// determines which columns have items that changed, as well as the minimum index
// changed in that column, as all items after that index will have their positions
// affected by the change
for (; i < updates.length - 1; i++) {
const index = updates[i],
item = items[index]
item.height = updates[++i]
columns[item.column] =
columns[item.column] === void 0
? index
: Math.min(index, columns[item.column])
}
for (i = 0; i < columns.length; i++) {
// bails out if the column didn't change
if (columns[i] === void 0) continue
const itemsInColumn = columnItems[i],
// the index order is sorted with certainty so binary search is a great solution
// here as opposed to Array.indexOf()
startIndex = binarySearch(itemsInColumn, columns[i]),
index = columnItems[i][startIndex],
startItem = items[index]
columnHeights[i] = startItem.top + startItem.height + columnGutter
updatedItems.push(index, startItem)
for (j = startIndex + 1; j < itemsInColumn.length; j++) {
const index = itemsInColumn[j],
item = items[index]
item.top = columnHeights[i]
columnHeights[i] = item.top + item.height + columnGutter
updatedItems.push(index, item)
}
}
return updatedItems
}
return {
set,
get: (index: number | undefined): any =>
index === void 0 ? index : items[index],
update,
columnCount,
columnWidth,
columnGutter,
}
}
// Position cache requirements:
interface PositionCache {
range: (
lo: number,
hi: number,
renderCallback: (index: number, left: number, top: number) => void
) => void
size: number
estimateTotalHeight: (
itemCount: number,
columnCount: number,
defaultItemHeight: number
) => number
getShortestColumnSize: () => number
setPosition: (
index: number,
left: number,
top: number,
height: number
) => void
}
// O(log(n)) lookup of cells to render for a given viewport size
// O(1) lookup of shortest measured column (so we know when to enter phase 1)
const createPositionCache = (): PositionCache => {
// Store tops and bottoms of each cell for fast intersection lookup.
const intervalTree = createIntervalTree(),
// Tracks the intervals that were inserted into the interval tree so they can be
// removed when positions are updated
intervalValueMap: number[][] = [],
// Maps cell index to x coordinates for quick lookup.
leftMap: number[] = [],
// Tracks the height of each column
columnSizeMap = {}
const estimateTotalHeight = (
itemCount: number,
columnCount: number,
defaultItemHeight: number
): number =>
itemCount === intervalTree.size
? getTallestColumnSize()
: getTallestColumnSize() +
Math.ceil((itemCount - intervalTree.size) / columnCount) *
defaultItemHeight
// Render all cells visible within the viewport range defined.
const range = (
lo: number,
hi: number,
renderCallback: (index: number, left: number, top: number) => void
): void => {
intervalTree.search(lo, hi, (index, top) =>
renderCallback(index, leftMap[index], top)
)
}
const setPosition = (
index: number,
left: number,
top: number,
height: number
): void => {
const prevInterval = intervalValueMap[index],
prev = prevInterval !== void 0 && prevInterval[1],
next = top + height
if (prevInterval !== void 0) intervalTree.remove.apply(null, prevInterval)
intervalTree.insert(top, next, index)
intervalValueMap[index] = [top, next, index]
leftMap[index] = left
const columnHeight = columnSizeMap[left]
if (prev !== false && prev > next && columnSizeMap[left] === prev)
columnSizeMap[left] = next
else {
columnSizeMap[left] = Math.max(columnHeight || 0, next)
}
}
const getShortestColumnSize = (): number => {
const keys = Object.keys(columnSizeMap)
let size = columnSizeMap[keys[0]],
i = 1
if (size !== void 0 && keys.length > 1) {
for (; i < keys.length; i++) {
const height = columnSizeMap[keys[i]]
size = size < height ? size : height
}
}
return size || 0
}
const getTallestColumnSize = (): number =>
Math.max(0, Math.max.apply(null, Object.values(columnSizeMap)))
return {
range,
get size(): number {
return intervalTree.size
},
estimateTotalHeight,
getShortestColumnSize,
setPosition,
}
}
export interface WindowScrollerOptions {
size?: {
wait?: number
}
scroll?: {
fps?: number
}
}
export interface WindowScrollerResult {
width: number
height: number
scrollY: number
isScrolling: boolean
}
const defaultSizeOpt = {wait: 120}
export const useWindowScroller = (
initialWidth: number,
initialHeight: number,
options: WindowScrollerOptions = emptyObj
): WindowScrollerResult => {
const fps = options.scroll?.fps || 8
const scrollY = useWindowScroll(fps)
const [width, height] = useWindowSize(
initialWidth,
initialHeight,
options.size || defaultSizeOpt
)
const [isScrolling, setIsScrolling] = useState<boolean>(false)
const isScrollingTimeout = useRef<number | undefined>()
useLayoutEffect(() => {
if (isScrollingTimeout.current !== null) {
clearTimeout(isScrollingTimeout.current)
isScrollingTimeout.current = void 0
}
setIsScrolling(true)
isScrollingTimeout.current = window.setTimeout(() => {
// This is here to prevent premature bail outs while maintaining high resolution
// unsets. Without it there will always bee a lot of unnecessary DOM writes to style.
setIsScrolling(false)
isScrollingTimeout.current = void 0
}, 1000 / 6)
}, [scrollY])
// cleans up isScrollingTimeout on unmount
useEffect(() => {
const to = isScrollingTimeout.current
return (): any => to !== void 0 && window.clearTimeout(to)
}, emptyArr)
return {width, height, scrollY, isScrolling}
}
const defaultRect = {top: 0, width: 0}
const getContainerRect = memoizeOne(
(element, width, top) => [{width, top}, element],
(args, pargs) =>
args[1] === pargs[1] && args[2] === pargs[2] && args[0] === pargs[0]
)
interface ContainerRect {
top: number
width: number
}
export const useContainerRect = (
windowWidth: number,
windowHeight: number
): [ContainerRect, (element: HTMLElement) => void] => {
const [element, setElement] = useState<HTMLElement | null>(null)
const [containerRect, setContainerRect] = useState<ContainerRect>(defaultRect)
useLayoutEffect((): void | (() => void) => {
if (element !== null) {
const setRect = (): void => {
// @ts-ignore
const rect = element.getBoundingClientRect()
if (
rect.top !== containerRect.top ||
rect.width !== containerRect.width
) {
setContainerRect({top: rect.top, width: rect.width})
}
}
setRect()
// Got a better way to track changes to `top`?
// Resize/MutationObserver() won't cover it I don't think (top)
// Submit a PR
const qi = window.setInterval(setRect, 360)
return (): void => window.clearInterval(qi)
}
}, [windowWidth, windowHeight, containerRect, element])
return getContainerRect(
setElement,
containerRect.width || windowWidth,
containerRect.top
)
}
const getColumns = (
width = 0,
minimumWidth = 0,
gutter = 8,
columnCount?: number
): [number, number] => {
columnCount = columnCount || Math.floor(width / (minimumWidth + gutter)) || 1
const columnWidth = Math.floor(
(width - gutter * (columnCount - 1)) / columnCount
)
return [columnWidth, columnCount]
}
const getContainerStyle = memoizeOne(
(isScrolling: boolean, estimateTotalHeight: number) => ({
position: 'relative',
width: '100%',
maxWidth: '100%',
height: Math.ceil(estimateTotalHeight),
maxHeight: Math.ceil(estimateTotalHeight),
willChange: isScrolling ? 'contents, height' : void 0,
pointerEvents: isScrolling ? 'none' : void 0,
})
)
const assignUserStyle = memoizeOne(
(containerStyle, userStyle) => Object.assign({}, containerStyle, userStyle),
(args, pargs) => args[0] === pargs[0] && args[1] === pargs[1]
)
const assignUserItemStyle = trieMemoize(
[WeakMap, OneKeyMap],
(itemStyle, userStyle) => Object.assign({}, itemStyle, userStyle)
)
const defaultGetItemKey = (_: any[], i: number): number => i
// the below memoizations for for ensuring shallow equal is reliable for pure
// component children
const getCachedSize = memoizeOne(
width => ({
width,
zIndex: -1000,
visibility: 'hidden',
position: 'absolute',
writingMode: 'horizontal-tb',
}),
(args, pargs) => args[0] === pargs[0]
)
const getCachedItemStyle = trieMemoize(
[OneKeyMap, Map, Map],
(width, left, top) => ({
top,
left,
width,
writingMode: 'horizontal-tb',
position: 'absolute',
})
)
export interface MasonryPropsBase {
readonly columnWidth?: number
readonly columnGutter?: number
readonly columnCount?: number
readonly as?: any
readonly id?: string
readonly className?: string
readonly style?: {[property: string]: any}
readonly role?: string
readonly tabIndex?: number | string
readonly items: any[]
readonly itemAs?: any
readonly itemStyle?: {[property: string]: any}
readonly itemHeightEstimate?: number
readonly itemKey?: (data: any, index: number) => string | number
readonly overscanBy?: number
readonly onRender?: (
startIndex: number,
stopIndex: number | undefined,
items: any[]
) => void
readonly render: any
}
export interface FreeMasonryProps extends MasonryPropsBase {
readonly width: number // width of the container
readonly height: number // height of the window
readonly scrollTop: number
readonly isScrolling?: boolean
readonly containerRef?: (
element: HTMLElement
) => void | {current: HTMLElement | null | undefined}
}
const useForceUpdate = (): (() => void) => {
const setState = useState<number>(0)[1]
return useCallback(() => setState(current => ++current), [])
}
const elementsCache: WeakMap<Element, number> = new WeakMap()
interface ResizeObserverEntryBoxSize {
/**
* The length of the observed element's border box in the block dimension. For
* boxes with a horizontal
* [writing-mode](https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode),
* this is the vertical dimension, or height; if the writing-mode is vertical,
* this is the horizontal dimension, or width.
*/
blockSize: number
/**
* The length of the observed element's border box in the inline dimension.
* For boxes with a horizontal
* [writing-mode](https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode),
* this is the horizontal dimension, or width; if the writing-mode is
* vertical, this is the vertical dimension, or height.
*/
inlineSize: number
}
interface NativeResizeObserverEntry extends ResizeObserverEntry {
borderBoxSize: ResizeObserverEntryBoxSize
contentBoxSize: ResizeObserverEntryBoxSize
}
const getRefSetter = trieMemoize(
[OneKeyMap, OneKeyMap, OneKeyMap],
(resizeObserver, positionCache, itemPositioner) =>
trieMemoize([{}], index => (el: HTMLElement | null): void => {
if (el === null) return
resizeObserver.observe(el)
elementsCache.set(el, index)
if (itemPositioner.get(index) === void 0) {
const item = itemPositioner.set(index, el.offsetHeight)
positionCache.setPosition(index, item.left, item.top, item.height)
}
})
)
export const FreeMasonry: React.FC<FreeMasonryProps> = React.forwardRef(
(
{
items,
width,
columnWidth,
columnCount,
columnGutter,
onRender,
as = 'div',
id,
className,
style,
role = 'grid',
tabIndex = 0,
containerRef,
itemAs = 'div',
itemStyle,
itemHeightEstimate = 300,
itemKey = defaultGetItemKey,
overscanBy = 2,
scrollTop,
isScrolling,
height,
render,
},
ref
) => {
const didMount = useRef<string>('0')
const initPositioner = (): ItemPositioner => {
const gutter = columnGutter || 0
const [computedColumnWidth, computedColumnCount] = getColumns(
width,
columnWidth || 200,
gutter,
columnCount
)
return createItemPositioner(
computedColumnCount,
computedColumnWidth,
gutter
)
}
const stopIndex = useRef<number | undefined>()
const startIndex = useRef<number>(0)
const prevStartIndex = useRef<number | undefined>()
const prevStopIndex = useRef<number | undefined>()
const [itemPositioner, setItemPositioner] = useState<ItemPositioner>(
initPositioner
)
const [positionCache, setPositionCache] = useState<PositionCache>(
createPositionCache
)
const forceUpdate = useForceUpdate()
const resizeObserver = useMemo<ResizeObserver>(
() =>
new ResizeObserver(entries => {
const updates: number[] = []
for (let i = 0; i < entries.length; i++) {
const entry = entries[i]
// There are native resize observers that still don't have
// the borderBoxSize property. For those we fallback to the
// offset height of the target element.
const hasBorderBox =
(entry as NativeResizeObserverEntry).borderBoxSize !== void 0
const height = hasBorderBox
? (entry as NativeResizeObserverEntry).borderBoxSize.blockSize
: (entry.target as HTMLElement).offsetHeight
if (height > 0) {
const index = elementsCache.get(entry.target)
const position = itemPositioner.get(index)
if (
position !== void 0 &&
index !== void 0 &&
height !== position.height
) {
updates.push(index, height)
}
}
}
if (updates.length > 0) {
// Updates the size/positions of the cell with the resize
// observer updates
const updatedItems = itemPositioner.update(updates)
for (let i = 0; i < updatedItems.length; i++) {
const index = updatedItems[i++] as number
const item = updatedItems[i] as IUpdatedItem
positionCache.setPosition(index, item.left, item.top, item.height)
}
forceUpdate()
}
}),
[itemPositioner, positionCache]
)
// cleans up the resize observers when they change or the
// component unmounts
useEffect(() => resizeObserver.disconnect.bind(resizeObserver), [
resizeObserver,
])
// Allows parent components to clear the position cache imperatively
useImperativeHandle(
ref,
() => ({
clearPositions: (): void => {
setPositionCache(createPositionCache())
},
}),
emptyArr
)
// Updates the item positions any time a prop potentially affecting their
// size changes
useLayoutEffect(() => {
didMount.current = '1'
const cacheSize = positionCache.size
const nextPositionCache = createPositionCache()
const nextItemPositioner = initPositioner()
const stateUpdates = (): void => {
setPositionCache(nextPositionCache)
setItemPositioner(nextItemPositioner)
}
if (typeof unstable_batchedUpdates === 'function') {
unstable_batchedUpdates(stateUpdates)
} else {
stateUpdates()
}
for (let index = 0; index < cacheSize; index++) {
const pos = itemPositioner.get(index)
if (pos !== void 0) {
const item = nextItemPositioner.set(index, pos.height)
nextPositionCache.setPosition(index, item.left, item.top, pos.height)
}
}
}, [width, columnWidth, columnGutter, columnCount])
// Calls the onRender callback if the rendered indices changed
useLayoutEffect(() => {
if (typeof onRender === 'function') {
onRender(startIndex.current, stopIndex.current, items)
prevStartIndex.current = startIndex.current
prevStopIndex.current = stopIndex.current
}
}, [items, prevStartIndex.current, prevStopIndex.current])
const setItemRef = getRefSetter(
resizeObserver,
positionCache,
itemPositioner
)
const itemCount = items.length
const measuredCount = positionCache.size
const shortestColumnSize = positionCache.getShortestColumnSize()
const children: React.ReactElement[] = []
const itemRole = `${role}item`
overscanBy = height * overscanBy
positionCache.range(
Math.max(0, scrollTop - overscanBy),
scrollTop + overscanBy,
(index, left, top) => {
stopIndex.current = void 0
if (stopIndex.current === void 0) {
startIndex.current = index
stopIndex.current = index
} else {
startIndex.current = Math.min(startIndex.current, index)
stopIndex.current = Math.max(stopIndex.current, index)
}
const data = items[index],
key = itemKey(data, index),
observerStyle = getCachedItemStyle(
itemPositioner.columnWidth,
left,
top
)
children.push(
React.createElement(
itemAs,
{
key,
ref: setItemRef(index),
role: itemRole,
style:
typeof itemStyle === 'object' && itemStyle !== null
? assignUserItemStyle(observerStyle, itemStyle)
: observerStyle,
},
React.createElement(render, {
key,
index,
data,
width: itemPositioner.columnWidth,
})
)
)
}
)
if (
shortestColumnSize < scrollTop + overscanBy &&
measuredCount < itemCount
) {
const batchSize = Math.min(
itemCount - measuredCount,
Math.ceil(
((scrollTop + overscanBy - shortestColumnSize) / itemHeightEstimate) *
itemPositioner.columnCount
)
)
let index = measuredCount
for (; index < measuredCount + batchSize; index++) {
const data = items[index],
key = itemKey(data, index),
observerStyle = getCachedSize(itemPositioner.columnWidth)
children.push(
React.createElement(
itemAs,
{
key,
ref: setItemRef(index),
role: itemRole,
style:
typeof itemStyle === 'object' && itemStyle !== null
? assignUserItemStyle(observerStyle, itemStyle)
: observerStyle,
},
React.createElement(render, {
key,
index,
data,
width: itemPositioner.columnWidth,
})
)
)
}
}
// gets the container style object based upon the estimated height and whether or not
// the page is being scrolled
const containerStyle = getContainerStyle(
isScrolling,
positionCache.estimateTotalHeight(
itemCount,
itemPositioner.columnCount,
itemHeightEstimate
)
)
return React.createElement(as, {
ref: containerRef,
id,
key: didMount.current,
role,
className,
tabIndex,
style:
typeof style === 'object' && style !== null
? assignUserStyle(containerStyle, style)
: containerStyle,
children,
})
}
)
export interface MasonryProps extends MasonryPropsBase {
readonly initialWidth?: number
readonly initialHeight?: number
readonly windowScroller?: WindowScrollerOptions
}
export const Masonry: React.FC<MasonryProps> = React.memo(
React.forwardRef((props, ref) => {
const {width, height, scrollY, isScrolling} = useWindowScroller(
props.initialWidth || 1280,
props.initialHeight || 720,
props.windowScroller
),
[rect, containerRef] = useContainerRect(width, height)
return React.createElement(
FreeMasonry,
Object.assign(
{
width: rect.width,
height,
scrollTop: Math.max(0, scrollY - (rect.top + scrollY)),
isScrolling,
containerRef,
ref,
},
props
)
)
})
)
export interface ListProps extends MasonryProps {
columnGutter?: never
columnCount?: never
columnWidth?: never
rowGutter?: number
}
export const List: React.FC<ListProps> = props =>
React.createElement(
Masonry,
Object.assign({role: 'list'}, props, {
columnGutter: props.rowGutter,
columnCount: 1,
columnWidth: 1,
})
)
/**
* Returns all of the ranges within a larger range that contain unloaded rows.
*/
const scanForUnloadedRanges = (
isItemLoaded: (index: number, items: any[]) => boolean,
minimumBatchSize: number,
items: any[],
totalItems: number,
startIndex: number,
stopIndex: number
): number[] => {
const unloadedRanges: number[] = []
let rangeStartIndex, rangeStopIndex
for (let index = startIndex; index <= stopIndex; index++) {
const loaded = isItemLoaded(index, items)
if (!loaded) {
rangeStopIndex = index
if (rangeStartIndex === void 0) {
rangeStartIndex = index
}
} else if (rangeStopIndex !== void 0) {
unloadedRanges.push(rangeStartIndex, rangeStopIndex)
rangeStartIndex = rangeStopIndex = void 0
}
}
// If :rangeStopIndex is not null it means we haven't ran out of unloaded rows.
// Scan forward to try filling our :minimumBatchSize.
if (rangeStopIndex !== void 0) {
const potentialStopIndex = Math.min(
Math.max(rangeStopIndex, rangeStartIndex + minimumBatchSize - 1),
totalItems - 1
)
for (let index = rangeStopIndex + 1; index <= potentialStopIndex; index++) {
if (!isItemLoaded(index, items)) {
rangeStopIndex = index
} else {
break
}
}
unloadedRanges.push(rangeStartIndex, rangeStopIndex)
}
// Check to see if our first range ended prematurely.
// In this case we should scan backwards to try filling our :minimumBatchSize.
if (unloadedRanges.length) {
let firstUnloadedStart = unloadedRanges[0]
const firstUnloadedStop = unloadedRanges[1]
while (
firstUnloadedStop - firstUnloadedStart + 1 < minimumBatchSize &&
firstUnloadedStart > 0
) {
const index = firstUnloadedStart - 1
if (!isItemLoaded(index, items)) {
unloadedRanges[0] = firstUnloadedStart = index
} else {
break
}
}
}
return unloadedRanges
}
const defaultIsItemLoaded = (index: number, items: any[]): boolean =>
items[index] !== void 0
export interface InfiniteLoaderOptions {
isItemLoaded?: (index: number, items: any[]) => boolean
minimumBatchSize?: number
threshold?: number
totalItems?: number
}
export const useInfiniteLoader = (
/**
* Callback to be invoked when more rows must be loaded.
* It should implement the following signature: (startIndex, stopIndex, items): Promise
* The returned Promise should be resolved once row data has finished loading.
* It will be used to determine when to refresh the list with the newly-loaded data.
* This callback may be called multiple times in reaction to a single scroll event.
*/
loadMoreItems,
options: InfiniteLoaderOptions = emptyObj
): ((startIndex: number, stopIndex: number, items: any[]) => void) => {
const {
/**
* Function responsible for tracking the loaded state of each row.
* It should implement the following signature: (index): boolean
*/
isItemLoaded = defaultIsItemLoaded,
/**
* Minimum number of rows to be loaded at a time.
* This property can be used to batch requests to reduce HTTP requests.
*/
minimumBatchSize = 16,
/**
* Threshold at which to pre-fetch data.
* A threshold X means that data will start loading when a user scrolls within X rows.
* This value defaults to 15.
*/
threshold = 16,
/**
* The total number of items you'll need to eventually load (if known). This can
* be arbitrarily high if not known.
*/
totalItems = 9e9,
} = options
return useCallback(
(startIndex, stopIndex, items) => {
const unloadedRanges = scanForUnloadedRanges(
isItemLoaded,
minimumBatchSize,
items,
totalItems,
Math.max(0, startIndex - threshold),
Math.min(totalItems - 1, stopIndex + threshold)
)
// the user is responsible for memoizing their loadMoreItems() function
// because we don't want to make assumptions about how they want to deal
// with `items`
for (let i = 0; i < unloadedRanges.length - 1; ++i)
loadMoreItems(unloadedRanges[i], unloadedRanges[++i], items)
},
[totalItems, minimumBatchSize, threshold, isItemLoaded]
)
}
if (typeof process !== 'undefined' && process.env.NODE_ENV !== 'production') {
Masonry.displayName = 'Masonry'
FreeMasonry.displayName = 'FreeMasonry'
List.displayName = 'List'
}