-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.js
101 lines (87 loc) · 2.28 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
* External dependencies
*/
import { cond, matchesProperty } from 'lodash';
/**
* WordPress dependencies
*/
import { NavigableMenu, KeyboardShortcuts } from '@wordpress/components';
import { Component, findDOMNode } from '@wordpress/element';
import { focus } from '@wordpress/dom';
import { keycodes } from '@wordpress/utils';
/**
* Browser dependencies
*/
const { Node, getSelection } = window;
/**
* Module Constants
*/
const { ESCAPE } = keycodes;
class NavigableToolbar extends Component {
constructor() {
super( ...arguments );
this.bindNode = this.bindNode.bind( this );
this.focusToolbar = this.focusToolbar.bind( this );
this.focusSelection = this.focusSelection.bind( this );
this.switchOnKeyDown = cond( [
[ matchesProperty( [ 'keyCode' ], ESCAPE ), this.focusSelection ],
] );
}
bindNode( ref ) {
// Disable reason: Need DOM node for finding first focusable element
// on keyboard interaction to shift to toolbar.
// eslint-disable-next-line react/no-find-dom-node
this.toolbar = findDOMNode( ref );
}
focusToolbar() {
const tabbables = focus.tabbable.find( this.toolbar );
if ( tabbables.length ) {
tabbables[ 0 ].focus();
}
}
/**
* Programmatically shifts focus to the element where the current selection
* exists, if there is a selection.
*/
focusSelection() {
// Ensure that a selection exists.
const selection = getSelection();
if ( ! selection ) {
return;
}
// Focus node may be a text node, which cannot be focused directly.
// Find its parent element instead.
const { focusNode } = selection;
let focusElement = focusNode;
if ( focusElement.nodeType !== Node.ELEMENT_NODE ) {
focusElement = focusElement.parentElement;
}
if ( focusElement ) {
focusElement.focus();
}
}
render() {
const { children, ...props } = this.props;
return (
<NavigableMenu
orientation="horizontal"
role="toolbar"
deep
ref={ this.bindNode }
onKeyDown={ this.switchOnKeyDown }
{ ...props }
>
<KeyboardShortcuts
bindGlobal
// Use the same event that TinyMCE uses in the Classic block for its own `alt+f10` shortcut.
eventName="keydown"
shortcuts={ {
'alt+f10': this.focusToolbar,
} }
/>
{ children }
</NavigableMenu>
);
}
}
export default NavigableToolbar;