useDomMotionEvents.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import * as React from 'react';
  2. import { useRef } from 'react';
  3. import { animationEndName, transitionEndName } from "../util/motion";
  4. export default (function (onInternalMotionEnd) {
  5. var cacheElementRef = useRef();
  6. // Remove events
  7. function removeMotionEvents(element) {
  8. if (element) {
  9. element.removeEventListener(transitionEndName, onInternalMotionEnd);
  10. element.removeEventListener(animationEndName, onInternalMotionEnd);
  11. }
  12. }
  13. // Patch events
  14. function patchMotionEvents(element) {
  15. if (cacheElementRef.current && cacheElementRef.current !== element) {
  16. removeMotionEvents(cacheElementRef.current);
  17. }
  18. if (element && element !== cacheElementRef.current) {
  19. element.addEventListener(transitionEndName, onInternalMotionEnd);
  20. element.addEventListener(animationEndName, onInternalMotionEnd);
  21. // Save as cache in case dom removed trigger by `motionDeadline`
  22. cacheElementRef.current = element;
  23. }
  24. }
  25. // Clean up when removed
  26. React.useEffect(function () {
  27. return function () {
  28. removeMotionEvents(cacheElementRef.current);
  29. };
  30. }, []);
  31. return [patchMotionEvents, removeMotionEvents];
  32. });