1 | import { useRef } from 'react';
|
2 | import useMounted from './useMounted';
|
3 | import useEventCallback from './useEventCallback';
|
4 | const isSyntheticEvent = event => typeof event.persist === 'function';
|
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 | export default function useThrottledEventHandler(handler) {
|
35 | const isMounted = useMounted();
|
36 | const eventHandler = useEventCallback(handler);
|
37 | const nextEventInfoRef = useRef({
|
38 | event: null,
|
39 | handle: null
|
40 | });
|
41 | const clear = () => {
|
42 | cancelAnimationFrame(nextEventInfoRef.current.handle);
|
43 | nextEventInfoRef.current.handle = null;
|
44 | };
|
45 | const handlePointerMoveAnimation = () => {
|
46 | const {
|
47 | current: next
|
48 | } = nextEventInfoRef;
|
49 | if (next.handle && next.event) {
|
50 | if (isMounted()) {
|
51 | next.handle = null;
|
52 | eventHandler(next.event);
|
53 | }
|
54 | }
|
55 | next.event = null;
|
56 | };
|
57 | const throttledHandler = event => {
|
58 | if (!isMounted()) return;
|
59 | if (isSyntheticEvent(event)) {
|
60 | event.persist();
|
61 | }
|
62 |
|
63 |
|
64 | else if ('evt' in event) {
|
65 | event = Object.assign({}, event);
|
66 | }
|
67 | nextEventInfoRef.current.event = event;
|
68 | if (!nextEventInfoRef.current.handle) {
|
69 | nextEventInfoRef.current.handle = requestAnimationFrame(handlePointerMoveAnimation);
|
70 | }
|
71 | };
|
72 | throttledHandler.clear = clear;
|
73 | return throttledHandler;
|
74 | } |
\ | No newline at end of file |