-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.js
74 lines (68 loc) · 2.18 KB
/
index.js
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
/**
* WordPress dependencies
*/
import { useCallback, useEffect, useRef, useState } from '@wordpress/element';
/**
* Internal dependencies
*/
import useIsomorphicLayoutEffect from '../use-isomorphic-layout-effect';
// Event handlers that are triggered from `document` listeners accept a MouseEvent,
// while those triggered from React listeners accept a React.MouseEvent.
/**
* @param {Object} props
* @param {(e: import('react').MouseEvent) => void} props.onDragStart
* @param {(e: MouseEvent) => void} props.onDragMove
* @param {(e?: MouseEvent) => void} props.onDragEnd
*/
export default function useDragging( { onDragStart, onDragMove, onDragEnd } ) {
const [ isDragging, setIsDragging ] = useState( false );
const eventsRef = useRef( {
onDragStart,
onDragMove,
onDragEnd,
} );
useIsomorphicLayoutEffect( () => {
eventsRef.current.onDragStart = onDragStart;
eventsRef.current.onDragMove = onDragMove;
eventsRef.current.onDragEnd = onDragEnd;
}, [ onDragStart, onDragMove, onDragEnd ] );
/** @type {(e: MouseEvent) => void} */
const onMouseMove = useCallback(
( event ) =>
eventsRef.current.onDragMove &&
eventsRef.current.onDragMove( event ),
[]
);
/** @type {(e?: MouseEvent) => void} */
const endDrag = useCallback( ( event ) => {
if ( eventsRef.current.onDragEnd ) {
eventsRef.current.onDragEnd( event );
}
document.removeEventListener( 'mousemove', onMouseMove );
document.removeEventListener( 'mouseup', endDrag );
setIsDragging( false );
}, [] );
/** @type {(e: import('react').MouseEvent) => void} */
const startDrag = useCallback( ( event ) => {
if ( eventsRef.current.onDragStart ) {
eventsRef.current.onDragStart( event );
}
document.addEventListener( 'mousemove', onMouseMove );
document.addEventListener( 'mouseup', endDrag );
setIsDragging( true );
}, [] );
// Remove the global events when unmounting if needed.
useEffect( () => {
return () => {
if ( isDragging ) {
document.removeEventListener( 'mousemove', onMouseMove );
document.removeEventListener( 'mouseup', endDrag );
}
};
}, [ isDragging ] );
return {
startDrag,
endDrag,
isDragging,
};
}