Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

86 строки
2.5 KiB

  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. import { useRef } from 'react';
  3. import useMounted from './useMounted';
  4. import useEventCallback from './useEventCallback';
  5. var isSyntheticEvent = function isSyntheticEvent(event) {
  6. return typeof event.persist === 'function';
  7. };
  8. /**
  9. * Creates a event handler function throttled by `requestAnimationFrame` that
  10. * returns the **most recent** event. Useful for noisy events that update react state.
  11. *
  12. * ```tsx
  13. * function Component() {
  14. * const [position, setPosition] = useState();
  15. * const handleMove = useThrottledEventHandler<React.PointerEvent>(
  16. * (event) => {
  17. * setPosition({
  18. * top: event.clientX,
  19. * left: event.clientY,
  20. * })
  21. * }
  22. * )
  23. *
  24. * return (
  25. * <div onPointerMove={handleMove}>
  26. * <div style={position} />
  27. * </div>
  28. * );
  29. * }
  30. * ```
  31. *
  32. * @param handler An event handler function
  33. * @typeParam TEvent The event object passed to the handler function
  34. * @returns The event handler with a `clear` method attached for clearing any in-flight handler calls
  35. *
  36. */
  37. export default function useThrottledEventHandler(handler) {
  38. var isMounted = useMounted();
  39. var eventHandler = useEventCallback(handler);
  40. var nextEventInfoRef = useRef({
  41. event: null,
  42. handle: null
  43. });
  44. var clear = function clear() {
  45. cancelAnimationFrame(nextEventInfoRef.current.handle);
  46. nextEventInfoRef.current.handle = null;
  47. };
  48. var handlePointerMoveAnimation = function handlePointerMoveAnimation() {
  49. var next = nextEventInfoRef.current;
  50. if (next.handle && next.event) {
  51. if (isMounted()) {
  52. next.handle = null;
  53. eventHandler(next.event);
  54. }
  55. }
  56. next.event = null;
  57. };
  58. var throttledHandler = function throttledHandler(event) {
  59. if (!isMounted()) return;
  60. if (isSyntheticEvent(event)) {
  61. event.persist();
  62. } // Special handling for a React.Konva event which reuses the
  63. // event object as it bubbles, setting target
  64. else if ('evt' in event) {
  65. event = _extends({}, 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. }