1 | function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
|
2 |
|
3 | import { useRef } from 'react';
|
4 | import useMounted from './useMounted';
|
5 | import useEventCallback from './useEventCallback';
|
6 |
|
7 | var isSyntheticEvent = function isSyntheticEvent(event) {
|
8 | return typeof event.persist === 'function';
|
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 | export default function useThrottledEventHandler(handler) {
|
41 | var isMounted = useMounted();
|
42 | var eventHandler = useEventCallback(handler);
|
43 | var nextEventInfoRef = useRef({
|
44 | event: null,
|
45 | handle: null
|
46 | });
|
47 |
|
48 | var clear = function clear() {
|
49 | cancelAnimationFrame(nextEventInfoRef.current.handle);
|
50 | nextEventInfoRef.current.handle = null;
|
51 | };
|
52 |
|
53 | var handlePointerMoveAnimation = function handlePointerMoveAnimation() {
|
54 | var next = nextEventInfoRef.current;
|
55 |
|
56 | if (next.handle && next.event) {
|
57 | if (isMounted()) {
|
58 | next.handle = null;
|
59 | eventHandler(next.event);
|
60 | }
|
61 | }
|
62 |
|
63 | next.event = null;
|
64 | };
|
65 |
|
66 | var throttledHandler = function throttledHandler(event) {
|
67 | if (!isMounted()) return;
|
68 |
|
69 | if (isSyntheticEvent(event)) {
|
70 | event.persist();
|
71 | }
|
72 |
|
73 | else if ('evt' in event) {
|
74 | event = _extends({}, event);
|
75 | }
|
76 |
|
77 | nextEventInfoRef.current.event = event;
|
78 |
|
79 | if (!nextEventInfoRef.current.handle) {
|
80 | nextEventInfoRef.current.handle = requestAnimationFrame(handlePointerMoveAnimation);
|
81 | }
|
82 | };
|
83 |
|
84 | throttledHandler.clear = clear;
|
85 | return throttledHandler;
|
86 | } |
\ | No newline at end of file |