-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
use-shortcut.js
49 lines (43 loc) · 1.08 KB
/
use-shortcut.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
/**
* WordPress dependencies
*/
import { useContext, useEffect, useRef } from '@wordpress/element';
/**
* Internal dependencies
*/
import useShortcutEventMatch from './use-shortcut-event-match';
import { context } from '../context';
/**
* Attach a keyboard shortcut handler.
*
* @param {string} name Shortcut name.
* @param {Function} callback Shortcut callback.
* @param {Object} options Shortcut options.
* @param {boolean} options.isDisabled Whether to disable to shortut.
*/
export default function useShortcut(
name,
callback,
{ isDisabled = false } = {}
) {
const shortcuts = useContext( context );
const isMatch = useShortcutEventMatch();
const callbackRef = useRef();
useEffect( () => {
callbackRef.current = callback;
}, [ callback ] );
useEffect( () => {
if ( isDisabled ) {
return;
}
function _callback( event ) {
if ( isMatch( name, event ) ) {
callbackRef.current( event );
}
}
shortcuts.add( _callback );
return () => {
shortcuts.delete( _callback );
};
}, [ name, isDisabled, shortcuts ] );
}