/
index.js
57 lines (47 loc) · 1.29 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
/**
* External dependencies
*/
import { overEvery, findLast } from 'lodash';
/**
* WordPress dependencies
*/
import { useRefEffect } from '@wordpress/compose';
import { focus, isTextField, placeCaretAtHorizontalEdge } from '@wordpress/dom';
/**
* Given an element, returns true if the element is a tabbable text field, or
* false otherwise.
*
* @param {Element} element Element to test.
*
* @return {boolean} Whether element is a tabbable text field.
*/
const isTabbableTextField = overEvery( [
isTextField,
focus.tabbable.isTabbableIndex,
] );
export function useCanvasClickRedirect() {
return useRefEffect( ( node ) => {
function onMouseDown( event ) {
// Only handle clicks on the canvas, not the content.
if ( event.target !== node ) {
return;
}
const focusableNodes = focus.focusable.find( node );
const target = findLast( focusableNodes, isTabbableTextField );
if ( ! target ) {
return;
}
const { bottom } = target.getBoundingClientRect();
// Ensure the click is below the last block.
if ( event.clientY < bottom ) {
return;
}
placeCaretAtHorizontalEdge( target, true );
event.preventDefault();
}
node.addEventListener( 'mousedown', onMouseDown );
return () => {
node.addEventListener( 'mousedown', onMouseDown );
};
}, [] );
}