-
Notifications
You must be signed in to change notification settings - Fork 184
/
Copy pathPullToRefresh.tsx
290 lines (255 loc) · 9.88 KB
/
PullToRefresh.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
import * as React from 'react';
import { classNames } from '@vkontakte/vkjs';
import { clamp } from '../../helpers/math';
import { usePlatform } from '../../hooks/usePlatform';
import { usePrevious } from '../../hooks/usePrevious';
import { DOMProps, useDOM } from '../../lib/dom';
import { useIsomorphicLayoutEffect } from '../../lib/useIsomorphicLayoutEffect';
import { AnyFunction, HasChildren } from '../../types';
import { ScrollContextInterface, useScroll } from '../AppRoot/ScrollContext';
import { FixedLayout } from '../FixedLayout/FixedLayout';
import { Touch, TouchEvent as TouchEventInternal, TouchProps } from '../Touch/Touch';
import TouchRootContext from '../Touch/TouchContext';
import { PullToRefreshSpinner } from './PullToRefreshSpinner';
import styles from './PullToRefresh.module.css';
const WAIT_FETCHING_TIMEOUT_MS = 1000;
function cancelEvent(event: TouchEventInternal) {
/* istanbul ignore if: неясно в какой ситуации `event` из `Touch` может быть не определён */
if (!event) {
return false;
}
if ('preventDefault' in event.originalEvent && event.originalEvent.cancelable) {
event.originalEvent.preventDefault();
}
if ('stopPropagation' in event.originalEvent) {
event.originalEvent.stopPropagation();
}
return false;
}
export interface PullToRefreshProps extends DOMProps, TouchProps, HasChildren {
/**
* Будет вызвана для обновления контента (прим.: функция должна быть мемоизированным коллбэком)
*/
onRefresh: AnyFunction;
/**
* Определяет, выполняется ли обновление. Для скрытия спиннера после получения контента необходимо передать `false`
*/
isFetching?: boolean;
/** @ignore */
scroll?: ScrollContextInterface;
}
/**
* @see https://vkcom.github.io/VKUI/#/PullToRefresh
*/
export const PullToRefresh = ({
children,
isFetching,
onRefresh,
className,
...restProps
}: PullToRefreshProps) => {
const platform = usePlatform();
const scroll = useScroll();
const { window, document } = useDOM();
const prevIsFetching = usePrevious(isFetching);
const initParams = React.useMemo(
() => ({
start: platform === 'ios' ? -10 : -45,
max: platform === 'ios' ? 50 : 80,
maxY: platform === 'ios' ? 400 : 80,
refreshing: platform === 'ios' ? 36 : 50,
positionMultiplier: platform === 'ios' ? 0.21 : 1,
}),
[platform],
);
const [spinnerY, setSpinnerY] = React.useState(initParams.start);
const [watching, setWatching] = React.useState(false);
const [refreshing, setRefreshing] = React.useState(false);
const [canRefresh, setCanRefresh] = React.useState(false);
const [touchDown, setTouchDown] = React.useState(false);
const prevTouchDown = usePrevious(touchDown);
const touchY = React.useRef(0);
const [contentShift, setContentShift] = React.useState(0);
const [spinnerProgress, setSpinnerProgress] = React.useState(0);
const resetRefreshingState = React.useCallback(() => {
setWatching(false);
setCanRefresh(false);
setRefreshing(false);
setSpinnerY(initParams.start);
setSpinnerProgress(0);
setContentShift(0);
}, [initParams]);
const onRefreshingFinish = React.useCallback(() => {
if (!touchDown) {
resetRefreshingState();
}
}, [touchDown, resetRefreshingState]);
const waitFetchingTimeoutId = React.useRef<NodeJS.Timeout>();
useIsomorphicLayoutEffect(() => {
if (prevIsFetching !== undefined && prevIsFetching && !isFetching) {
onRefreshingFinish();
}
}, [prevIsFetching, isFetching, onRefreshingFinish]);
useIsomorphicLayoutEffect(() => {
if (prevIsFetching !== undefined && !prevIsFetching && isFetching) {
clearTimeout(waitFetchingTimeoutId.current);
}
}, [isFetching, prevIsFetching]);
const runRefreshing = React.useCallback(() => {
if (!refreshing && onRefresh) {
// cleanup if the consumer does not start fetching in 1s
clearTimeout(waitFetchingTimeoutId.current);
waitFetchingTimeoutId.current = setTimeout(onRefreshingFinish, WAIT_FETCHING_TIMEOUT_MS);
setRefreshing(true);
setSpinnerY((prevSpinnerY) => (platform === 'ios' ? prevSpinnerY : initParams.refreshing));
onRefresh();
}
}, [refreshing, onRefresh, onRefreshingFinish, platform, initParams.refreshing]);
useIsomorphicLayoutEffect(() => {
if (prevTouchDown !== undefined && prevTouchDown && !touchDown) {
if (!refreshing && canRefresh) {
runRefreshing();
} else if (refreshing && !isFetching) {
// only iOS can start refresh before gesture end
resetRefreshingState();
/* istanbul ignore if: TODO написать тест */
} else {
// refreshing && isFetching: refresh in progress
// OR !refreshing && !canRefresh: pull was not strong enough
setSpinnerY(refreshing ? initParams.refreshing : initParams.start);
setSpinnerProgress(0);
setContentShift(0);
}
}
}, [
initParams,
prevIsFetching,
isFetching,
onRefreshingFinish,
prevTouchDown,
touchDown,
refreshing,
canRefresh,
runRefreshing,
]);
useIsomorphicLayoutEffect(
function toggleBodyOverscrollBehavior() {
/* istanbul ignore if: невозможный кейс, т.к. в SSR эффекты не вызываются. Проверка на будущее, если вдруг эффект будет вызываться. */
if (!window || !document) {
return;
}
/**
* ⚠️ В частности, необходимо для iOS 15. Начиная с этой версии в Safari добавили
* pull-to-refresh. CSS св-во `overflow-behavior` появился только с iOS 16.
*
* Во вторую очередь, полезна блокированием скролла, чтобы пользователь дождался обновления
* данных.
*/
/* istanbul ignore next: в jest не протестировать */
const handleWindowTouchMoveForPreventIOSViewportBounce = (event: TouchEvent) => {
event.preventDefault();
event.stopPropagation();
};
if (watching || refreshing) {
// eslint-disable-next-line no-restricted-properties
document.documentElement.classList.add('vkui--disable-overscroll-behavior');
/* istanbul ignore next: в jest не протестировать */
window.addEventListener('touchmove', handleWindowTouchMoveForPreventIOSViewportBounce, {
passive: false,
});
}
return () => {
// eslint-disable-next-line no-restricted-properties
document.documentElement.classList.remove('vkui--disable-overscroll-behavior');
/* istanbul ignore next: в jest не протестировать */
window.removeEventListener('touchmove', handleWindowTouchMoveForPreventIOSViewportBounce);
};
},
[window, document, watching, refreshing],
);
const startYRef = React.useRef(0);
const onTouchStart = (event: TouchEventInternal) => {
if (refreshing) {
cancelEvent(event);
return;
}
setTouchDown(true);
startYRef.current = event.startY;
};
const onTouchMove = (event: TouchEventInternal) => {
const { isY, shiftY } = event;
const { start, max } = initParams;
const pageYOffset = scroll?.getScroll().y;
if (watching && touchDown) {
cancelEvent(event);
const { positionMultiplier, maxY } = initParams;
const shift = Math.max(0, shiftY - touchY.current);
const currentY = clamp(start + shift * positionMultiplier, start, maxY);
const progress = currentY > -10 ? Math.abs((currentY + 10) / max) * 80 : 0;
setSpinnerY(currentY);
setSpinnerProgress(clamp(progress, 0, 80));
setCanRefresh(progress > 80);
setContentShift((currentY + 10) * 2.3);
if (progress > 85 && !refreshing && platform === 'ios') {
runRefreshing();
}
} else if (isY && pageYOffset === 0 && shiftY > 0 && !refreshing && touchDown) {
cancelEvent(event);
touchY.current = shiftY;
setWatching(true);
setSpinnerY(start);
setSpinnerProgress(0);
}
};
const onTouchEnd = () => {
setWatching(false);
setTouchDown(false);
};
const spinnerTransform = `translate3d(0, ${spinnerY}px, 0)`;
let contentTransform = '';
if (platform === 'ios' && refreshing && !touchDown) {
contentTransform = 'translate3d(0, 100px, 0)';
} else if (platform === 'ios' && (contentShift || refreshing)) {
contentTransform = `translate3d(0, ${contentShift}px, 0)`;
}
return (
<TouchRootContext.Provider value={true}>
<Touch
aria-live="polite"
aria-busy={!!isFetching}
{...restProps}
onStart={onTouchStart}
onMove={onTouchMove}
onEnd={onTouchEnd}
className={classNames(
styles['PullToRefresh'],
platform === 'ios' && styles['PullToRefresh--ios'],
watching && styles['PullToRefresh--watching'],
refreshing && styles['PullToRefresh--refreshing'],
className,
)}
>
<FixedLayout className={styles['PullToRefresh__controls']} useParentWidth>
<PullToRefreshSpinner
style={{
transform: spinnerTransform,
WebkitTransform: spinnerTransform,
opacity: watching || refreshing || canRefresh ? 1 : 0,
}}
on={refreshing}
progress={refreshing ? undefined : spinnerProgress}
/>
</FixedLayout>
<div
className={styles['PullToRefresh__content']}
style={{
transform: contentTransform,
WebkitTransform: contentTransform,
}}
>
{children}
</div>
</Touch>
</TouchRootContext.Provider>
);
};