-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.js
56 lines (47 loc) · 1.41 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
/**
* WordPress dependencies
*/
import { useSelect, useDispatch } from '@wordpress/data';
import { useRefEffect } from '@wordpress/compose';
/**
* Internal dependencies
*/
import { store as blockEditorStore } from '../../store';
/**
* Pass the returned ref callback to an element that should clear block
* selection. Selection will only be cleared if the element is clicked directly,
* not if a child element is clicked.
*
* @return {import('react').RefCallback} Ref callback.
*/
export function useBlockSelectionClearer() {
const { getSettings, hasSelectedBlock, hasMultiSelection } =
useSelect( blockEditorStore );
const { clearSelectedBlock } = useDispatch( blockEditorStore );
const { clearBlockSelection: isEnabled } = getSettings();
return useRefEffect(
( node ) => {
if ( ! isEnabled ) {
return;
}
function onMouseDown( event ) {
if ( ! hasSelectedBlock() && ! hasMultiSelection() ) {
return;
}
// Only handle clicks on the element, not the children.
if ( event.target !== node ) {
return;
}
clearSelectedBlock();
}
node.addEventListener( 'mousedown', onMouseDown );
return () => {
node.removeEventListener( 'mousedown', onMouseDown );
};
},
[ hasSelectedBlock, hasMultiSelection, clearSelectedBlock, isEnabled ]
);
}
export default function BlockSelectionClearer( props ) {
return <div ref={ useBlockSelectionClearer() } { ...props } />;
}