-
Notifications
You must be signed in to change notification settings - Fork 40
/
pull-to-refresh.tsx
250 lines (227 loc) · 8.24 KB
/
pull-to-refresh.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
import React, { useRef, useEffect } from 'react';
import { isTreeScrollable } from '../isScrollable';
import RefreshingContent from './refreshing-content';
import PullingContent from './pulling-content';
import { DIRECTION } from '../types';
import '../styles/main.scss';
interface PullToRefreshProps {
isPullable?: boolean;
canFetchMore?: boolean;
onRefresh: () => Promise<any>;
onFetchMore?: () => Promise<any>;
refreshingContent?: JSX.Element | string;
pullingContent?: JSX.Element | string;
children: JSX.Element;
pullDownThreshold?: number;
fetchMoreThreshold?: number;
maxPullDownDistance?: number;
resistance?: number;
backgroundColor?: string;
className?: string;
}
const PullToRefresh: React.FC<PullToRefreshProps> = ({
isPullable = true,
canFetchMore = false,
onRefresh,
onFetchMore,
refreshingContent = <RefreshingContent />,
pullingContent = <PullingContent />,
children,
pullDownThreshold = 67,
fetchMoreThreshold = 100,
maxPullDownDistance = 95, // max distance to scroll to trigger refresh
resistance = 1,
backgroundColor,
className = '',
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const childrenRef = useRef<HTMLDivElement>(null);
const pullDownRef = useRef<HTMLDivElement>(null);
const fetchMoreRef = useRef<HTMLDivElement>(null);
let pullToRefreshThresholdBreached: boolean = false;
let fetchMoreTresholdBreached: boolean = false; // if true, fetchMore loader is displayed
let isDragging: boolean = false;
let startY: number = 0;
let currentY: number = 0;
useEffect(() => {
if (!isPullable || !childrenRef || !childrenRef.current) return;
const childrenEl = childrenRef.current;
childrenEl.addEventListener('touchstart', onTouchStart, { passive: true });
childrenEl.addEventListener('mousedown', onTouchStart);
childrenEl.addEventListener('touchmove', onTouchMove, { passive: false });
childrenEl.addEventListener('mousemove', onTouchMove);
window.addEventListener('scroll', onScroll);
childrenEl.addEventListener('touchend', onEnd);
childrenEl.addEventListener('mouseup', onEnd);
document.body.addEventListener('mouseleave', onEnd);
return () => {
childrenEl.removeEventListener('touchstart', onTouchStart);
childrenEl.removeEventListener('mousedown', onTouchStart);
childrenEl.removeEventListener('touchmove', onTouchMove);
childrenEl.removeEventListener('mousemove', onTouchMove);
window.removeEventListener('scroll', onScroll);
childrenEl.removeEventListener('touchend', onEnd);
childrenEl.removeEventListener('mouseup', onEnd);
document.body.removeEventListener('mouseleave', onEnd);
};
}, [
children,
isPullable,
onRefresh,
pullDownThreshold,
maxPullDownDistance,
canFetchMore,
fetchMoreThreshold,
]);
/**
* Check onMount / canFetchMore becomes true
* if fetchMoreThreshold is already breached
*/
useEffect(() => {
/**
* Check if it is already in fetching more state
*/
if (!containerRef?.current) return;
const isAlreadyFetchingMore = containerRef.current.classList.contains(
'ptr--fetch-more-treshold-breached'
);
if (isAlreadyFetchingMore) return;
/**
* Proceed
*/
if (canFetchMore && getScrollToBottomValue() < fetchMoreThreshold && onFetchMore) {
containerRef.current.classList.add('ptr--fetch-more-treshold-breached');
fetchMoreTresholdBreached = true;
onFetchMore().then(initContainer).catch(initContainer);
}
}, [canFetchMore, children]);
/**
* Returns distance to bottom of the container
*/
const getScrollToBottomValue = (): number => {
if (!childrenRef || !childrenRef.current) return -1;
const scrollTop = window.scrollY; // is the pixels hidden in top due to the scroll. With no scroll its value is 0.
const scrollHeight = childrenRef.current.scrollHeight; // is the pixels of the whole container
return scrollHeight - scrollTop - window.innerHeight;
};
const initContainer = (): void => {
requestAnimationFrame(() => {
/**
* Reset Styles
*/
if (childrenRef.current) {
childrenRef.current.style.overflowX = 'hidden';
childrenRef.current.style.overflowY = 'auto';
childrenRef.current.style.transform = `unset`;
}
if (pullDownRef.current) {
pullDownRef.current.style.opacity = '0';
}
if (containerRef.current) {
containerRef.current.classList.remove('ptr--pull-down-treshold-breached');
containerRef.current.classList.remove('ptr--dragging');
containerRef.current.classList.remove('ptr--fetch-more-treshold-breached');
}
if (pullToRefreshThresholdBreached) pullToRefreshThresholdBreached = false;
if (fetchMoreTresholdBreached) fetchMoreTresholdBreached = false;
});
};
const onTouchStart = (e: MouseEvent | TouchEvent): void => {
isDragging = false;
if (e instanceof MouseEvent) {
startY = e.pageY;
}
if (window.TouchEvent && e instanceof TouchEvent) {
startY = e.touches[0].pageY;
}
currentY = startY;
// Check if element can be scrolled
if (e.type === 'touchstart' && isTreeScrollable(e.target as HTMLElement, DIRECTION.UP)) {
return;
}
// Top non visible so cancel
if (childrenRef.current!.getBoundingClientRect().top < 0) {
return;
}
isDragging = true;
};
const onTouchMove = (e: MouseEvent | TouchEvent): void => {
if (!isDragging) {
return;
}
if (window.TouchEvent && e instanceof TouchEvent) {
currentY = e.touches[0].pageY;
} else {
currentY = (e as MouseEvent).pageY;
}
containerRef.current!.classList.add('ptr--dragging');
if (currentY < startY) {
isDragging = false;
return;
}
if (e.cancelable) {
e.preventDefault();
}
const yDistanceMoved = Math.min((currentY - startY) / resistance, maxPullDownDistance);
// Limit to trigger refresh has been breached
if (yDistanceMoved >= pullDownThreshold) {
isDragging = true;
pullToRefreshThresholdBreached = true;
containerRef.current!.classList.remove('ptr--dragging');
containerRef.current!.classList.add('ptr--pull-down-treshold-breached');
}
// maxPullDownDistance breached, stop the animation
if (yDistanceMoved >= maxPullDownDistance) {
return;
}
pullDownRef.current!.style.opacity = ((yDistanceMoved) / 65).toString();
childrenRef.current!.style.overflow = 'visible';
childrenRef.current!.style.transform = `translate(0px, ${yDistanceMoved}px)`;
pullDownRef.current!.style.visibility = 'visible';
};
const onScroll = (e: Event): void => {
/**
* Check if component has already called onFetchMore
*/
if (fetchMoreTresholdBreached) return;
/**
* Check if user breached fetchMoreThreshold
*/
if (canFetchMore && getScrollToBottomValue() < fetchMoreThreshold && onFetchMore) {
fetchMoreTresholdBreached = true;
containerRef.current!.classList.add('ptr--fetch-more-treshold-breached');
onFetchMore().then(initContainer).catch(initContainer);
}
};
const onEnd = (): void => {
isDragging = false;
startY = 0;
currentY = 0;
// Container has not been dragged enough, put it back to it's initial state
if (!pullToRefreshThresholdBreached) {
if (pullDownRef.current) pullDownRef.current.style.visibility = 'hidden';
initContainer();
return;
}
if (childrenRef.current) {
childrenRef.current.style.overflow = 'visible';
childrenRef.current.style.transform = `translate(0px, ${pullDownThreshold}px)`;
}
onRefresh().then(initContainer).catch(initContainer);
};
return (
<div className={`ptr ${className}`} style={{ backgroundColor }} ref={containerRef}>
<div className="ptr__pull-down" ref={pullDownRef}>
<div className="ptr__loader ptr__pull-down--loading">{refreshingContent}</div>
<div className="ptr__pull-down--pull-more">{pullingContent}</div>
</div>
<div className="ptr__children" ref={childrenRef}>
{children}
<div className="ptr__fetch-more" ref={fetchMoreRef}>
<div className="ptr__loader ptr__fetch-more--loading">{refreshingContent}</div>
</div>
</div>
</div>
);
};
export default PullToRefresh;