-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathList.tsx
686 lines (587 loc) · 19.7 KB
/
List.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
import classNames from 'classnames';
import type { ResizeObserverProps } from 'rc-resize-observer';
import ResizeObserver from 'rc-resize-observer';
import { useEvent } from 'rc-util';
import useLayoutEffect from 'rc-util/lib/hooks/useLayoutEffect';
import * as React from 'react';
import { useRef, useState } from 'react';
import { flushSync } from 'react-dom';
import type { InnerProps } from './Filler';
import Filler from './Filler';
import useChildren from './hooks/useChildren';
import useDiffItem from './hooks/useDiffItem';
import useFrameWheel from './hooks/useFrameWheel';
import { useGetSize } from './hooks/useGetSize';
import useHeights from './hooks/useHeights';
import useMobileTouchMove from './hooks/useMobileTouchMove';
import useOriginScroll from './hooks/useOriginScroll';
import useScrollDrag from './hooks/useScrollDrag';
import type { ScrollPos, ScrollTarget } from './hooks/useScrollTo';
import useScrollTo from './hooks/useScrollTo';
import type { ExtraRenderInfo, GetKey, RenderFunc, SharedConfig } from './interface';
import type { ScrollBarDirectionType, ScrollBarRef } from './ScrollBar';
import ScrollBar from './ScrollBar';
import { getSpinSize } from './utils/scrollbarUtil';
import { debounce } from './utils/debounce';
const EMPTY_DATA = [];
const ScrollStyle: React.CSSProperties = {
overflowY: 'auto',
overflowAnchor: 'none',
};
export interface ScrollInfo {
x: number;
y: number;
}
export type ScrollConfig = ScrollTarget | ScrollPos;
export type ScrollTo = (arg: number | ScrollConfig) => void;
export type ListRef = {
nativeElement: HTMLDivElement;
scrollTo: ScrollTo;
getScrollInfo: () => ScrollInfo;
};
export interface ListProps<T> extends Omit<React.HTMLAttributes<any>, 'children'> {
prefixCls?: string;
children: RenderFunc<T>;
data: T[];
height?: number;
itemHeight?: number;
/** If not match virtual scroll condition, Set List still use height of container. */
fullHeight?: boolean;
itemKey: React.Key | ((item: T) => React.Key);
component?: string | React.FC<any> | React.ComponentClass<any>;
/** Set `false` will always use real scroll instead of virtual one */
virtual?: boolean;
direction?: ScrollBarDirectionType;
/**
* By default `scrollWidth` is same as container.
* When set this, it will show the horizontal scrollbar and
* `scrollWidth` will be used as the real width instead of container width.
* When set, `virtual` will always be enabled.
*/
scrollWidth?: number;
styles?: {
horizontalScrollBar?: React.CSSProperties;
horizontalScrollBarThumb?: React.CSSProperties;
verticalScrollBar?: React.CSSProperties;
verticalScrollBarThumb?: React.CSSProperties;
};
onScroll?: React.UIEventHandler<HTMLElement>;
/**
* Given the virtual offset value.
* It's the logic offset from start position.
*/
onVirtualScroll?: (info: ScrollInfo) => void;
/** Trigger when render list item changed */
onVisibleChange?: (visibleList: T[], fullList: T[]) => void;
/** Inject to inner container props. Only use when you need pass aria related data */
innerProps?: InnerProps;
/** Render extra content into Filler */
extraRender?: (info: ExtraRenderInfo) => React.ReactNode;
}
export function RawList<T>(props: ListProps<T>, ref: React.Ref<ListRef>) {
const {
prefixCls = 'rc-virtual-list',
className,
height,
itemHeight,
fullHeight = true,
style,
data,
children,
itemKey,
virtual,
direction,
scrollWidth,
component: Component = 'div',
onScroll,
onVirtualScroll,
onVisibleChange,
innerProps,
extraRender,
styles,
...restProps
} = props;
// =============================== Item Key ===============================
const getKey = React.useCallback<GetKey<T>>(
(item: T) => {
if (typeof itemKey === 'function') {
return itemKey(item);
}
return item?.[itemKey as string];
},
[itemKey],
);
// ================================ Height ================================
const [setInstanceRef, collectHeight, heights, heightUpdatedMark] = useHeights(
getKey,
null,
null,
);
// ================================= MISC =================================
const useVirtual = !!(virtual !== false && height && itemHeight);
const containerHeight = React.useMemo(
() => Object.values(heights.maps).reduce((total, curr) => total + curr, 0),
[heights.id, heights.maps],
);
const inVirtual =
useVirtual &&
data &&
(Math.max(itemHeight * data.length, containerHeight) > height || !!scrollWidth);
const isRTL = direction === 'rtl';
const mergedClassName = classNames(prefixCls, { [`${prefixCls}-rtl`]: isRTL }, className);
const mergedData = data || EMPTY_DATA;
const componentRef = useRef<HTMLDivElement>();
const fillerInnerRef = useRef<HTMLDivElement>();
const containerRef = useRef<HTMLDivElement>();
// =============================== Item Key ===============================
const [offsetTop, setOffsetTop] = useState(0);
const [offsetLeft, setOffsetLeft] = useState(0);
const [scrollMoving, setScrollMoving] = useState(false);
const onScrollbarStartMove = () => {
setScrollMoving(true);
};
const onScrollbarStopMove = () => {
setScrollMoving(false);
};
const sharedConfig: SharedConfig<T> = {
getKey,
};
// ================================ Scroll ================================
function syncScrollTop(newTop: number | ((prev: number) => number)) {
setOffsetTop((origin) => {
let value: number;
if (typeof newTop === 'function') {
value = newTop(origin);
} else {
value = newTop;
}
const alignedTop = keepInRange(value);
componentRef.current.scrollTop = alignedTop;
return alignedTop;
});
}
// ================================ Legacy ================================
// Put ref here since the range is generate by follow
const rangeRef = useRef({ start: 0, end: mergedData.length });
const diffItemRef = useRef<T>();
const [diffItem] = useDiffItem(mergedData, getKey);
diffItemRef.current = diffItem;
// ========================== Visible Calculation =========================
const {
scrollHeight,
start,
end,
offset: fillerOffset,
} = React.useMemo(() => {
if (!useVirtual) {
return {
scrollHeight: undefined,
start: 0,
end: mergedData.length - 1,
offset: undefined,
};
}
// Always use virtual scroll bar in avoid shaking
if (!inVirtual) {
return {
scrollHeight: fillerInnerRef.current?.offsetHeight || 0,
start: 0,
end: mergedData.length - 1,
offset: undefined,
};
}
let itemTop = 0;
let startIndex: number;
let startOffset: number;
let endIndex: number;
const dataLen = mergedData.length;
for (let i = 0; i < dataLen; i += 1) {
const item = mergedData[i];
const key = getKey(item);
const cacheHeight = heights.get(key);
const currentItemBottom = itemTop + (cacheHeight === undefined ? itemHeight : cacheHeight);
// Check item top in the range
if (currentItemBottom >= offsetTop && startIndex === undefined) {
startIndex = i;
startOffset = itemTop;
}
// Check item bottom in the range. We will render additional one item for motion usage
if (currentItemBottom > offsetTop + height && endIndex === undefined) {
endIndex = i;
}
itemTop = currentItemBottom;
}
// When scrollTop at the end but data cut to small count will reach this
if (startIndex === undefined) {
startIndex = 0;
startOffset = 0;
endIndex = Math.ceil(height / itemHeight);
}
if (endIndex === undefined) {
endIndex = mergedData.length - 1;
}
// Give cache to improve scroll experience
endIndex = Math.min(endIndex + 1, mergedData.length - 1);
return {
scrollHeight: itemTop,
start: startIndex,
end: endIndex,
offset: startOffset,
};
}, [inVirtual, useVirtual, offsetTop, mergedData, heightUpdatedMark, height]);
rangeRef.current.start = start;
rangeRef.current.end = end;
const isScrollingRef = useRef(false);
// When scroll up, first visible item get real height may not same as `itemHeight`,
// Which will make scroll jump.
// Let's sync scroll top to avoid jump
React.useLayoutEffect(() => {
// When the `scrollHeight` change is not caused by scrolling,
// end the function execution avoiding table jitter caused by changes in the first row
if (!isScrollingRef.current) return;
const changedRecord = heights.getRecord();
if (changedRecord.size === 1) {
const recordKey = Array.from(changedRecord)[0];
const startIndexKey = getKey(mergedData[start]);
if (startIndexKey === recordKey) {
const realStartHeight = heights.get(recordKey);
const diffHeight = realStartHeight - itemHeight;
syncScrollTop((ori) => {
return ori + diffHeight;
});
}
}
heights.resetRecord();
}, [scrollHeight]);
// ================================= Size =================================
const [size, setSize] = React.useState({ width: 0, height });
const onHolderResize: ResizeObserverProps['onResize'] = (sizeInfo) => {
setSize({
width: sizeInfo.offsetWidth,
height: sizeInfo.offsetHeight,
});
};
// Hack on scrollbar to enable flash call
const verticalScrollBarRef = useRef<ScrollBarRef>();
const horizontalScrollBarRef = useRef<ScrollBarRef>();
const horizontalScrollBarSpinSize = React.useMemo(
() => getSpinSize(size.width, scrollWidth),
[size.width, scrollWidth],
);
const verticalScrollBarSpinSize = React.useMemo(
() => getSpinSize(size.height, scrollHeight),
[size.height, scrollHeight],
);
// =============================== In Range ===============================
const maxScrollHeight = scrollHeight - height;
const maxScrollHeightRef = useRef(maxScrollHeight);
maxScrollHeightRef.current = maxScrollHeight;
function keepInRange(newScrollTop: number) {
let newTop = newScrollTop;
if (!Number.isNaN(maxScrollHeightRef.current)) {
newTop = Math.min(newTop, maxScrollHeightRef.current);
}
newTop = Math.max(newTop, 0);
return newTop;
}
const isScrollAtTop = offsetTop <= 0;
const isScrollAtBottom = offsetTop >= maxScrollHeight;
const isScrollAtLeft = offsetLeft <= 0;
const isScrollAtRight = offsetLeft >= scrollWidth;
const originScroll = useOriginScroll(
isScrollAtTop,
isScrollAtBottom,
isScrollAtLeft,
isScrollAtRight,
);
// ================================ Scroll ================================
const getVirtualScrollInfo = () => ({
x: isRTL ? -offsetLeft : offsetLeft,
y: offsetTop,
});
const lastVirtualScrollInfoRef = useRef(getVirtualScrollInfo());
const triggerScroll = useEvent((params?: { x?: number; y?: number }) => {
if (onVirtualScroll) {
const nextInfo = { ...getVirtualScrollInfo(), ...params };
// Trigger when offset changed
if (
lastVirtualScrollInfoRef.current.x !== nextInfo.x ||
lastVirtualScrollInfoRef.current.y !== nextInfo.y
) {
onVirtualScroll(nextInfo);
lastVirtualScrollInfoRef.current = nextInfo;
}
}
});
function onScrollBar(newScrollOffset: number, horizontal?: boolean) {
const newOffset = newScrollOffset;
if (horizontal) {
flushSync(() => {
setOffsetLeft(newOffset);
});
triggerScroll();
} else {
syncScrollTop(newOffset);
}
}
const toggleScrollStatus = React.useCallback(debounce(() => {
isScrollingRef.current = false;
}, 100), []);
// When data size reduce. It may trigger native scroll event back to fit scroll position
function onFallbackScroll(e: React.UIEvent<HTMLDivElement>) {
const { scrollTop: newScrollTop } = e.currentTarget;
if (newScrollTop !== offsetTop) {
syncScrollTop(newScrollTop);
}
// Trigger origin onScroll
onScroll?.(e);
triggerScroll();
// Set the scroll status to `true`
isScrollingRef.current = true;
// Set the scroll status to `false` after scrolling ends
toggleScrollStatus();
}
const keepInHorizontalRange = (nextOffsetLeft: number) => {
let tmpOffsetLeft = nextOffsetLeft;
const max = !!scrollWidth ? scrollWidth - size.width : 0;
tmpOffsetLeft = Math.max(tmpOffsetLeft, 0);
tmpOffsetLeft = Math.min(tmpOffsetLeft, max);
return tmpOffsetLeft;
};
const onWheelDelta: Parameters<typeof useFrameWheel>[6] = useEvent((offsetXY, fromHorizontal) => {
if (fromHorizontal) {
flushSync(() => {
setOffsetLeft((left) => {
const nextOffsetLeft = left + (isRTL ? -offsetXY : offsetXY);
return keepInHorizontalRange(nextOffsetLeft);
});
});
triggerScroll();
} else {
syncScrollTop((top) => {
const newTop = top + offsetXY;
return newTop;
});
}
});
// Since this added in global,should use ref to keep update
const [onRawWheel, onFireFoxScroll] = useFrameWheel(
useVirtual,
isScrollAtTop,
isScrollAtBottom,
isScrollAtLeft,
isScrollAtRight,
!!scrollWidth,
onWheelDelta,
);
// Mobile touch move
useMobileTouchMove(useVirtual, componentRef, (isHorizontal, delta, smoothOffset, e) => {
const event = e as TouchEvent & {
_virtualHandled?: boolean;
};
if (originScroll(isHorizontal, delta, smoothOffset)) {
return false;
}
// Fix nest List trigger TouchMove event
if (!event || !event._virtualHandled) {
if (event) {
event._virtualHandled = true;
}
onRawWheel({
preventDefault() {},
deltaX: isHorizontal ? delta : 0,
deltaY: isHorizontal ? 0 : delta,
} as WheelEvent);
return true;
}
return false;
});
// MouseDown drag for scroll
useScrollDrag(inVirtual, componentRef, (offset) => {
syncScrollTop((top) => top + offset);
});
useLayoutEffect(() => {
// Firefox only
function onMozMousePixelScroll(e: WheelEvent) {
// scrolling at top/bottom limit
const scrollingUpAtTop = isScrollAtTop && e.detail < 0;
const scrollingDownAtBottom = isScrollAtBottom && e.detail > 0;
if (useVirtual && !scrollingUpAtTop && !scrollingDownAtBottom) {
e.preventDefault();
}
}
const componentEle = componentRef.current;
componentEle.addEventListener('wheel', onRawWheel, { passive: false });
componentEle.addEventListener('DOMMouseScroll', onFireFoxScroll as any, { passive: true });
componentEle.addEventListener('MozMousePixelScroll', onMozMousePixelScroll, { passive: false });
return () => {
componentEle.removeEventListener('wheel', onRawWheel);
componentEle.removeEventListener('DOMMouseScroll', onFireFoxScroll as any);
componentEle.removeEventListener('MozMousePixelScroll', onMozMousePixelScroll as any);
};
}, [useVirtual, isScrollAtTop, isScrollAtBottom]);
// Sync scroll left
useLayoutEffect(() => {
if (scrollWidth) {
const newOffsetLeft = keepInHorizontalRange(offsetLeft);
setOffsetLeft(newOffsetLeft);
triggerScroll({ x: newOffsetLeft });
}
}, [size.width, scrollWidth]);
// ================================= Ref ==================================
const delayHideScrollBar = () => {
verticalScrollBarRef.current?.delayHidden();
horizontalScrollBarRef.current?.delayHidden();
};
const scrollTo = useScrollTo<T>(
componentRef,
mergedData,
heights,
itemHeight,
getKey,
() => collectHeight(true),
syncScrollTop,
delayHideScrollBar,
);
React.useImperativeHandle(ref, () => ({
nativeElement: containerRef.current,
getScrollInfo: getVirtualScrollInfo,
scrollTo: (config) => {
function isPosScroll(arg: any): arg is ScrollPos {
return arg && typeof arg === 'object' && ('left' in arg || 'top' in arg);
}
if (isPosScroll(config)) {
// Scroll X
if (config.left !== undefined) {
setOffsetLeft(keepInHorizontalRange(config.left));
}
// Scroll Y
scrollTo(config.top);
} else {
scrollTo(config);
}
},
}));
// ================================ Effect ================================
/** We need told outside that some list not rendered */
useLayoutEffect(() => {
if (onVisibleChange) {
const renderList = mergedData.slice(start, end + 1);
onVisibleChange(renderList, mergedData);
}
}, [start, end, mergedData]);
// ================================ Extra =================================
const getSize = useGetSize(mergedData, getKey, heights, itemHeight);
const extraContent = extraRender?.({
start,
end,
virtual: inVirtual,
offsetX: offsetLeft,
offsetY: fillerOffset,
rtl: isRTL,
getSize,
});
// ================================ Render ================================
const listChildren = useChildren(
mergedData,
start,
end,
scrollWidth,
offsetLeft,
setInstanceRef,
children,
sharedConfig,
);
let componentStyle: React.CSSProperties = null;
if (height) {
componentStyle = { [fullHeight ? 'height' : 'maxHeight']: height, ...ScrollStyle };
if (useVirtual) {
componentStyle.overflowY = 'hidden';
if (scrollWidth) {
componentStyle.overflowX = 'hidden';
}
if (scrollMoving) {
componentStyle.pointerEvents = 'none';
}
}
}
const containerProps: React.HTMLAttributes<HTMLDivElement> = {};
if (isRTL) {
containerProps.dir = 'rtl';
}
return (
<div
ref={containerRef}
style={{
...style,
position: 'relative',
}}
className={mergedClassName}
{...containerProps}
{...restProps}
>
<ResizeObserver onResize={onHolderResize}>
<Component
className={`${prefixCls}-holder`}
style={componentStyle}
ref={componentRef}
onScroll={onFallbackScroll}
onMouseEnter={delayHideScrollBar}
>
<Filler
prefixCls={prefixCls}
height={scrollHeight}
offsetX={offsetLeft}
offsetY={fillerOffset}
scrollWidth={scrollWidth}
onInnerResize={collectHeight}
ref={fillerInnerRef}
innerProps={innerProps}
rtl={isRTL}
extra={extraContent}
>
{listChildren}
</Filler>
</Component>
</ResizeObserver>
{inVirtual && scrollHeight > height && (
<ScrollBar
ref={verticalScrollBarRef}
prefixCls={prefixCls}
scrollOffset={offsetTop}
scrollRange={scrollHeight}
rtl={isRTL}
onScroll={onScrollBar}
onStartMove={onScrollbarStartMove}
onStopMove={onScrollbarStopMove}
spinSize={verticalScrollBarSpinSize}
containerSize={size.height}
style={styles?.verticalScrollBar}
thumbStyle={styles?.verticalScrollBarThumb}
/>
)}
{inVirtual && scrollWidth > size.width && (
<ScrollBar
ref={horizontalScrollBarRef}
prefixCls={prefixCls}
scrollOffset={offsetLeft}
scrollRange={scrollWidth}
rtl={isRTL}
onScroll={onScrollBar}
onStartMove={onScrollbarStartMove}
onStopMove={onScrollbarStopMove}
spinSize={horizontalScrollBarSpinSize}
containerSize={size.width}
horizontal
style={styles?.horizontalScrollBar}
thumbStyle={styles?.horizontalScrollBarThumb}
/>
)}
</div>
);
}
const List = React.forwardRef<ListRef, ListProps<any>>(RawList);
List.displayName = 'List';
export default List as <Item = any>(
props: ListProps<Item> & { ref?: React.Ref<ListRef> },
) => React.ReactElement;