-
Notifications
You must be signed in to change notification settings - Fork 333
Expand file tree
/
Copy pathindex.tsx
More file actions
443 lines (396 loc) · 15 KB
/
index.tsx
File metadata and controls
443 lines (396 loc) · 15 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
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
import {
useState,
useEffect,
useRef,
useCallback,
ReactNode,
CSSProperties,
} from 'react';
import { buildRootMargin } from './utils/buildRootMargin';
export { useInfiniteScroll } from './useInfiniteScroll';
export type {
UseInfiniteScrollOptions,
UseInfiniteScrollResult,
} from './useInfiniteScroll';
type Fn = () => any;
export interface Props {
/**
* Total number of items currently rendered. Unlocks the next load when it
* changes. Always pass the length of your full accumulated list, not just
* the most recently fetched page.
*/
dataLength: number;
/**
* Called when the user scrolls near the end of the list. Must append new
* items to your list state (not replace them). The component calls this at
* most once per data load, guarded by an IntersectionObserver sentinel.
*/
next: Fn;
/**
* Whether more data exists to load. When false, the observer stops and
* `endMessage` is shown instead of `loader`.
*/
hasMore: boolean;
/**
* The full accumulated list of items to render. Pass every item loaded so
* far — the component is not paginated internally.
*/
children: ReactNode;
/**
* Element shown while the next page is being fetched (while `hasMore` is
* true and `next` has been triggered).
*/
loader: ReactNode;
/**
* How close to the end of the list before `next` fires.
* - Number 0–1: fraction of container height, e.g. `0.8` triggers at 80%
* scrolled (default).
* - Pixel string: absolute offset, e.g. `"200px"` triggers 200 px before
* the end.
* @default 0.8
*/
scrollThreshold?: number | string;
/** Shown below the list once `hasMore` is false. */
endMessage?: ReactNode;
/** Inline styles applied to the inner scroll container. */
style?: CSSProperties;
/**
* Fixed height for the scroll container. When provided, a scrollable box
* of this height is rendered. Omit to scroll the window (document body).
*/
height?: number | string;
/**
* A scrollable parent element that already provides overflow scrollbars.
* Accepts a DOM element reference or the element's string `id`. Pass this
* instead of `height` when the scroll container is owned by the parent.
*
* @example
* // string id
* scrollableTarget="scrollableDiv"
*
* @example
* // ref value
* const ref = useRef(null);
* <div ref={ref}><InfiniteScroll scrollableTarget={ref.current} /></div>
*/
scrollableTarget?: HTMLElement | string | null;
/**
* Set to `true` when `children` is not a plain array (e.g. a single node
* or a fragment). Prevents the component from treating a length of 0 as
* "no items loaded".
*/
hasChildren?: boolean;
/**
* Reverse the scroll direction: the sentinel is placed at the top of the
* list and `next` loads older content upward. Use with
* `flexDirection: 'column-reverse'` on the scroll container for chat or
* messaging UIs.
* @default false
*/
inverse?: boolean;
/**
* Enable pull-down-to-refresh on touch and mouse. Requires
* `refreshFunction` to be provided.
* @default false
*/
pullDownToRefresh?: boolean;
/** Content shown while the user is pulling down. @default <h3>Pull down to refresh</h3> */
pullDownToRefreshContent?: ReactNode;
/** Content shown when the pull threshold is breached. @default <h3>Release to refresh</h3> */
releaseToRefreshContent?: ReactNode;
/**
* Minimum pixels the user must pull before `refreshFunction` fires.
* @default 100
*/
pullDownToRefreshThreshold?: number;
/**
* Called when the pull-to-refresh threshold is breached. Should reload or
* reset the list to fresh data.
*/
refreshFunction?: Fn;
/** Called on every scroll event of the scroll container. */
onScroll?: (e: UIEvent) => any;
/** Scroll Y position (in pixels) to restore when the component mounts. */
initialScrollY?: number;
/** CSS class name added to the inner scroll container element. */
className?: string;
}
export default function InfiniteScroll({
next,
hasMore,
children,
loader,
scrollThreshold = 0.8,
endMessage,
style,
height,
scrollableTarget,
hasChildren,
inverse = false,
pullDownToRefresh = false,
pullDownToRefreshContent,
releaseToRefreshContent,
pullDownToRefreshThreshold = 100,
refreshFunction,
onScroll,
dataLength,
initialScrollY,
className = '',
}: Props) {
const [showLoader, setShowLoader] = useState(false);
const [pullToRefreshThresholdBreached, setPullToRefreshThresholdBreached] =
useState(false);
// State drives the JSX re-render when height is measured; ref is read by handlers
const [maxPullDownDistance, setMaxPullDownDistance] = useState(0);
const infScrollRef = useRef<HTMLDivElement>(null);
const sentinelRef = useRef<HTMLDivElement>(null);
const pullDownRef = useRef<HTMLDivElement>(null);
// --- Stable callback refs ---
// Assigned synchronously every render so effects and event handlers always call
// the latest version without adding the functions to any effect dependency array.
// This prevents the IO observer and PTR listeners from being recreated every time
// consumers pass inline functions (the most common real-world usage).
const nextRef = useRef(next);
nextRef.current = next;
const refreshFunctionRef = useRef(refreshFunction);
refreshFunctionRef.current = refreshFunction;
// Ref for pullDownToRefreshThreshold so onMove always reads the current value
// without needing it in the PTR effect deps
const pullThresholdRef = useRef(pullDownToRefreshThreshold);
pullThresholdRef.current = pullDownToRefreshThreshold;
// --- Mutable refs — never trigger re-renders ---
const actionTriggeredRef = useRef(false);
const draggingRef = useRef(false);
const startYRef = useRef(0);
const currentYRef = useRef(0);
const maxPullDownDistanceRef = useRef(0); // kept in sync with maxPullDownDistance state
// Resolve the custom scrollable element; stable as long as scrollableTarget doesn't change
const getScrollableNode = useCallback((): HTMLElement | null => {
if (scrollableTarget instanceof HTMLElement) return scrollableTarget;
if (typeof scrollableTarget === 'string') {
return document.getElementById(scrollableTarget);
}
if (scrollableTarget === null) {
console.warn(
`You are trying to pass scrollableTarget but it is null. This might
happen because the element may not have been added to DOM yet.
See https://github.com/ankeetmaini/react-infinite-scroll-component/issues/59 for more info.
`
);
}
return null;
}, [scrollableTarget]);
// Effect 1 — one-time validation and initialScrollY
useEffect(() => {
if (typeof dataLength === 'undefined') {
throw new Error(
`mandatory prop "dataLength" is missing. The prop is needed` +
` when loading more content. Check README.md for usage`
);
}
if (pullDownToRefresh && typeof refreshFunction !== 'function') {
throw new Error(
`Mandatory prop "refreshFunction" missing.
Pull Down To Refresh functionality will not work
as expected. Check README.md for usage'`
);
}
if (typeof initialScrollY === 'number') {
const el = height ? infScrollRef.current : getScrollableNode();
if (el && el.scrollHeight > initialScrollY) {
el.scrollTo(0, initialScrollY);
}
}
}, []);
// Effect 2a — reset the load guard when new data arrives.
// Deliberately decoupled from the IO observer (Effect 2b) so the observer
// is NOT recreated on every data load — it lives for the component's full
// mount lifetime and only reconnects when structural config changes.
useEffect(() => {
actionTriggeredRef.current = false;
setShowLoader(false);
}, [dataLength]);
// Effect 2b — IntersectionObserver lifecycle.
// dataLength is intentionally absent from deps: the guard reset above handles
// the per-load reset. The observer only reconnects when the root, margin, or
// direction changes — typically never after initial mount.
useEffect(() => {
if (!hasMore) return;
if (typeof IntersectionObserver === 'undefined') return;
const sentinel = sentinelRef.current;
if (!sentinel) return;
const root: Element | null = height
? infScrollRef.current
: getScrollableNode();
const observer = new IntersectionObserver(
([entry]) => {
if (!entry.isIntersecting || actionTriggeredRef.current) return;
actionTriggeredRef.current = true;
setShowLoader(true);
nextRef.current(); // stable ref — safe to call without listing next in deps
},
{
root,
rootMargin: buildRootMargin(scrollThreshold, inverse),
threshold: 0,
}
);
observer.observe(sentinel);
return () => observer.disconnect();
}, [hasMore, scrollThreshold, inverse, height, getScrollableNode]);
// Effect 3 — onScroll passthrough (only when prop is provided)
useEffect(() => {
if (!onScroll) return;
const scrollEl: HTMLElement | Window | null =
(height ? infScrollRef.current : getScrollableNode()) ??
(typeof window !== 'undefined' ? window : null);
if (!scrollEl) return;
const handler = (e: Event) => {
setTimeout(() => onScroll(e as UIEvent), 0);
};
scrollEl.addEventListener('scroll', handler as EventListener);
return () =>
scrollEl.removeEventListener('scroll', handler as EventListener);
}, [onScroll, height, getScrollableNode]);
// Effect 4 — Pull-to-refresh event listeners.
// refreshFunction and pullDownToRefreshThreshold are intentionally absent from
// deps — they are read via refs so listener re-registration is not needed when
// consumers pass new function references or change the threshold at runtime.
useEffect(() => {
if (!pullDownToRefresh) return;
const scrollEl: HTMLElement | Window | null =
(height ? infScrollRef.current : getScrollableNode()) ??
(typeof window !== 'undefined' ? window : null);
if (!scrollEl) return;
// Measure pull-down indicator height after mount
if (pullDownRef.current?.firstChild) {
const dist = (
pullDownRef.current.firstChild as HTMLElement
).getBoundingClientRect().height;
maxPullDownDistanceRef.current = dist;
setMaxPullDownDistance(dist);
}
const onStart = (evt: Event) => {
// Only allow pull-to-refresh when the scroll container is at the very top.
// Replaces the old lastScrollTop ref which was never updated after removing
// the scroll event listener, making the original guard permanently a no-op.
const scrollTop =
scrollEl instanceof HTMLElement
? scrollEl.scrollTop
: document.documentElement.scrollTop;
if (scrollTop > 0) return;
draggingRef.current = true;
if (evt instanceof MouseEvent) {
startYRef.current = evt.pageY;
} else if (evt instanceof TouchEvent) {
startYRef.current = evt.touches[0].pageY;
}
currentYRef.current = startYRef.current;
if (infScrollRef.current) {
infScrollRef.current.style.willChange = 'transform';
infScrollRef.current.style.transition =
'transform 0.2s cubic-bezier(0,0,0.31,1)';
}
};
const onMove = (evt: Event) => {
if (!draggingRef.current) return;
if (evt instanceof MouseEvent) {
currentYRef.current = evt.pageY;
} else if (evt instanceof TouchEvent) {
currentYRef.current = evt.touches[0].pageY;
}
// user is scrolling up — ignore
if (currentYRef.current < startYRef.current) return;
const delta = currentYRef.current - startYRef.current;
// Read via ref — no stale closure risk, no effect re-registration needed
if (delta >= pullThresholdRef.current) {
setPullToRefreshThresholdBreached(true);
}
// limit drag to 1.5x maxPullDownDistance
if (delta > maxPullDownDistanceRef.current * 1.5) return;
if (infScrollRef.current) {
infScrollRef.current.style.overflow = 'visible';
infScrollRef.current.style.transform = `translate3d(0px, ${delta}px, 0px)`;
}
};
const onEnd = () => {
startYRef.current = 0;
currentYRef.current = 0;
draggingRef.current = false;
setPullToRefreshThresholdBreached((breached) => {
if (breached) {
// Read via ref — refreshFunction identity changes don't re-register listeners
refreshFunctionRef.current?.();
}
return false;
});
requestAnimationFrame(() => {
if (infScrollRef.current) {
infScrollRef.current.style.overflow = 'auto';
infScrollRef.current.style.transform = 'none';
infScrollRef.current.style.willChange = 'unset';
}
});
};
scrollEl.addEventListener('touchstart', onStart as EventListener);
scrollEl.addEventListener('touchmove', onMove as EventListener);
scrollEl.addEventListener('touchend', onEnd as EventListener);
scrollEl.addEventListener('mousedown', onStart as EventListener);
scrollEl.addEventListener('mousemove', onMove as EventListener);
scrollEl.addEventListener('mouseup', onEnd as EventListener);
return () => {
scrollEl.removeEventListener('touchstart', onStart as EventListener);
scrollEl.removeEventListener('touchmove', onMove as EventListener);
scrollEl.removeEventListener('touchend', onEnd as EventListener);
scrollEl.removeEventListener('mousedown', onStart as EventListener);
scrollEl.removeEventListener('mousemove', onMove as EventListener);
scrollEl.removeEventListener('mouseup', onEnd as EventListener);
};
}, [pullDownToRefresh, height, getScrollableNode]);
const containerStyle: CSSProperties = {
height: height ?? 'auto',
overflow: 'auto',
WebkitOverflowScrolling: 'touch',
...style,
};
const hasChildrenResolved =
hasChildren || !!(children && children instanceof Array && children.length);
const outerDivStyle: CSSProperties =
pullDownToRefresh && height ? { overflow: 'auto' } : {};
const sentinel = hasMore ? (
<div ref={sentinelRef} style={{ height: 1 }} />
) : null;
return (
<div style={outerDivStyle} className="infinite-scroll-component__outerdiv">
<div
className={['infinite-scroll-component', className]
.filter(Boolean)
.join(' ')}
ref={infScrollRef}
style={containerStyle}
>
{pullDownToRefresh && (
<div style={{ position: 'relative' }} ref={pullDownRef}>
<div
style={{
position: 'absolute',
left: 0,
right: 0,
top: -1 * maxPullDownDistance,
}}
>
{pullToRefreshThresholdBreached
? releaseToRefreshContent
: pullDownToRefreshContent}
</div>
</div>
)}
{children}
{!showLoader && !hasChildrenResolved && hasMore && loader}
{showLoader && hasMore && loader}
{sentinel}
{!hasMore && endMessage}
</div>
</div>
);
}